1/******************************************************************************
2** This file is an amalgamation of many separate C source files from SQLite
3** version 3.7.6.3.  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 number of samples of an index that SQLite takes in order to
321** construct a histogram of the table content when running ANALYZE
322** and with SQLITE_ENABLE_STAT2
323*/
324#define SQLITE_INDEX_SAMPLES 10
325
326/*
327** The following macros are used to cast pointers to integers and
328** integers to pointers.  The way you do this varies from one compiler
329** to the next, so we have developed the following set of #if statements
330** to generate appropriate macros for a wide range of compilers.
331**
332** The correct "ANSI" way to do this is to use the intptr_t type.
333** Unfortunately, that typedef is not available on all compilers, or
334** if it is available, it requires an #include of specific headers
335** that vary from one machine to the next.
336**
337** Ticket #3860:  The llvm-gcc-4.2 compiler from Apple chokes on
338** the ((void*)&((char*)0)[X]) construct.  But MSVC chokes on ((void*)(X)).
339** So we have to define the macros in different ways depending on the
340** compiler.
341*/
342#if defined(__PTRDIFF_TYPE__)  /* This case should work for GCC */
343# define SQLITE_INT_TO_PTR(X)  ((void*)(__PTRDIFF_TYPE__)(X))
344# define SQLITE_PTR_TO_INT(X)  ((int)(__PTRDIFF_TYPE__)(X))
345#elif !defined(__GNUC__)       /* Works for compilers other than LLVM */
346# define SQLITE_INT_TO_PTR(X)  ((void*)&((char*)0)[X])
347# define SQLITE_PTR_TO_INT(X)  ((int)(((char*)X)-(char*)0))
348#elif defined(HAVE_STDINT_H)   /* Use this case if we have ANSI headers */
349# define SQLITE_INT_TO_PTR(X)  ((void*)(intptr_t)(X))
350# define SQLITE_PTR_TO_INT(X)  ((int)(intptr_t)(X))
351#else                          /* Generates a warning - but it always works */
352# define SQLITE_INT_TO_PTR(X)  ((void*)(X))
353# define SQLITE_PTR_TO_INT(X)  ((int)(X))
354#endif
355
356/*
357** The SQLITE_THREADSAFE macro must be defined as 0, 1, or 2.
358** 0 means mutexes are permanently disable and the library is never
359** threadsafe.  1 means the library is serialized which is the highest
360** level of threadsafety.  2 means the libary is multithreaded - multiple
361** threads can use SQLite as long as no two threads try to use the same
362** database connection at the same time.
363**
364** Older versions of SQLite used an optional THREADSAFE macro.
365** We support that for legacy.
366*/
367#if !defined(SQLITE_THREADSAFE)
368#if defined(THREADSAFE)
369# define SQLITE_THREADSAFE THREADSAFE
370#else
371# define SQLITE_THREADSAFE 1 /* IMP: R-07272-22309 */
372#endif
373#endif
374
375/*
376** The SQLITE_DEFAULT_MEMSTATUS macro must be defined as either 0 or 1.
377** It determines whether or not the features related to
378** SQLITE_CONFIG_MEMSTATUS are available by default or not. This value can
379** be overridden at runtime using the sqlite3_config() API.
380*/
381#if !defined(SQLITE_DEFAULT_MEMSTATUS)
382# define SQLITE_DEFAULT_MEMSTATUS 1
383#endif
384
385/*
386** Exactly one of the following macros must be defined in order to
387** specify which memory allocation subsystem to use.
388**
389**     SQLITE_SYSTEM_MALLOC          // Use normal system malloc()
390**     SQLITE_MEMDEBUG               // Debugging version of system malloc()
391**
392** (Historical note:  There used to be several other options, but we've
393** pared it down to just these two.)
394**
395** If none of the above are defined, then set SQLITE_SYSTEM_MALLOC as
396** the default.
397*/
398#if defined(SQLITE_SYSTEM_MALLOC)+defined(SQLITE_MEMDEBUG)>1
399# error "At most one of the following compile-time configuration options\
400 is allows: SQLITE_SYSTEM_MALLOC, SQLITE_MEMDEBUG"
401#endif
402#if defined(SQLITE_SYSTEM_MALLOC)+defined(SQLITE_MEMDEBUG)==0
403# define SQLITE_SYSTEM_MALLOC 1
404#endif
405
406/*
407** If SQLITE_MALLOC_SOFT_LIMIT is not zero, then try to keep the
408** sizes of memory allocations below this value where possible.
409*/
410#if !defined(SQLITE_MALLOC_SOFT_LIMIT)
411# define SQLITE_MALLOC_SOFT_LIMIT 1024
412#endif
413
414/*
415** We need to define _XOPEN_SOURCE as follows in order to enable
416** recursive mutexes on most Unix systems.  But Mac OS X is different.
417** The _XOPEN_SOURCE define causes problems for Mac OS X we are told,
418** so it is omitted there.  See ticket #2673.
419**
420** Later we learn that _XOPEN_SOURCE is poorly or incorrectly
421** implemented on some systems.  So we avoid defining it at all
422** if it is already defined or if it is unneeded because we are
423** not doing a threadsafe build.  Ticket #2681.
424**
425** See also ticket #2741.
426*/
427#if !defined(_XOPEN_SOURCE) && !defined(__DARWIN__) && !defined(__APPLE__) && SQLITE_THREADSAFE
428#  define _XOPEN_SOURCE 500  /* Needed to enable pthread recursive mutexes */
429#endif
430
431/*
432** The TCL headers are only needed when compiling the TCL bindings.
433*/
434#if defined(SQLITE_TCL) || defined(TCLSH)
435# include <tcl.h>
436#endif
437
438/*
439** Many people are failing to set -DNDEBUG=1 when compiling SQLite.
440** Setting NDEBUG makes the code smaller and run faster.  So the following
441** lines are added to automatically set NDEBUG unless the -DSQLITE_DEBUG=1
442** option is set.  Thus NDEBUG becomes an opt-in rather than an opt-out
443** feature.
444*/
445#if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
446# define NDEBUG 1
447#endif
448
449/*
450** The testcase() macro is used to aid in coverage testing.  When
451** doing coverage testing, the condition inside the argument to
452** testcase() must be evaluated both true and false in order to
453** get full branch coverage.  The testcase() macro is inserted
454** to help ensure adequate test coverage in places where simple
455** condition/decision coverage is inadequate.  For example, testcase()
456** can be used to make sure boundary values are tested.  For
457** bitmask tests, testcase() can be used to make sure each bit
458** is significant and used at least once.  On switch statements
459** where multiple cases go to the same block of code, testcase()
460** can insure that all cases are evaluated.
461**
462*/
463#ifdef SQLITE_COVERAGE_TEST
464SQLITE_PRIVATE   void sqlite3Coverage(int);
465# define testcase(X)  if( X ){ sqlite3Coverage(__LINE__); }
466#else
467# define testcase(X)
468#endif
469
470/*
471** The TESTONLY macro is used to enclose variable declarations or
472** other bits of code that are needed to support the arguments
473** within testcase() and assert() macros.
474*/
475#if !defined(NDEBUG) || defined(SQLITE_COVERAGE_TEST)
476# define TESTONLY(X)  X
477#else
478# define TESTONLY(X)
479#endif
480
481/*
482** Sometimes we need a small amount of code such as a variable initialization
483** to setup for a later assert() statement.  We do not want this code to
484** appear when assert() is disabled.  The following macro is therefore
485** used to contain that setup code.  The "VVA" acronym stands for
486** "Verification, Validation, and Accreditation".  In other words, the
487** code within VVA_ONLY() will only run during verification processes.
488*/
489#ifndef NDEBUG
490# define VVA_ONLY(X)  X
491#else
492# define VVA_ONLY(X)
493#endif
494
495/*
496** The ALWAYS and NEVER macros surround boolean expressions which
497** are intended to always be true or false, respectively.  Such
498** expressions could be omitted from the code completely.  But they
499** are included in a few cases in order to enhance the resilience
500** of SQLite to unexpected behavior - to make the code "self-healing"
501** or "ductile" rather than being "brittle" and crashing at the first
502** hint of unplanned behavior.
503**
504** In other words, ALWAYS and NEVER are added for defensive code.
505**
506** When doing coverage testing ALWAYS and NEVER are hard-coded to
507** be true and false so that the unreachable code then specify will
508** not be counted as untested code.
509*/
510#if defined(SQLITE_COVERAGE_TEST)
511# define ALWAYS(X)      (1)
512# define NEVER(X)       (0)
513#elif !defined(NDEBUG)
514# define ALWAYS(X)      ((X)?1:(assert(0),0))
515# define NEVER(X)       ((X)?(assert(0),1):0)
516#else
517# define ALWAYS(X)      (X)
518# define NEVER(X)       (X)
519#endif
520
521/*
522** Return true (non-zero) if the input is a integer that is too large
523** to fit in 32-bits.  This macro is used inside of various testcase()
524** macros to verify that we have tested SQLite for large-file support.
525*/
526#define IS_BIG_INT(X)  (((X)&~(i64)0xffffffff)!=0)
527
528/*
529** The macro unlikely() is a hint that surrounds a boolean
530** expression that is usually false.  Macro likely() surrounds
531** a boolean expression that is usually true.  GCC is able to
532** use these hints to generate better code, sometimes.
533*/
534#if defined(__GNUC__) && 0
535# define likely(X)    __builtin_expect((X),1)
536# define unlikely(X)  __builtin_expect((X),0)
537#else
538# define likely(X)    !!(X)
539# define unlikely(X)  !!(X)
540#endif
541
542/************** Include sqlite3.h in the middle of sqliteInt.h ***************/
543/************** Begin file sqlite3.h *****************************************/
544/*
545** 2001 September 15
546**
547** The author disclaims copyright to this source code.  In place of
548** a legal notice, here is a blessing:
549**
550**    May you do good and not evil.
551**    May you find forgiveness for yourself and forgive others.
552**    May you share freely, never taking more than you give.
553**
554*************************************************************************
555** This header file defines the interface that the SQLite library
556** presents to client programs.  If a C-function, structure, datatype,
557** or constant definition does not appear in this file, then it is
558** not a published API of SQLite, is subject to change without
559** notice, and should not be referenced by programs that use SQLite.
560**
561** Some of the definitions that are in this file are marked as
562** "experimental".  Experimental interfaces are normally new
563** features recently added to SQLite.  We do not anticipate changes
564** to experimental interfaces but reserve the right to make minor changes
565** if experience from use "in the wild" suggest such changes are prudent.
566**
567** The official C-language API documentation for SQLite is derived
568** from comments in this file.  This file is the authoritative source
569** on how SQLite interfaces are suppose to operate.
570**
571** The name of this file under configuration management is "sqlite.h.in".
572** The makefile makes some minor changes to this file (such as inserting
573** the version number) and changes its name to "sqlite3.h" as
574** part of the build process.
575*/
576#ifndef _SQLITE3_H_
577#define _SQLITE3_H_
578#include <stdarg.h>     /* Needed for the definition of va_list */
579
580/*
581** Make sure we can call this stuff from C++.
582*/
583#if 0
584extern "C" {
585#endif
586
587
588/*
589** Add the ability to override 'extern'
590*/
591#ifndef SQLITE_EXTERN
592# define SQLITE_EXTERN extern
593#endif
594
595#ifndef SQLITE_API
596# define SQLITE_API
597#endif
598
599
600/*
601** These no-op macros are used in front of interfaces to mark those
602** interfaces as either deprecated or experimental.  New applications
603** should not use deprecated interfaces - they are support for backwards
604** compatibility only.  Application writers should be aware that
605** experimental interfaces are subject to change in point releases.
606**
607** These macros used to resolve to various kinds of compiler magic that
608** would generate warning messages when they were used.  But that
609** compiler magic ended up generating such a flurry of bug reports
610** that we have taken it all out and gone back to using simple
611** noop macros.
612*/
613#define SQLITE_DEPRECATED
614#define SQLITE_EXPERIMENTAL
615
616/*
617** Ensure these symbols were not defined by some previous header file.
618*/
619#ifdef SQLITE_VERSION
620# undef SQLITE_VERSION
621#endif
622#ifdef SQLITE_VERSION_NUMBER
623# undef SQLITE_VERSION_NUMBER
624#endif
625
626/*
627** CAPI3REF: Compile-Time Library Version Numbers
628**
629** ^(The [SQLITE_VERSION] C preprocessor macro in the sqlite3.h header
630** evaluates to a string literal that is the SQLite version in the
631** format "X.Y.Z" where X is the major version number (always 3 for
632** SQLite3) and Y is the minor version number and Z is the release number.)^
633** ^(The [SQLITE_VERSION_NUMBER] C preprocessor macro resolves to an integer
634** with the value (X*1000000 + Y*1000 + Z) where X, Y, and Z are the same
635** numbers used in [SQLITE_VERSION].)^
636** The SQLITE_VERSION_NUMBER for any given release of SQLite will also
637** be larger than the release from which it is derived.  Either Y will
638** be held constant and Z will be incremented or else Y will be incremented
639** and Z will be reset to zero.
640**
641** Since version 3.6.18, SQLite source code has been stored in the
642** <a href="http://www.fossil-scm.org/">Fossil configuration management
643** system</a>.  ^The SQLITE_SOURCE_ID macro evaluates to
644** a string which identifies a particular check-in of SQLite
645** within its configuration management system.  ^The SQLITE_SOURCE_ID
646** string contains the date and time of the check-in (UTC) and an SHA1
647** hash of the entire source tree.
648**
649** See also: [sqlite3_libversion()],
650** [sqlite3_libversion_number()], [sqlite3_sourceid()],
651** [sqlite_version()] and [sqlite_source_id()].
652*/
653#define SQLITE_VERSION        "3.7.6.3"
654#define SQLITE_VERSION_NUMBER 3007006
655#define SQLITE_SOURCE_ID      "2011-05-19 13:26:54 ed1da510a239ea767a01dc332b667119fa3c908e"
656
657/*
658** CAPI3REF: Run-Time Library Version Numbers
659** KEYWORDS: sqlite3_version, sqlite3_sourceid
660**
661** These interfaces provide the same information as the [SQLITE_VERSION],
662** [SQLITE_VERSION_NUMBER], and [SQLITE_SOURCE_ID] C preprocessor macros
663** but are associated with the library instead of the header file.  ^(Cautious
664** programmers might include assert() statements in their application to
665** verify that values returned by these interfaces match the macros in
666** the header, and thus insure that the application is
667** compiled with matching library and header files.
668**
669** <blockquote><pre>
670** assert( sqlite3_libversion_number()==SQLITE_VERSION_NUMBER );
671** assert( strcmp(sqlite3_sourceid(),SQLITE_SOURCE_ID)==0 );
672** assert( strcmp(sqlite3_libversion(),SQLITE_VERSION)==0 );
673** </pre></blockquote>)^
674**
675** ^The sqlite3_version[] string constant contains the text of [SQLITE_VERSION]
676** macro.  ^The sqlite3_libversion() function returns a pointer to the
677** to the sqlite3_version[] string constant.  The sqlite3_libversion()
678** function is provided for use in DLLs since DLL users usually do not have
679** direct access to string constants within the DLL.  ^The
680** sqlite3_libversion_number() function returns an integer equal to
681** [SQLITE_VERSION_NUMBER].  ^The sqlite3_sourceid() function returns
682** a pointer to a string constant whose value is the same as the
683** [SQLITE_SOURCE_ID] C preprocessor macro.
684**
685** See also: [sqlite_version()] and [sqlite_source_id()].
686*/
687SQLITE_API const char sqlite3_version[] = SQLITE_VERSION;
688SQLITE_API const char *sqlite3_libversion(void);
689SQLITE_API const char *sqlite3_sourceid(void);
690SQLITE_API int sqlite3_libversion_number(void);
691
692/*
693** CAPI3REF: Run-Time Library Compilation Options Diagnostics
694**
695** ^The sqlite3_compileoption_used() function returns 0 or 1
696** indicating whether the specified option was defined at
697** compile time.  ^The SQLITE_ prefix may be omitted from the
698** option name passed to sqlite3_compileoption_used().
699**
700** ^The sqlite3_compileoption_get() function allows iterating
701** over the list of options that were defined at compile time by
702** returning the N-th compile time option string.  ^If N is out of range,
703** sqlite3_compileoption_get() returns a NULL pointer.  ^The SQLITE_
704** prefix is omitted from any strings returned by
705** sqlite3_compileoption_get().
706**
707** ^Support for the diagnostic functions sqlite3_compileoption_used()
708** and sqlite3_compileoption_get() may be omitted by specifying the
709** [SQLITE_OMIT_COMPILEOPTION_DIAGS] option at compile time.
710**
711** See also: SQL functions [sqlite_compileoption_used()] and
712** [sqlite_compileoption_get()] and the [compile_options pragma].
713*/
714#ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
715SQLITE_API int sqlite3_compileoption_used(const char *zOptName);
716SQLITE_API const char *sqlite3_compileoption_get(int N);
717#endif
718
719/*
720** CAPI3REF: Test To See If The Library Is Threadsafe
721**
722** ^The sqlite3_threadsafe() function returns zero if and only if
723** SQLite was compiled mutexing code omitted due to the
724** [SQLITE_THREADSAFE] compile-time option being set to 0.
725**
726** SQLite can be compiled with or without mutexes.  When
727** the [SQLITE_THREADSAFE] C preprocessor macro is 1 or 2, mutexes
728** are enabled and SQLite is threadsafe.  When the
729** [SQLITE_THREADSAFE] macro is 0,
730** the mutexes are omitted.  Without the mutexes, it is not safe
731** to use SQLite concurrently from more than one thread.
732**
733** Enabling mutexes incurs a measurable performance penalty.
734** So if speed is of utmost importance, it makes sense to disable
735** the mutexes.  But for maximum safety, mutexes should be enabled.
736** ^The default behavior is for mutexes to be enabled.
737**
738** This interface can be used by an application to make sure that the
739** version of SQLite that it is linking against was compiled with
740** the desired setting of the [SQLITE_THREADSAFE] macro.
741**
742** This interface only reports on the compile-time mutex setting
743** of the [SQLITE_THREADSAFE] flag.  If SQLite is compiled with
744** SQLITE_THREADSAFE=1 or =2 then mutexes are enabled by default but
745** can be fully or partially disabled using a call to [sqlite3_config()]
746** with the verbs [SQLITE_CONFIG_SINGLETHREAD], [SQLITE_CONFIG_MULTITHREAD],
747** or [SQLITE_CONFIG_MUTEX].  ^(The return value of the
748** sqlite3_threadsafe() function shows only the compile-time setting of
749** thread safety, not any run-time changes to that setting made by
750** sqlite3_config(). In other words, the return value from sqlite3_threadsafe()
751** is unchanged by calls to sqlite3_config().)^
752**
753** See the [threading mode] documentation for additional information.
754*/
755SQLITE_API int sqlite3_threadsafe(void);
756
757/*
758** CAPI3REF: Database Connection Handle
759** KEYWORDS: {database connection} {database connections}
760**
761** Each open SQLite database is represented by a pointer to an instance of
762** the opaque structure named "sqlite3".  It is useful to think of an sqlite3
763** pointer as an object.  The [sqlite3_open()], [sqlite3_open16()], and
764** [sqlite3_open_v2()] interfaces are its constructors, and [sqlite3_close()]
765** is its destructor.  There are many other interfaces (such as
766** [sqlite3_prepare_v2()], [sqlite3_create_function()], and
767** [sqlite3_busy_timeout()] to name but three) that are methods on an
768** sqlite3 object.
769*/
770typedef struct sqlite3 sqlite3;
771
772/*
773** CAPI3REF: 64-Bit Integer Types
774** KEYWORDS: sqlite_int64 sqlite_uint64
775**
776** Because there is no cross-platform way to specify 64-bit integer types
777** SQLite includes typedefs for 64-bit signed and unsigned integers.
778**
779** The sqlite3_int64 and sqlite3_uint64 are the preferred type definitions.
780** The sqlite_int64 and sqlite_uint64 types are supported for backwards
781** compatibility only.
782**
783** ^The sqlite3_int64 and sqlite_int64 types can store integer values
784** between -9223372036854775808 and +9223372036854775807 inclusive.  ^The
785** sqlite3_uint64 and sqlite_uint64 types can store integer values
786** between 0 and +18446744073709551615 inclusive.
787*/
788#ifdef SQLITE_INT64_TYPE
789  typedef SQLITE_INT64_TYPE sqlite_int64;
790  typedef unsigned SQLITE_INT64_TYPE sqlite_uint64;
791#elif defined(_MSC_VER) || defined(__BORLANDC__)
792  typedef __int64 sqlite_int64;
793  typedef unsigned __int64 sqlite_uint64;
794#else
795  typedef long long int sqlite_int64;
796  typedef unsigned long long int sqlite_uint64;
797#endif
798typedef sqlite_int64 sqlite3_int64;
799typedef sqlite_uint64 sqlite3_uint64;
800
801/*
802** If compiling for a processor that lacks floating point support,
803** substitute integer for floating-point.
804*/
805#ifdef SQLITE_OMIT_FLOATING_POINT
806# define double sqlite3_int64
807#endif
808
809/*
810** CAPI3REF: Closing A Database Connection
811**
812** ^The sqlite3_close() routine is the destructor for the [sqlite3] object.
813** ^Calls to sqlite3_close() return SQLITE_OK if the [sqlite3] object is
814** successfully destroyed and all associated resources are deallocated.
815**
816** Applications must [sqlite3_finalize | finalize] all [prepared statements]
817** and [sqlite3_blob_close | close] all [BLOB handles] associated with
818** the [sqlite3] object prior to attempting to close the object.  ^If
819** sqlite3_close() is called on a [database connection] that still has
820** outstanding [prepared statements] or [BLOB handles], then it returns
821** SQLITE_BUSY.
822**
823** ^If [sqlite3_close()] is invoked while a transaction is open,
824** the transaction is automatically rolled back.
825**
826** The C parameter to [sqlite3_close(C)] must be either a NULL
827** pointer or an [sqlite3] object pointer obtained
828** from [sqlite3_open()], [sqlite3_open16()], or
829** [sqlite3_open_v2()], and not previously closed.
830** ^Calling sqlite3_close() with a NULL pointer argument is a
831** harmless no-op.
832*/
833SQLITE_API int sqlite3_close(sqlite3 *);
834
835/*
836** The type for a callback function.
837** This is legacy and deprecated.  It is included for historical
838** compatibility and is not documented.
839*/
840typedef int (*sqlite3_callback)(void*,int,char**, char**);
841
842/*
843** CAPI3REF: One-Step Query Execution Interface
844**
845** The sqlite3_exec() interface is a convenience wrapper around
846** [sqlite3_prepare_v2()], [sqlite3_step()], and [sqlite3_finalize()],
847** that allows an application to run multiple statements of SQL
848** without having to use a lot of C code.
849**
850** ^The sqlite3_exec() interface runs zero or more UTF-8 encoded,
851** semicolon-separate SQL statements passed into its 2nd argument,
852** in the context of the [database connection] passed in as its 1st
853** argument.  ^If the callback function of the 3rd argument to
854** sqlite3_exec() is not NULL, then it is invoked for each result row
855** coming out of the evaluated SQL statements.  ^The 4th argument to
856** to sqlite3_exec() is relayed through to the 1st argument of each
857** callback invocation.  ^If the callback pointer to sqlite3_exec()
858** is NULL, then no callback is ever invoked and result rows are
859** ignored.
860**
861** ^If an error occurs while evaluating the SQL statements passed into
862** sqlite3_exec(), then execution of the current statement stops and
863** subsequent statements are skipped.  ^If the 5th parameter to sqlite3_exec()
864** is not NULL then any error message is written into memory obtained
865** from [sqlite3_malloc()] and passed back through the 5th parameter.
866** To avoid memory leaks, the application should invoke [sqlite3_free()]
867** on error message strings returned through the 5th parameter of
868** of sqlite3_exec() after the error message string is no longer needed.
869** ^If the 5th parameter to sqlite3_exec() is not NULL and no errors
870** occur, then sqlite3_exec() sets the pointer in its 5th parameter to
871** NULL before returning.
872**
873** ^If an sqlite3_exec() callback returns non-zero, the sqlite3_exec()
874** routine returns SQLITE_ABORT without invoking the callback again and
875** without running any subsequent SQL statements.
876**
877** ^The 2nd argument to the sqlite3_exec() callback function is the
878** number of columns in the result.  ^The 3rd argument to the sqlite3_exec()
879** callback is an array of pointers to strings obtained as if from
880** [sqlite3_column_text()], one for each column.  ^If an element of a
881** result row is NULL then the corresponding string pointer for the
882** sqlite3_exec() callback is a NULL pointer.  ^The 4th argument to the
883** sqlite3_exec() callback is an array of pointers to strings where each
884** entry represents the name of corresponding result column as obtained
885** from [sqlite3_column_name()].
886**
887** ^If the 2nd parameter to sqlite3_exec() is a NULL pointer, a pointer
888** to an empty string, or a pointer that contains only whitespace and/or
889** SQL comments, then no SQL statements are evaluated and the database
890** is not changed.
891**
892** Restrictions:
893**
894** <ul>
895** <li> The application must insure that the 1st parameter to sqlite3_exec()
896**      is a valid and open [database connection].
897** <li> The application must not close [database connection] specified by
898**      the 1st parameter to sqlite3_exec() while sqlite3_exec() is running.
899** <li> The application must not modify the SQL statement text passed into
900**      the 2nd parameter of sqlite3_exec() while sqlite3_exec() is running.
901** </ul>
902*/
903SQLITE_API int sqlite3_exec(
904  sqlite3*,                                  /* An open database */
905  const char *sql,                           /* SQL to be evaluated */
906  int (*callback)(void*,int,char**,char**),  /* Callback function */
907  void *,                                    /* 1st argument to callback */
908  char **errmsg                              /* Error msg written here */
909);
910
911/*
912** CAPI3REF: Result Codes
913** KEYWORDS: SQLITE_OK {error code} {error codes}
914** KEYWORDS: {result code} {result codes}
915**
916** Many SQLite functions return an integer result code from the set shown
917** here in order to indicates success or failure.
918**
919** New error codes may be added in future versions of SQLite.
920**
921** See also: [SQLITE_IOERR_READ | extended result codes]
922*/
923#define SQLITE_OK           0   /* Successful result */
924/* beginning-of-error-codes */
925#define SQLITE_ERROR        1   /* SQL error or missing database */
926#define SQLITE_INTERNAL     2   /* Internal logic error in SQLite */
927#define SQLITE_PERM         3   /* Access permission denied */
928#define SQLITE_ABORT        4   /* Callback routine requested an abort */
929#define SQLITE_BUSY         5   /* The database file is locked */
930#define SQLITE_LOCKED       6   /* A table in the database is locked */
931#define SQLITE_NOMEM        7   /* A malloc() failed */
932#define SQLITE_READONLY     8   /* Attempt to write a readonly database */
933#define SQLITE_INTERRUPT    9   /* Operation terminated by sqlite3_interrupt()*/
934#define SQLITE_IOERR       10   /* Some kind of disk I/O error occurred */
935#define SQLITE_CORRUPT     11   /* The database disk image is malformed */
936#define SQLITE_NOTFOUND    12   /* Unknown opcode in sqlite3_file_control() */
937#define SQLITE_FULL        13   /* Insertion failed because database is full */
938#define SQLITE_CANTOPEN    14   /* Unable to open the database file */
939#define SQLITE_PROTOCOL    15   /* Database lock protocol error */
940#define SQLITE_EMPTY       16   /* Database is empty */
941#define SQLITE_SCHEMA      17   /* The database schema changed */
942#define SQLITE_TOOBIG      18   /* String or BLOB exceeds size limit */
943#define SQLITE_CONSTRAINT  19   /* Abort due to constraint violation */
944#define SQLITE_MISMATCH    20   /* Data type mismatch */
945#define SQLITE_MISUSE      21   /* Library used incorrectly */
946#define SQLITE_NOLFS       22   /* Uses OS features not supported on host */
947#define SQLITE_AUTH        23   /* Authorization denied */
948#define SQLITE_FORMAT      24   /* Auxiliary database format error */
949#define SQLITE_RANGE       25   /* 2nd parameter to sqlite3_bind out of range */
950#define SQLITE_NOTADB      26   /* File opened that is not a database file */
951#define SQLITE_ROW         100  /* sqlite3_step() has another row ready */
952#define SQLITE_DONE        101  /* sqlite3_step() has finished executing */
953/* end-of-error-codes */
954
955/*
956** CAPI3REF: Extended Result Codes
957** KEYWORDS: {extended error code} {extended error codes}
958** KEYWORDS: {extended result code} {extended result codes}
959**
960** In its default configuration, SQLite API routines return one of 26 integer
961** [SQLITE_OK | result codes].  However, experience has shown that many of
962** these result codes are too coarse-grained.  They do not provide as
963** much information about problems as programmers might like.  In an effort to
964** address this, newer versions of SQLite (version 3.3.8 and later) include
965** support for additional result codes that provide more detailed information
966** about errors. The extended result codes are enabled or disabled
967** on a per database connection basis using the
968** [sqlite3_extended_result_codes()] API.
969**
970** Some of the available extended result codes are listed here.
971** One may expect the number of extended result codes will be expand
972** over time.  Software that uses extended result codes should expect
973** to see new result codes in future releases of SQLite.
974**
975** The SQLITE_OK result code will never be extended.  It will always
976** be exactly zero.
977*/
978#define SQLITE_IOERR_READ              (SQLITE_IOERR | (1<<8))
979#define SQLITE_IOERR_SHORT_READ        (SQLITE_IOERR | (2<<8))
980#define SQLITE_IOERR_WRITE             (SQLITE_IOERR | (3<<8))
981#define SQLITE_IOERR_FSYNC             (SQLITE_IOERR | (4<<8))
982#define SQLITE_IOERR_DIR_FSYNC         (SQLITE_IOERR | (5<<8))
983#define SQLITE_IOERR_TRUNCATE          (SQLITE_IOERR | (6<<8))
984#define SQLITE_IOERR_FSTAT             (SQLITE_IOERR | (7<<8))
985#define SQLITE_IOERR_UNLOCK            (SQLITE_IOERR | (8<<8))
986#define SQLITE_IOERR_RDLOCK            (SQLITE_IOERR | (9<<8))
987#define SQLITE_IOERR_DELETE            (SQLITE_IOERR | (10<<8))
988#define SQLITE_IOERR_BLOCKED           (SQLITE_IOERR | (11<<8))
989#define SQLITE_IOERR_NOMEM             (SQLITE_IOERR | (12<<8))
990#define SQLITE_IOERR_ACCESS            (SQLITE_IOERR | (13<<8))
991#define SQLITE_IOERR_CHECKRESERVEDLOCK (SQLITE_IOERR | (14<<8))
992#define SQLITE_IOERR_LOCK              (SQLITE_IOERR | (15<<8))
993#define SQLITE_IOERR_CLOSE             (SQLITE_IOERR | (16<<8))
994#define SQLITE_IOERR_DIR_CLOSE         (SQLITE_IOERR | (17<<8))
995#define SQLITE_IOERR_SHMOPEN           (SQLITE_IOERR | (18<<8))
996#define SQLITE_IOERR_SHMSIZE           (SQLITE_IOERR | (19<<8))
997#define SQLITE_IOERR_SHMLOCK           (SQLITE_IOERR | (20<<8))
998#define SQLITE_LOCKED_SHAREDCACHE      (SQLITE_LOCKED |  (1<<8))
999#define SQLITE_BUSY_RECOVERY           (SQLITE_BUSY   |  (1<<8))
1000#define SQLITE_CANTOPEN_NOTEMPDIR      (SQLITE_CANTOPEN | (1<<8))
1001
1002/*
1003** CAPI3REF: Flags For File Open Operations
1004**
1005** These bit values are intended for use in the
1006** 3rd parameter to the [sqlite3_open_v2()] interface and
1007** in the 4th parameter to the xOpen method of the
1008** [sqlite3_vfs] object.
1009*/
1010#define SQLITE_OPEN_READONLY         0x00000001  /* Ok for sqlite3_open_v2() */
1011#define SQLITE_OPEN_READWRITE        0x00000002  /* Ok for sqlite3_open_v2() */
1012#define SQLITE_OPEN_CREATE           0x00000004  /* Ok for sqlite3_open_v2() */
1013#define SQLITE_OPEN_DELETEONCLOSE    0x00000008  /* VFS only */
1014#define SQLITE_OPEN_EXCLUSIVE        0x00000010  /* VFS only */
1015#define SQLITE_OPEN_AUTOPROXY        0x00000020  /* VFS only */
1016#define SQLITE_OPEN_MAIN_DB          0x00000100  /* VFS only */
1017#define SQLITE_OPEN_TEMP_DB          0x00000200  /* VFS only */
1018#define SQLITE_OPEN_TRANSIENT_DB     0x00000400  /* VFS only */
1019#define SQLITE_OPEN_MAIN_JOURNAL     0x00000800  /* VFS only */
1020#define SQLITE_OPEN_TEMP_JOURNAL     0x00001000  /* VFS only */
1021#define SQLITE_OPEN_SUBJOURNAL       0x00002000  /* VFS only */
1022#define SQLITE_OPEN_MASTER_JOURNAL   0x00004000  /* VFS only */
1023#define SQLITE_OPEN_NOMUTEX          0x00008000  /* Ok for sqlite3_open_v2() */
1024#define SQLITE_OPEN_FULLMUTEX        0x00010000  /* Ok for sqlite3_open_v2() */
1025#define SQLITE_OPEN_SHAREDCACHE      0x00020000  /* Ok for sqlite3_open_v2() */
1026#define SQLITE_OPEN_PRIVATECACHE     0x00040000  /* Ok for sqlite3_open_v2() */
1027#define SQLITE_OPEN_WAL              0x00080000  /* VFS only */
1028
1029/* Reserved:                         0x00F00000 */
1030
1031/*
1032** CAPI3REF: Device Characteristics
1033**
1034** The xDeviceCharacteristics method of the [sqlite3_io_methods]
1035** object returns an integer which is a vector of the these
1036** bit values expressing I/O characteristics of the mass storage
1037** device that holds the file that the [sqlite3_io_methods]
1038** refers to.
1039**
1040** The SQLITE_IOCAP_ATOMIC property means that all writes of
1041** any size are atomic.  The SQLITE_IOCAP_ATOMICnnn values
1042** mean that writes of blocks that are nnn bytes in size and
1043** are aligned to an address which is an integer multiple of
1044** nnn are atomic.  The SQLITE_IOCAP_SAFE_APPEND value means
1045** that when data is appended to a file, the data is appended
1046** first then the size of the file is extended, never the other
1047** way around.  The SQLITE_IOCAP_SEQUENTIAL property means that
1048** information is written to disk in the same order as calls
1049** to xWrite().
1050*/
1051#define SQLITE_IOCAP_ATOMIC                 0x00000001
1052#define SQLITE_IOCAP_ATOMIC512              0x00000002
1053#define SQLITE_IOCAP_ATOMIC1K               0x00000004
1054#define SQLITE_IOCAP_ATOMIC2K               0x00000008
1055#define SQLITE_IOCAP_ATOMIC4K               0x00000010
1056#define SQLITE_IOCAP_ATOMIC8K               0x00000020
1057#define SQLITE_IOCAP_ATOMIC16K              0x00000040
1058#define SQLITE_IOCAP_ATOMIC32K              0x00000080
1059#define SQLITE_IOCAP_ATOMIC64K              0x00000100
1060#define SQLITE_IOCAP_SAFE_APPEND            0x00000200
1061#define SQLITE_IOCAP_SEQUENTIAL             0x00000400
1062#define SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN  0x00000800
1063
1064/*
1065** CAPI3REF: File Locking Levels
1066**
1067** SQLite uses one of these integer values as the second
1068** argument to calls it makes to the xLock() and xUnlock() methods
1069** of an [sqlite3_io_methods] object.
1070*/
1071#define SQLITE_LOCK_NONE          0
1072#define SQLITE_LOCK_SHARED        1
1073#define SQLITE_LOCK_RESERVED      2
1074#define SQLITE_LOCK_PENDING       3
1075#define SQLITE_LOCK_EXCLUSIVE     4
1076
1077/*
1078** CAPI3REF: Synchronization Type Flags
1079**
1080** When SQLite invokes the xSync() method of an
1081** [sqlite3_io_methods] object it uses a combination of
1082** these integer values as the second argument.
1083**
1084** When the SQLITE_SYNC_DATAONLY flag is used, it means that the
1085** sync operation only needs to flush data to mass storage.  Inode
1086** information need not be flushed. If the lower four bits of the flag
1087** equal SQLITE_SYNC_NORMAL, that means to use normal fsync() semantics.
1088** If the lower four bits equal SQLITE_SYNC_FULL, that means
1089** to use Mac OS X style fullsync instead of fsync().
1090**
1091** Do not confuse the SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL flags
1092** with the [PRAGMA synchronous]=NORMAL and [PRAGMA synchronous]=FULL
1093** settings.  The [synchronous pragma] determines when calls to the
1094** xSync VFS method occur and applies uniformly across all platforms.
1095** The SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL flags determine how
1096** energetic or rigorous or forceful the sync operations are and
1097** only make a difference on Mac OSX for the default SQLite code.
1098** (Third-party VFS implementations might also make the distinction
1099** between SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL, but among the
1100** operating systems natively supported by SQLite, only Mac OSX
1101** cares about the difference.)
1102*/
1103#define SQLITE_SYNC_NORMAL        0x00002
1104#define SQLITE_SYNC_FULL          0x00003
1105#define SQLITE_SYNC_DATAONLY      0x00010
1106
1107/*
1108** CAPI3REF: OS Interface Open File Handle
1109**
1110** An [sqlite3_file] object represents an open file in the
1111** [sqlite3_vfs | OS interface layer].  Individual OS interface
1112** implementations will
1113** want to subclass this object by appending additional fields
1114** for their own use.  The pMethods entry is a pointer to an
1115** [sqlite3_io_methods] object that defines methods for performing
1116** I/O operations on the open file.
1117*/
1118typedef struct sqlite3_file sqlite3_file;
1119struct sqlite3_file {
1120  const struct sqlite3_io_methods *pMethods;  /* Methods for an open file */
1121};
1122
1123/*
1124** CAPI3REF: OS Interface File Virtual Methods Object
1125**
1126** Every file opened by the [sqlite3_vfs] xOpen method populates an
1127** [sqlite3_file] object (or, more commonly, a subclass of the
1128** [sqlite3_file] object) with a pointer to an instance of this object.
1129** This object defines the methods used to perform various operations
1130** against the open file represented by the [sqlite3_file] object.
1131**
1132** If the xOpen method sets the sqlite3_file.pMethods element
1133** to a non-NULL pointer, then the sqlite3_io_methods.xClose method
1134** may be invoked even if the xOpen reported that it failed.  The
1135** only way to prevent a call to xClose following a failed xOpen
1136** is for the xOpen to set the sqlite3_file.pMethods element to NULL.
1137**
1138** The flags argument to xSync may be one of [SQLITE_SYNC_NORMAL] or
1139** [SQLITE_SYNC_FULL].  The first choice is the normal fsync().
1140** The second choice is a Mac OS X style fullsync.  The [SQLITE_SYNC_DATAONLY]
1141** flag may be ORed in to indicate that only the data of the file
1142** and not its inode needs to be synced.
1143**
1144** The integer values to xLock() and xUnlock() are one of
1145** <ul>
1146** <li> [SQLITE_LOCK_NONE],
1147** <li> [SQLITE_LOCK_SHARED],
1148** <li> [SQLITE_LOCK_RESERVED],
1149** <li> [SQLITE_LOCK_PENDING], or
1150** <li> [SQLITE_LOCK_EXCLUSIVE].
1151** </ul>
1152** xLock() increases the lock. xUnlock() decreases the lock.
1153** The xCheckReservedLock() method checks whether any database connection,
1154** either in this process or in some other process, is holding a RESERVED,
1155** PENDING, or EXCLUSIVE lock on the file.  It returns true
1156** if such a lock exists and false otherwise.
1157**
1158** The xFileControl() method is a generic interface that allows custom
1159** VFS implementations to directly control an open file using the
1160** [sqlite3_file_control()] interface.  The second "op" argument is an
1161** integer opcode.  The third argument is a generic pointer intended to
1162** point to a structure that may contain arguments or space in which to
1163** write return values.  Potential uses for xFileControl() might be
1164** functions to enable blocking locks with timeouts, to change the
1165** locking strategy (for example to use dot-file locks), to inquire
1166** about the status of a lock, or to break stale locks.  The SQLite
1167** core reserves all opcodes less than 100 for its own use.
1168** A [SQLITE_FCNTL_LOCKSTATE | list of opcodes] less than 100 is available.
1169** Applications that define a custom xFileControl method should use opcodes
1170** greater than 100 to avoid conflicts.  VFS implementations should
1171** return [SQLITE_NOTFOUND] for file control opcodes that they do not
1172** recognize.
1173**
1174** The xSectorSize() method returns the sector size of the
1175** device that underlies the file.  The sector size is the
1176** minimum write that can be performed without disturbing
1177** other bytes in the file.  The xDeviceCharacteristics()
1178** method returns a bit vector describing behaviors of the
1179** underlying device:
1180**
1181** <ul>
1182** <li> [SQLITE_IOCAP_ATOMIC]
1183** <li> [SQLITE_IOCAP_ATOMIC512]
1184** <li> [SQLITE_IOCAP_ATOMIC1K]
1185** <li> [SQLITE_IOCAP_ATOMIC2K]
1186** <li> [SQLITE_IOCAP_ATOMIC4K]
1187** <li> [SQLITE_IOCAP_ATOMIC8K]
1188** <li> [SQLITE_IOCAP_ATOMIC16K]
1189** <li> [SQLITE_IOCAP_ATOMIC32K]
1190** <li> [SQLITE_IOCAP_ATOMIC64K]
1191** <li> [SQLITE_IOCAP_SAFE_APPEND]
1192** <li> [SQLITE_IOCAP_SEQUENTIAL]
1193** </ul>
1194**
1195** The SQLITE_IOCAP_ATOMIC property means that all writes of
1196** any size are atomic.  The SQLITE_IOCAP_ATOMICnnn values
1197** mean that writes of blocks that are nnn bytes in size and
1198** are aligned to an address which is an integer multiple of
1199** nnn are atomic.  The SQLITE_IOCAP_SAFE_APPEND value means
1200** that when data is appended to a file, the data is appended
1201** first then the size of the file is extended, never the other
1202** way around.  The SQLITE_IOCAP_SEQUENTIAL property means that
1203** information is written to disk in the same order as calls
1204** to xWrite().
1205**
1206** If xRead() returns SQLITE_IOERR_SHORT_READ it must also fill
1207** in the unread portions of the buffer with zeros.  A VFS that
1208** fails to zero-fill short reads might seem to work.  However,
1209** failure to zero-fill short reads will eventually lead to
1210** database corruption.
1211*/
1212typedef struct sqlite3_io_methods sqlite3_io_methods;
1213struct sqlite3_io_methods {
1214  int iVersion;
1215  int (*xClose)(sqlite3_file*);
1216  int (*xRead)(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst);
1217  int (*xWrite)(sqlite3_file*, const void*, int iAmt, sqlite3_int64 iOfst);
1218  int (*xTruncate)(sqlite3_file*, sqlite3_int64 size);
1219  int (*xSync)(sqlite3_file*, int flags);
1220  int (*xFileSize)(sqlite3_file*, sqlite3_int64 *pSize);
1221  int (*xLock)(sqlite3_file*, int);
1222  int (*xUnlock)(sqlite3_file*, int);
1223  int (*xCheckReservedLock)(sqlite3_file*, int *pResOut);
1224  int (*xFileControl)(sqlite3_file*, int op, void *pArg);
1225  int (*xSectorSize)(sqlite3_file*);
1226  int (*xDeviceCharacteristics)(sqlite3_file*);
1227  /* Methods above are valid for version 1 */
1228  int (*xShmMap)(sqlite3_file*, int iPg, int pgsz, int, void volatile**);
1229  int (*xShmLock)(sqlite3_file*, int offset, int n, int flags);
1230  void (*xShmBarrier)(sqlite3_file*);
1231  int (*xShmUnmap)(sqlite3_file*, int deleteFlag);
1232  /* Methods above are valid for version 2 */
1233  /* Additional methods may be added in future releases */
1234};
1235
1236/*
1237** CAPI3REF: Standard File Control Opcodes
1238**
1239** These integer constants are opcodes for the xFileControl method
1240** of the [sqlite3_io_methods] object and for the [sqlite3_file_control()]
1241** interface.
1242**
1243** The [SQLITE_FCNTL_LOCKSTATE] opcode is used for debugging.  This
1244** opcode causes the xFileControl method to write the current state of
1245** the lock (one of [SQLITE_LOCK_NONE], [SQLITE_LOCK_SHARED],
1246** [SQLITE_LOCK_RESERVED], [SQLITE_LOCK_PENDING], or [SQLITE_LOCK_EXCLUSIVE])
1247** into an integer that the pArg argument points to. This capability
1248** is used during testing and only needs to be supported when SQLITE_TEST
1249** is defined.
1250**
1251** The [SQLITE_FCNTL_SIZE_HINT] opcode is used by SQLite to give the VFS
1252** layer a hint of how large the database file will grow to be during the
1253** current transaction.  This hint is not guaranteed to be accurate but it
1254** is often close.  The underlying VFS might choose to preallocate database
1255** file space based on this hint in order to help writes to the database
1256** file run faster.
1257**
1258** The [SQLITE_FCNTL_CHUNK_SIZE] opcode is used to request that the VFS
1259** extends and truncates the database file in chunks of a size specified
1260** by the user. The fourth argument to [sqlite3_file_control()] should
1261** point to an integer (type int) containing the new chunk-size to use
1262** for the nominated database. Allocating database file space in large
1263** chunks (say 1MB at a time), may reduce file-system fragmentation and
1264** improve performance on some systems.
1265**
1266** The [SQLITE_FCNTL_FILE_POINTER] opcode is used to obtain a pointer
1267** to the [sqlite3_file] object associated with a particular database
1268** connection.  See the [sqlite3_file_control()] documentation for
1269** additional information.
1270**
1271** ^(The [SQLITE_FCNTL_SYNC_OMITTED] opcode is generated internally by
1272** SQLite and sent to all VFSes in place of a call to the xSync method
1273** when the database connection has [PRAGMA synchronous] set to OFF.)^
1274** Some specialized VFSes need this signal in order to operate correctly
1275** when [PRAGMA synchronous | PRAGMA synchronous=OFF] is set, but most
1276** VFSes do not need this signal and should silently ignore this opcode.
1277** Applications should not call [sqlite3_file_control()] with this
1278** opcode as doing so may disrupt the operation of the specialized VFSes
1279** that do require it.
1280*/
1281#define SQLITE_FCNTL_LOCKSTATE        1
1282#define SQLITE_GET_LOCKPROXYFILE      2
1283#define SQLITE_SET_LOCKPROXYFILE      3
1284#define SQLITE_LAST_ERRNO             4
1285#define SQLITE_FCNTL_SIZE_HINT        5
1286#define SQLITE_FCNTL_CHUNK_SIZE       6
1287#define SQLITE_FCNTL_FILE_POINTER     7
1288#define SQLITE_FCNTL_SYNC_OMITTED     8
1289
1290
1291/*
1292** CAPI3REF: Mutex Handle
1293**
1294** The mutex module within SQLite defines [sqlite3_mutex] to be an
1295** abstract type for a mutex object.  The SQLite core never looks
1296** at the internal representation of an [sqlite3_mutex].  It only
1297** deals with pointers to the [sqlite3_mutex] object.
1298**
1299** Mutexes are created using [sqlite3_mutex_alloc()].
1300*/
1301typedef struct sqlite3_mutex sqlite3_mutex;
1302
1303/*
1304** CAPI3REF: OS Interface Object
1305**
1306** An instance of the sqlite3_vfs object defines the interface between
1307** the SQLite core and the underlying operating system.  The "vfs"
1308** in the name of the object stands for "virtual file system".
1309**
1310** The value of the iVersion field is initially 1 but may be larger in
1311** future versions of SQLite.  Additional fields may be appended to this
1312** object when the iVersion value is increased.  Note that the structure
1313** of the sqlite3_vfs object changes in the transaction between
1314** SQLite version 3.5.9 and 3.6.0 and yet the iVersion field was not
1315** modified.
1316**
1317** The szOsFile field is the size of the subclassed [sqlite3_file]
1318** structure used by this VFS.  mxPathname is the maximum length of
1319** a pathname in this VFS.
1320**
1321** Registered sqlite3_vfs objects are kept on a linked list formed by
1322** the pNext pointer.  The [sqlite3_vfs_register()]
1323** and [sqlite3_vfs_unregister()] interfaces manage this list
1324** in a thread-safe way.  The [sqlite3_vfs_find()] interface
1325** searches the list.  Neither the application code nor the VFS
1326** implementation should use the pNext pointer.
1327**
1328** The pNext field is the only field in the sqlite3_vfs
1329** structure that SQLite will ever modify.  SQLite will only access
1330** or modify this field while holding a particular static mutex.
1331** The application should never modify anything within the sqlite3_vfs
1332** object once the object has been registered.
1333**
1334** The zName field holds the name of the VFS module.  The name must
1335** be unique across all VFS modules.
1336**
1337** ^SQLite guarantees that the zFilename parameter to xOpen
1338** is either a NULL pointer or string obtained
1339** from xFullPathname() with an optional suffix added.
1340** ^If a suffix is added to the zFilename parameter, it will
1341** consist of a single "-" character followed by no more than
1342** 10 alphanumeric and/or "-" characters.
1343** ^SQLite further guarantees that
1344** the string will be valid and unchanged until xClose() is
1345** called. Because of the previous sentence,
1346** the [sqlite3_file] can safely store a pointer to the
1347** filename if it needs to remember the filename for some reason.
1348** If the zFilename parameter to xOpen is a NULL pointer then xOpen
1349** must invent its own temporary name for the file.  ^Whenever the
1350** xFilename parameter is NULL it will also be the case that the
1351** flags parameter will include [SQLITE_OPEN_DELETEONCLOSE].
1352**
1353** The flags argument to xOpen() includes all bits set in
1354** the flags argument to [sqlite3_open_v2()].  Or if [sqlite3_open()]
1355** or [sqlite3_open16()] is used, then flags includes at least
1356** [SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE].
1357** If xOpen() opens a file read-only then it sets *pOutFlags to
1358** include [SQLITE_OPEN_READONLY].  Other bits in *pOutFlags may be set.
1359**
1360** ^(SQLite will also add one of the following flags to the xOpen()
1361** call, depending on the object being opened:
1362**
1363** <ul>
1364** <li>  [SQLITE_OPEN_MAIN_DB]
1365** <li>  [SQLITE_OPEN_MAIN_JOURNAL]
1366** <li>  [SQLITE_OPEN_TEMP_DB]
1367** <li>  [SQLITE_OPEN_TEMP_JOURNAL]
1368** <li>  [SQLITE_OPEN_TRANSIENT_DB]
1369** <li>  [SQLITE_OPEN_SUBJOURNAL]
1370** <li>  [SQLITE_OPEN_MASTER_JOURNAL]
1371** <li>  [SQLITE_OPEN_WAL]
1372** </ul>)^
1373**
1374** The file I/O implementation can use the object type flags to
1375** change the way it deals with files.  For example, an application
1376** that does not care about crash recovery or rollback might make
1377** the open of a journal file a no-op.  Writes to this journal would
1378** also be no-ops, and any attempt to read the journal would return
1379** SQLITE_IOERR.  Or the implementation might recognize that a database
1380** file will be doing page-aligned sector reads and writes in a random
1381** order and set up its I/O subsystem accordingly.
1382**
1383** SQLite might also add one of the following flags to the xOpen method:
1384**
1385** <ul>
1386** <li> [SQLITE_OPEN_DELETEONCLOSE]
1387** <li> [SQLITE_OPEN_EXCLUSIVE]
1388** </ul>
1389**
1390** The [SQLITE_OPEN_DELETEONCLOSE] flag means the file should be
1391** deleted when it is closed.  ^The [SQLITE_OPEN_DELETEONCLOSE]
1392** will be set for TEMP databases and their journals, transient
1393** databases, and subjournals.
1394**
1395** ^The [SQLITE_OPEN_EXCLUSIVE] flag is always used in conjunction
1396** with the [SQLITE_OPEN_CREATE] flag, which are both directly
1397** analogous to the O_EXCL and O_CREAT flags of the POSIX open()
1398** API.  The SQLITE_OPEN_EXCLUSIVE flag, when paired with the
1399** SQLITE_OPEN_CREATE, is used to indicate that file should always
1400** be created, and that it is an error if it already exists.
1401** It is <i>not</i> used to indicate the file should be opened
1402** for exclusive access.
1403**
1404** ^At least szOsFile bytes of memory are allocated by SQLite
1405** to hold the  [sqlite3_file] structure passed as the third
1406** argument to xOpen.  The xOpen method does not have to
1407** allocate the structure; it should just fill it in.  Note that
1408** the xOpen method must set the sqlite3_file.pMethods to either
1409** a valid [sqlite3_io_methods] object or to NULL.  xOpen must do
1410** this even if the open fails.  SQLite expects that the sqlite3_file.pMethods
1411** element will be valid after xOpen returns regardless of the success
1412** or failure of the xOpen call.
1413**
1414** ^The flags argument to xAccess() may be [SQLITE_ACCESS_EXISTS]
1415** to test for the existence of a file, or [SQLITE_ACCESS_READWRITE] to
1416** test whether a file is readable and writable, or [SQLITE_ACCESS_READ]
1417** to test whether a file is at least readable.   The file can be a
1418** directory.
1419**
1420** ^SQLite will always allocate at least mxPathname+1 bytes for the
1421** output buffer xFullPathname.  The exact size of the output buffer
1422** is also passed as a parameter to both  methods. If the output buffer
1423** is not large enough, [SQLITE_CANTOPEN] should be returned. Since this is
1424** handled as a fatal error by SQLite, vfs implementations should endeavor
1425** to prevent this by setting mxPathname to a sufficiently large value.
1426**
1427** The xRandomness(), xSleep(), xCurrentTime(), and xCurrentTimeInt64()
1428** interfaces are not strictly a part of the filesystem, but they are
1429** included in the VFS structure for completeness.
1430** The xRandomness() function attempts to return nBytes bytes
1431** of good-quality randomness into zOut.  The return value is
1432** the actual number of bytes of randomness obtained.
1433** The xSleep() method causes the calling thread to sleep for at
1434** least the number of microseconds given.  ^The xCurrentTime()
1435** method returns a Julian Day Number for the current date and time as
1436** a floating point value.
1437** ^The xCurrentTimeInt64() method returns, as an integer, the Julian
1438** Day Number multipled by 86400000 (the number of milliseconds in
1439** a 24-hour day).
1440** ^SQLite will use the xCurrentTimeInt64() method to get the current
1441** date and time if that method is available (if iVersion is 2 or
1442** greater and the function pointer is not NULL) and will fall back
1443** to xCurrentTime() if xCurrentTimeInt64() is unavailable.
1444**
1445** ^The xSetSystemCall(), xGetSystemCall(), and xNestSystemCall() interfaces
1446** are not used by the SQLite core.  These optional interfaces are provided
1447** by some VFSes to facilitate testing of the VFS code. By overriding
1448** system calls with functions under its control, a test program can
1449** simulate faults and error conditions that would otherwise be difficult
1450** or impossible to induce.  The set of system calls that can be overridden
1451** varies from one VFS to another, and from one version of the same VFS to the
1452** next.  Applications that use these interfaces must be prepared for any
1453** or all of these interfaces to be NULL or for their behavior to change
1454** from one release to the next.  Applications must not attempt to access
1455** any of these methods if the iVersion of the VFS is less than 3.
1456*/
1457typedef struct sqlite3_vfs sqlite3_vfs;
1458typedef void (*sqlite3_syscall_ptr)(void);
1459struct sqlite3_vfs {
1460  int iVersion;            /* Structure version number (currently 3) */
1461  int szOsFile;            /* Size of subclassed sqlite3_file */
1462  int mxPathname;          /* Maximum file pathname length */
1463  sqlite3_vfs *pNext;      /* Next registered VFS */
1464  const char *zName;       /* Name of this virtual file system */
1465  void *pAppData;          /* Pointer to application-specific data */
1466  int (*xOpen)(sqlite3_vfs*, const char *zName, sqlite3_file*,
1467               int flags, int *pOutFlags);
1468  int (*xDelete)(sqlite3_vfs*, const char *zName, int syncDir);
1469  int (*xAccess)(sqlite3_vfs*, const char *zName, int flags, int *pResOut);
1470  int (*xFullPathname)(sqlite3_vfs*, const char *zName, int nOut, char *zOut);
1471  void *(*xDlOpen)(sqlite3_vfs*, const char *zFilename);
1472  void (*xDlError)(sqlite3_vfs*, int nByte, char *zErrMsg);
1473  void (*(*xDlSym)(sqlite3_vfs*,void*, const char *zSymbol))(void);
1474  void (*xDlClose)(sqlite3_vfs*, void*);
1475  int (*xRandomness)(sqlite3_vfs*, int nByte, char *zOut);
1476  int (*xSleep)(sqlite3_vfs*, int microseconds);
1477  int (*xCurrentTime)(sqlite3_vfs*, double*);
1478  int (*xGetLastError)(sqlite3_vfs*, int, char *);
1479  /*
1480  ** The methods above are in version 1 of the sqlite_vfs object
1481  ** definition.  Those that follow are added in version 2 or later
1482  */
1483  int (*xCurrentTimeInt64)(sqlite3_vfs*, sqlite3_int64*);
1484  /*
1485  ** The methods above are in versions 1 and 2 of the sqlite_vfs object.
1486  ** Those below are for version 3 and greater.
1487  */
1488  int (*xSetSystemCall)(sqlite3_vfs*, const char *zName, sqlite3_syscall_ptr);
1489  sqlite3_syscall_ptr (*xGetSystemCall)(sqlite3_vfs*, const char *zName);
1490  const char *(*xNextSystemCall)(sqlite3_vfs*, const char *zName);
1491  /*
1492  ** The methods above are in versions 1 through 3 of the sqlite_vfs object.
1493  ** New fields may be appended in figure versions.  The iVersion
1494  ** value will increment whenever this happens.
1495  */
1496};
1497
1498/*
1499** CAPI3REF: Flags for the xAccess VFS method
1500**
1501** These integer constants can be used as the third parameter to
1502** the xAccess method of an [sqlite3_vfs] object.  They determine
1503** what kind of permissions the xAccess method is looking for.
1504** With SQLITE_ACCESS_EXISTS, the xAccess method
1505** simply checks whether the file exists.
1506** With SQLITE_ACCESS_READWRITE, the xAccess method
1507** checks whether the named directory is both readable and writable
1508** (in other words, if files can be added, removed, and renamed within
1509** the directory).
1510** The SQLITE_ACCESS_READWRITE constant is currently used only by the
1511** [temp_store_directory pragma], though this could change in a future
1512** release of SQLite.
1513** With SQLITE_ACCESS_READ, the xAccess method
1514** checks whether the file is readable.  The SQLITE_ACCESS_READ constant is
1515** currently unused, though it might be used in a future release of
1516** SQLite.
1517*/
1518#define SQLITE_ACCESS_EXISTS    0
1519#define SQLITE_ACCESS_READWRITE 1   /* Used by PRAGMA temp_store_directory */
1520#define SQLITE_ACCESS_READ      2   /* Unused */
1521
1522/*
1523** CAPI3REF: Flags for the xShmLock VFS method
1524**
1525** These integer constants define the various locking operations
1526** allowed by the xShmLock method of [sqlite3_io_methods].  The
1527** following are the only legal combinations of flags to the
1528** xShmLock method:
1529**
1530** <ul>
1531** <li>  SQLITE_SHM_LOCK | SQLITE_SHM_SHARED
1532** <li>  SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE
1533** <li>  SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED
1534** <li>  SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE
1535** </ul>
1536**
1537** When unlocking, the same SHARED or EXCLUSIVE flag must be supplied as
1538** was given no the corresponding lock.
1539**
1540** The xShmLock method can transition between unlocked and SHARED or
1541** between unlocked and EXCLUSIVE.  It cannot transition between SHARED
1542** and EXCLUSIVE.
1543*/
1544#define SQLITE_SHM_UNLOCK       1
1545#define SQLITE_SHM_LOCK         2
1546#define SQLITE_SHM_SHARED       4
1547#define SQLITE_SHM_EXCLUSIVE    8
1548
1549/*
1550** CAPI3REF: Maximum xShmLock index
1551**
1552** The xShmLock method on [sqlite3_io_methods] may use values
1553** between 0 and this upper bound as its "offset" argument.
1554** The SQLite core will never attempt to acquire or release a
1555** lock outside of this range
1556*/
1557#define SQLITE_SHM_NLOCK        8
1558
1559
1560/*
1561** CAPI3REF: Initialize The SQLite Library
1562**
1563** ^The sqlite3_initialize() routine initializes the
1564** SQLite library.  ^The sqlite3_shutdown() routine
1565** deallocates any resources that were allocated by sqlite3_initialize().
1566** These routines are designed to aid in process initialization and
1567** shutdown on embedded systems.  Workstation applications using
1568** SQLite normally do not need to invoke either of these routines.
1569**
1570** A call to sqlite3_initialize() is an "effective" call if it is
1571** the first time sqlite3_initialize() is invoked during the lifetime of
1572** the process, or if it is the first time sqlite3_initialize() is invoked
1573** following a call to sqlite3_shutdown().  ^(Only an effective call
1574** of sqlite3_initialize() does any initialization.  All other calls
1575** are harmless no-ops.)^
1576**
1577** A call to sqlite3_shutdown() is an "effective" call if it is the first
1578** call to sqlite3_shutdown() since the last sqlite3_initialize().  ^(Only
1579** an effective call to sqlite3_shutdown() does any deinitialization.
1580** All other valid calls to sqlite3_shutdown() are harmless no-ops.)^
1581**
1582** The sqlite3_initialize() interface is threadsafe, but sqlite3_shutdown()
1583** is not.  The sqlite3_shutdown() interface must only be called from a
1584** single thread.  All open [database connections] must be closed and all
1585** other SQLite resources must be deallocated prior to invoking
1586** sqlite3_shutdown().
1587**
1588** Among other things, ^sqlite3_initialize() will invoke
1589** sqlite3_os_init().  Similarly, ^sqlite3_shutdown()
1590** will invoke sqlite3_os_end().
1591**
1592** ^The sqlite3_initialize() routine returns [SQLITE_OK] on success.
1593** ^If for some reason, sqlite3_initialize() is unable to initialize
1594** the library (perhaps it is unable to allocate a needed resource such
1595** as a mutex) it returns an [error code] other than [SQLITE_OK].
1596**
1597** ^The sqlite3_initialize() routine is called internally by many other
1598** SQLite interfaces so that an application usually does not need to
1599** invoke sqlite3_initialize() directly.  For example, [sqlite3_open()]
1600** calls sqlite3_initialize() so the SQLite library will be automatically
1601** initialized when [sqlite3_open()] is called if it has not be initialized
1602** already.  ^However, if SQLite is compiled with the [SQLITE_OMIT_AUTOINIT]
1603** compile-time option, then the automatic calls to sqlite3_initialize()
1604** are omitted and the application must call sqlite3_initialize() directly
1605** prior to using any other SQLite interface.  For maximum portability,
1606** it is recommended that applications always invoke sqlite3_initialize()
1607** directly prior to using any other SQLite interface.  Future releases
1608** of SQLite may require this.  In other words, the behavior exhibited
1609** when SQLite is compiled with [SQLITE_OMIT_AUTOINIT] might become the
1610** default behavior in some future release of SQLite.
1611**
1612** The sqlite3_os_init() routine does operating-system specific
1613** initialization of the SQLite library.  The sqlite3_os_end()
1614** routine undoes the effect of sqlite3_os_init().  Typical tasks
1615** performed by these routines include allocation or deallocation
1616** of static resources, initialization of global variables,
1617** setting up a default [sqlite3_vfs] module, or setting up
1618** a default configuration using [sqlite3_config()].
1619**
1620** The application should never invoke either sqlite3_os_init()
1621** or sqlite3_os_end() directly.  The application should only invoke
1622** sqlite3_initialize() and sqlite3_shutdown().  The sqlite3_os_init()
1623** interface is called automatically by sqlite3_initialize() and
1624** sqlite3_os_end() is called by sqlite3_shutdown().  Appropriate
1625** implementations for sqlite3_os_init() and sqlite3_os_end()
1626** are built into SQLite when it is compiled for Unix, Windows, or OS/2.
1627** When [custom builds | built for other platforms]
1628** (using the [SQLITE_OS_OTHER=1] compile-time
1629** option) the application must supply a suitable implementation for
1630** sqlite3_os_init() and sqlite3_os_end().  An application-supplied
1631** implementation of sqlite3_os_init() or sqlite3_os_end()
1632** must return [SQLITE_OK] on success and some other [error code] upon
1633** failure.
1634*/
1635SQLITE_API int sqlite3_initialize(void);
1636SQLITE_API int sqlite3_shutdown(void);
1637SQLITE_API int sqlite3_os_init(void);
1638SQLITE_API int sqlite3_os_end(void);
1639
1640/*
1641** CAPI3REF: Configuring The SQLite Library
1642**
1643** The sqlite3_config() interface is used to make global configuration
1644** changes to SQLite in order to tune SQLite to the specific needs of
1645** the application.  The default configuration is recommended for most
1646** applications and so this routine is usually not necessary.  It is
1647** provided to support rare applications with unusual needs.
1648**
1649** The sqlite3_config() interface is not threadsafe.  The application
1650** must insure that no other SQLite interfaces are invoked by other
1651** threads while sqlite3_config() is running.  Furthermore, sqlite3_config()
1652** may only be invoked prior to library initialization using
1653** [sqlite3_initialize()] or after shutdown by [sqlite3_shutdown()].
1654** ^If sqlite3_config() is called after [sqlite3_initialize()] and before
1655** [sqlite3_shutdown()] then it will return SQLITE_MISUSE.
1656** Note, however, that ^sqlite3_config() can be called as part of the
1657** implementation of an application-defined [sqlite3_os_init()].
1658**
1659** The first argument to sqlite3_config() is an integer
1660** [SQLITE_CONFIG_SINGLETHREAD | configuration option] that determines
1661** what property of SQLite is to be configured.  Subsequent arguments
1662** vary depending on the [SQLITE_CONFIG_SINGLETHREAD | configuration option]
1663** in the first argument.
1664**
1665** ^When a configuration option is set, sqlite3_config() returns [SQLITE_OK].
1666** ^If the option is unknown or SQLite is unable to set the option
1667** then this routine returns a non-zero [error code].
1668*/
1669SQLITE_API int sqlite3_config(int, ...);
1670
1671/*
1672** CAPI3REF: Configure database connections
1673**
1674** The sqlite3_db_config() interface is used to make configuration
1675** changes to a [database connection].  The interface is similar to
1676** [sqlite3_config()] except that the changes apply to a single
1677** [database connection] (specified in the first argument).
1678**
1679** The second argument to sqlite3_db_config(D,V,...)  is the
1680** [SQLITE_DBCONFIG_LOOKASIDE | configuration verb] - an integer code
1681** that indicates what aspect of the [database connection] is being configured.
1682** Subsequent arguments vary depending on the configuration verb.
1683**
1684** ^Calls to sqlite3_db_config() return SQLITE_OK if and only if
1685** the call is considered successful.
1686*/
1687SQLITE_API int sqlite3_db_config(sqlite3*, int op, ...);
1688
1689/*
1690** CAPI3REF: Memory Allocation Routines
1691**
1692** An instance of this object defines the interface between SQLite
1693** and low-level memory allocation routines.
1694**
1695** This object is used in only one place in the SQLite interface.
1696** A pointer to an instance of this object is the argument to
1697** [sqlite3_config()] when the configuration option is
1698** [SQLITE_CONFIG_MALLOC] or [SQLITE_CONFIG_GETMALLOC].
1699** By creating an instance of this object
1700** and passing it to [sqlite3_config]([SQLITE_CONFIG_MALLOC])
1701** during configuration, an application can specify an alternative
1702** memory allocation subsystem for SQLite to use for all of its
1703** dynamic memory needs.
1704**
1705** Note that SQLite comes with several [built-in memory allocators]
1706** that are perfectly adequate for the overwhelming majority of applications
1707** and that this object is only useful to a tiny minority of applications
1708** with specialized memory allocation requirements.  This object is
1709** also used during testing of SQLite in order to specify an alternative
1710** memory allocator that simulates memory out-of-memory conditions in
1711** order to verify that SQLite recovers gracefully from such
1712** conditions.
1713**
1714** The xMalloc and xFree methods must work like the
1715** malloc() and free() functions from the standard C library.
1716** The xRealloc method must work like realloc() from the standard C library
1717** with the exception that if the second argument to xRealloc is zero,
1718** xRealloc must be a no-op - it must not perform any allocation or
1719** deallocation.  ^SQLite guarantees that the second argument to
1720** xRealloc is always a value returned by a prior call to xRoundup.
1721** And so in cases where xRoundup always returns a positive number,
1722** xRealloc can perform exactly as the standard library realloc() and
1723** still be in compliance with this specification.
1724**
1725** xSize should return the allocated size of a memory allocation
1726** previously obtained from xMalloc or xRealloc.  The allocated size
1727** is always at least as big as the requested size but may be larger.
1728**
1729** The xRoundup method returns what would be the allocated size of
1730** a memory allocation given a particular requested size.  Most memory
1731** allocators round up memory allocations at least to the next multiple
1732** of 8.  Some allocators round up to a larger multiple or to a power of 2.
1733** Every memory allocation request coming in through [sqlite3_malloc()]
1734** or [sqlite3_realloc()] first calls xRoundup.  If xRoundup returns 0,
1735** that causes the corresponding memory allocation to fail.
1736**
1737** The xInit method initializes the memory allocator.  (For example,
1738** it might allocate any require mutexes or initialize internal data
1739** structures.  The xShutdown method is invoked (indirectly) by
1740** [sqlite3_shutdown()] and should deallocate any resources acquired
1741** by xInit.  The pAppData pointer is used as the only parameter to
1742** xInit and xShutdown.
1743**
1744** SQLite holds the [SQLITE_MUTEX_STATIC_MASTER] mutex when it invokes
1745** the xInit method, so the xInit method need not be threadsafe.  The
1746** xShutdown method is only called from [sqlite3_shutdown()] so it does
1747** not need to be threadsafe either.  For all other methods, SQLite
1748** holds the [SQLITE_MUTEX_STATIC_MEM] mutex as long as the
1749** [SQLITE_CONFIG_MEMSTATUS] configuration option is turned on (which
1750** it is by default) and so the methods are automatically serialized.
1751** However, if [SQLITE_CONFIG_MEMSTATUS] is disabled, then the other
1752** methods must be threadsafe or else make their own arrangements for
1753** serialization.
1754**
1755** SQLite will never invoke xInit() more than once without an intervening
1756** call to xShutdown().
1757*/
1758typedef struct sqlite3_mem_methods sqlite3_mem_methods;
1759struct sqlite3_mem_methods {
1760  void *(*xMalloc)(int);         /* Memory allocation function */
1761  void (*xFree)(void*);          /* Free a prior allocation */
1762  void *(*xRealloc)(void*,int);  /* Resize an allocation */
1763  int (*xSize)(void*);           /* Return the size of an allocation */
1764  int (*xRoundup)(int);          /* Round up request size to allocation size */
1765  int (*xInit)(void*);           /* Initialize the memory allocator */
1766  void (*xShutdown)(void*);      /* Deinitialize the memory allocator */
1767  void *pAppData;                /* Argument to xInit() and xShutdown() */
1768};
1769
1770/*
1771** CAPI3REF: Configuration Options
1772**
1773** These constants are the available integer configuration options that
1774** can be passed as the first argument to the [sqlite3_config()] interface.
1775**
1776** New configuration options may be added in future releases of SQLite.
1777** Existing configuration options might be discontinued.  Applications
1778** should check the return code from [sqlite3_config()] to make sure that
1779** the call worked.  The [sqlite3_config()] interface will return a
1780** non-zero [error code] if a discontinued or unsupported configuration option
1781** is invoked.
1782**
1783** <dl>
1784** <dt>SQLITE_CONFIG_SINGLETHREAD</dt>
1785** <dd>There are no arguments to this option.  ^This option sets the
1786** [threading mode] to Single-thread.  In other words, it disables
1787** all mutexing and puts SQLite into a mode where it can only be used
1788** by a single thread.   ^If SQLite is compiled with
1789** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
1790** it is not possible to change the [threading mode] from its default
1791** value of Single-thread and so [sqlite3_config()] will return
1792** [SQLITE_ERROR] if called with the SQLITE_CONFIG_SINGLETHREAD
1793** configuration option.</dd>
1794**
1795** <dt>SQLITE_CONFIG_MULTITHREAD</dt>
1796** <dd>There are no arguments to this option.  ^This option sets the
1797** [threading mode] to Multi-thread.  In other words, it disables
1798** mutexing on [database connection] and [prepared statement] objects.
1799** The application is responsible for serializing access to
1800** [database connections] and [prepared statements].  But other mutexes
1801** are enabled so that SQLite will be safe to use in a multi-threaded
1802** environment as long as no two threads attempt to use the same
1803** [database connection] at the same time.  ^If SQLite is compiled with
1804** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
1805** it is not possible to set the Multi-thread [threading mode] and
1806** [sqlite3_config()] will return [SQLITE_ERROR] if called with the
1807** SQLITE_CONFIG_MULTITHREAD configuration option.</dd>
1808**
1809** <dt>SQLITE_CONFIG_SERIALIZED</dt>
1810** <dd>There are no arguments to this option.  ^This option sets the
1811** [threading mode] to Serialized. In other words, this option enables
1812** all mutexes including the recursive
1813** mutexes on [database connection] and [prepared statement] objects.
1814** In this mode (which is the default when SQLite is compiled with
1815** [SQLITE_THREADSAFE=1]) the SQLite library will itself serialize access
1816** to [database connections] and [prepared statements] so that the
1817** application is free to use the same [database connection] or the
1818** same [prepared statement] in different threads at the same time.
1819** ^If SQLite is compiled with
1820** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
1821** it is not possible to set the Serialized [threading mode] and
1822** [sqlite3_config()] will return [SQLITE_ERROR] if called with the
1823** SQLITE_CONFIG_SERIALIZED configuration option.</dd>
1824**
1825** <dt>SQLITE_CONFIG_MALLOC</dt>
1826** <dd> ^(This option takes a single argument which is a pointer to an
1827** instance of the [sqlite3_mem_methods] structure.  The argument specifies
1828** alternative low-level memory allocation routines to be used in place of
1829** the memory allocation routines built into SQLite.)^ ^SQLite makes
1830** its own private copy of the content of the [sqlite3_mem_methods] structure
1831** before the [sqlite3_config()] call returns.</dd>
1832**
1833** <dt>SQLITE_CONFIG_GETMALLOC</dt>
1834** <dd> ^(This option takes a single argument which is a pointer to an
1835** instance of the [sqlite3_mem_methods] structure.  The [sqlite3_mem_methods]
1836** structure is filled with the currently defined memory allocation routines.)^
1837** This option can be used to overload the default memory allocation
1838** routines with a wrapper that simulations memory allocation failure or
1839** tracks memory usage, for example. </dd>
1840**
1841** <dt>SQLITE_CONFIG_MEMSTATUS</dt>
1842** <dd> ^This option takes single argument of type int, interpreted as a
1843** boolean, which enables or disables the collection of memory allocation
1844** statistics. ^(When memory allocation statistics are disabled, the
1845** following SQLite interfaces become non-operational:
1846**   <ul>
1847**   <li> [sqlite3_memory_used()]
1848**   <li> [sqlite3_memory_highwater()]
1849**   <li> [sqlite3_soft_heap_limit64()]
1850**   <li> [sqlite3_status()]
1851**   </ul>)^
1852** ^Memory allocation statistics are enabled by default unless SQLite is
1853** compiled with [SQLITE_DEFAULT_MEMSTATUS]=0 in which case memory
1854** allocation statistics are disabled by default.
1855** </dd>
1856**
1857** <dt>SQLITE_CONFIG_SCRATCH</dt>
1858** <dd> ^This option specifies a static memory buffer that SQLite can use for
1859** scratch memory.  There are three arguments:  A pointer an 8-byte
1860** aligned memory buffer from which the scratch allocations will be
1861** drawn, the size of each scratch allocation (sz),
1862** and the maximum number of scratch allocations (N).  The sz
1863** argument must be a multiple of 16.
1864** The first argument must be a pointer to an 8-byte aligned buffer
1865** of at least sz*N bytes of memory.
1866** ^SQLite will use no more than two scratch buffers per thread.  So
1867** N should be set to twice the expected maximum number of threads.
1868** ^SQLite will never require a scratch buffer that is more than 6
1869** times the database page size. ^If SQLite needs needs additional
1870** scratch memory beyond what is provided by this configuration option, then
1871** [sqlite3_malloc()] will be used to obtain the memory needed.</dd>
1872**
1873** <dt>SQLITE_CONFIG_PAGECACHE</dt>
1874** <dd> ^This option specifies a static memory buffer that SQLite can use for
1875** the database page cache with the default page cache implemenation.
1876** This configuration should not be used if an application-define page
1877** cache implementation is loaded using the SQLITE_CONFIG_PCACHE option.
1878** There are three arguments to this option: A pointer to 8-byte aligned
1879** memory, the size of each page buffer (sz), and the number of pages (N).
1880** The sz argument should be the size of the largest database page
1881** (a power of two between 512 and 32768) plus a little extra for each
1882** page header.  ^The page header size is 20 to 40 bytes depending on
1883** the host architecture.  ^It is harmless, apart from the wasted memory,
1884** to make sz a little too large.  The first
1885** argument should point to an allocation of at least sz*N bytes of memory.
1886** ^SQLite will use the memory provided by the first argument to satisfy its
1887** memory needs for the first N pages that it adds to cache.  ^If additional
1888** page cache memory is needed beyond what is provided by this option, then
1889** SQLite goes to [sqlite3_malloc()] for the additional storage space.
1890** The pointer in the first argument must
1891** be aligned to an 8-byte boundary or subsequent behavior of SQLite
1892** will be undefined.</dd>
1893**
1894** <dt>SQLITE_CONFIG_HEAP</dt>
1895** <dd> ^This option specifies a static memory buffer that SQLite will use
1896** for all of its dynamic memory allocation needs beyond those provided
1897** for by [SQLITE_CONFIG_SCRATCH] and [SQLITE_CONFIG_PAGECACHE].
1898** There are three arguments: An 8-byte aligned pointer to the memory,
1899** the number of bytes in the memory buffer, and the minimum allocation size.
1900** ^If the first pointer (the memory pointer) is NULL, then SQLite reverts
1901** to using its default memory allocator (the system malloc() implementation),
1902** undoing any prior invocation of [SQLITE_CONFIG_MALLOC].  ^If the
1903** memory pointer is not NULL and either [SQLITE_ENABLE_MEMSYS3] or
1904** [SQLITE_ENABLE_MEMSYS5] are defined, then the alternative memory
1905** allocator is engaged to handle all of SQLites memory allocation needs.
1906** The first pointer (the memory pointer) must be aligned to an 8-byte
1907** boundary or subsequent behavior of SQLite will be undefined.
1908** The minimum allocation size is capped at 2^12. Reasonable values
1909** for the minimum allocation size are 2^5 through 2^8.</dd>
1910**
1911** <dt>SQLITE_CONFIG_MUTEX</dt>
1912** <dd> ^(This option takes a single argument which is a pointer to an
1913** instance of the [sqlite3_mutex_methods] structure.  The argument specifies
1914** alternative low-level mutex routines to be used in place
1915** the mutex routines built into SQLite.)^  ^SQLite makes a copy of the
1916** content of the [sqlite3_mutex_methods] structure before the call to
1917** [sqlite3_config()] returns. ^If SQLite is compiled with
1918** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
1919** the entire mutexing subsystem is omitted from the build and hence calls to
1920** [sqlite3_config()] with the SQLITE_CONFIG_MUTEX configuration option will
1921** return [SQLITE_ERROR].</dd>
1922**
1923** <dt>SQLITE_CONFIG_GETMUTEX</dt>
1924** <dd> ^(This option takes a single argument which is a pointer to an
1925** instance of the [sqlite3_mutex_methods] structure.  The
1926** [sqlite3_mutex_methods]
1927** structure is filled with the currently defined mutex routines.)^
1928** This option can be used to overload the default mutex allocation
1929** routines with a wrapper used to track mutex usage for performance
1930** profiling or testing, for example.   ^If SQLite is compiled with
1931** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
1932** the entire mutexing subsystem is omitted from the build and hence calls to
1933** [sqlite3_config()] with the SQLITE_CONFIG_GETMUTEX configuration option will
1934** return [SQLITE_ERROR].</dd>
1935**
1936** <dt>SQLITE_CONFIG_LOOKASIDE</dt>
1937** <dd> ^(This option takes two arguments that determine the default
1938** memory allocation for the lookaside memory allocator on each
1939** [database connection].  The first argument is the
1940** size of each lookaside buffer slot and the second is the number of
1941** slots allocated to each database connection.)^  ^(This option sets the
1942** <i>default</i> lookaside size. The [SQLITE_DBCONFIG_LOOKASIDE]
1943** verb to [sqlite3_db_config()] can be used to change the lookaside
1944** configuration on individual connections.)^ </dd>
1945**
1946** <dt>SQLITE_CONFIG_PCACHE</dt>
1947** <dd> ^(This option takes a single argument which is a pointer to
1948** an [sqlite3_pcache_methods] object.  This object specifies the interface
1949** to a custom page cache implementation.)^  ^SQLite makes a copy of the
1950** object and uses it for page cache memory allocations.</dd>
1951**
1952** <dt>SQLITE_CONFIG_GETPCACHE</dt>
1953** <dd> ^(This option takes a single argument which is a pointer to an
1954** [sqlite3_pcache_methods] object.  SQLite copies of the current
1955** page cache implementation into that object.)^ </dd>
1956**
1957** <dt>SQLITE_CONFIG_LOG</dt>
1958** <dd> ^The SQLITE_CONFIG_LOG option takes two arguments: a pointer to a
1959** function with a call signature of void(*)(void*,int,const char*),
1960** and a pointer to void. ^If the function pointer is not NULL, it is
1961** invoked by [sqlite3_log()] to process each logging event.  ^If the
1962** function pointer is NULL, the [sqlite3_log()] interface becomes a no-op.
1963** ^The void pointer that is the second argument to SQLITE_CONFIG_LOG is
1964** passed through as the first parameter to the application-defined logger
1965** function whenever that function is invoked.  ^The second parameter to
1966** the logger function is a copy of the first parameter to the corresponding
1967** [sqlite3_log()] call and is intended to be a [result code] or an
1968** [extended result code].  ^The third parameter passed to the logger is
1969** log message after formatting via [sqlite3_snprintf()].
1970** The SQLite logging interface is not reentrant; the logger function
1971** supplied by the application must not invoke any SQLite interface.
1972** In a multi-threaded application, the application-defined logger
1973** function must be threadsafe. </dd>
1974**
1975** </dl>
1976*/
1977#define SQLITE_CONFIG_SINGLETHREAD  1  /* nil */
1978#define SQLITE_CONFIG_MULTITHREAD   2  /* nil */
1979#define SQLITE_CONFIG_SERIALIZED    3  /* nil */
1980#define SQLITE_CONFIG_MALLOC        4  /* sqlite3_mem_methods* */
1981#define SQLITE_CONFIG_GETMALLOC     5  /* sqlite3_mem_methods* */
1982#define SQLITE_CONFIG_SCRATCH       6  /* void*, int sz, int N */
1983#define SQLITE_CONFIG_PAGECACHE     7  /* void*, int sz, int N */
1984#define SQLITE_CONFIG_HEAP          8  /* void*, int nByte, int min */
1985#define SQLITE_CONFIG_MEMSTATUS     9  /* boolean */
1986#define SQLITE_CONFIG_MUTEX        10  /* sqlite3_mutex_methods* */
1987#define SQLITE_CONFIG_GETMUTEX     11  /* sqlite3_mutex_methods* */
1988/* previously SQLITE_CONFIG_CHUNKALLOC 12 which is now unused. */
1989#define SQLITE_CONFIG_LOOKASIDE    13  /* int int */
1990#define SQLITE_CONFIG_PCACHE       14  /* sqlite3_pcache_methods* */
1991#define SQLITE_CONFIG_GETPCACHE    15  /* sqlite3_pcache_methods* */
1992#define SQLITE_CONFIG_LOG          16  /* xFunc, void* */
1993
1994/*
1995** CAPI3REF: Database Connection Configuration Options
1996**
1997** These constants are the available integer configuration options that
1998** can be passed as the second argument to the [sqlite3_db_config()] interface.
1999**
2000** New configuration options may be added in future releases of SQLite.
2001** Existing configuration options might be discontinued.  Applications
2002** should check the return code from [sqlite3_db_config()] to make sure that
2003** the call worked.  ^The [sqlite3_db_config()] interface will return a
2004** non-zero [error code] if a discontinued or unsupported configuration option
2005** is invoked.
2006**
2007** <dl>
2008** <dt>SQLITE_DBCONFIG_LOOKASIDE</dt>
2009** <dd> ^This option takes three additional arguments that determine the
2010** [lookaside memory allocator] configuration for the [database connection].
2011** ^The first argument (the third parameter to [sqlite3_db_config()] is a
2012** pointer to a memory buffer to use for lookaside memory.
2013** ^The first argument after the SQLITE_DBCONFIG_LOOKASIDE verb
2014** may be NULL in which case SQLite will allocate the
2015** lookaside buffer itself using [sqlite3_malloc()]. ^The second argument is the
2016** size of each lookaside buffer slot.  ^The third argument is the number of
2017** slots.  The size of the buffer in the first argument must be greater than
2018** or equal to the product of the second and third arguments.  The buffer
2019** must be aligned to an 8-byte boundary.  ^If the second argument to
2020** SQLITE_DBCONFIG_LOOKASIDE is not a multiple of 8, it is internally
2021** rounded down to the next smaller multiple of 8.  ^(The lookaside memory
2022** configuration for a database connection can only be changed when that
2023** connection is not currently using lookaside memory, or in other words
2024** when the "current value" returned by
2025** [sqlite3_db_status](D,[SQLITE_CONFIG_LOOKASIDE],...) is zero.
2026** Any attempt to change the lookaside memory configuration when lookaside
2027** memory is in use leaves the configuration unchanged and returns
2028** [SQLITE_BUSY].)^</dd>
2029**
2030** <dt>SQLITE_DBCONFIG_ENABLE_FKEY</dt>
2031** <dd> ^This option is used to enable or disable the enforcement of
2032** [foreign key constraints].  There should be two additional arguments.
2033** The first argument is an integer which is 0 to disable FK enforcement,
2034** positive to enable FK enforcement or negative to leave FK enforcement
2035** unchanged.  The second parameter is a pointer to an integer into which
2036** is written 0 or 1 to indicate whether FK enforcement is off or on
2037** following this call.  The second parameter may be a NULL pointer, in
2038** which case the FK enforcement setting is not reported back. </dd>
2039**
2040** <dt>SQLITE_DBCONFIG_ENABLE_TRIGGER</dt>
2041** <dd> ^This option is used to enable or disable [CREATE TRIGGER | triggers].
2042** There should be two additional arguments.
2043** The first argument is an integer which is 0 to disable triggers,
2044** positive to enable triggers or negative to leave the setting unchanged.
2045** The second parameter is a pointer to an integer into which
2046** is written 0 or 1 to indicate whether triggers are disabled or enabled
2047** following this call.  The second parameter may be a NULL pointer, in
2048** which case the trigger setting is not reported back. </dd>
2049**
2050** </dl>
2051*/
2052#define SQLITE_DBCONFIG_LOOKASIDE       1001  /* void* int int */
2053#define SQLITE_DBCONFIG_ENABLE_FKEY     1002  /* int int* */
2054#define SQLITE_DBCONFIG_ENABLE_TRIGGER  1003  /* int int* */
2055
2056
2057/*
2058** CAPI3REF: Enable Or Disable Extended Result Codes
2059**
2060** ^The sqlite3_extended_result_codes() routine enables or disables the
2061** [extended result codes] feature of SQLite. ^The extended result
2062** codes are disabled by default for historical compatibility.
2063*/
2064SQLITE_API int sqlite3_extended_result_codes(sqlite3*, int onoff);
2065
2066/*
2067** CAPI3REF: Last Insert Rowid
2068**
2069** ^Each entry in an SQLite table has a unique 64-bit signed
2070** integer key called the [ROWID | "rowid"]. ^The rowid is always available
2071** as an undeclared column named ROWID, OID, or _ROWID_ as long as those
2072** names are not also used by explicitly declared columns. ^If
2073** the table has a column of type [INTEGER PRIMARY KEY] then that column
2074** is another alias for the rowid.
2075**
2076** ^This routine returns the [rowid] of the most recent
2077** successful [INSERT] into the database from the [database connection]
2078** in the first argument.  ^If no successful [INSERT]s
2079** have ever occurred on that database connection, zero is returned.
2080**
2081** ^(If an [INSERT] occurs within a trigger, then the [rowid] of the inserted
2082** row is returned by this routine as long as the trigger is running.
2083** But once the trigger terminates, the value returned by this routine
2084** reverts to the last value inserted before the trigger fired.)^
2085**
2086** ^An [INSERT] that fails due to a constraint violation is not a
2087** successful [INSERT] and does not change the value returned by this
2088** routine.  ^Thus INSERT OR FAIL, INSERT OR IGNORE, INSERT OR ROLLBACK,
2089** and INSERT OR ABORT make no changes to the return value of this
2090** routine when their insertion fails.  ^(When INSERT OR REPLACE
2091** encounters a constraint violation, it does not fail.  The
2092** INSERT continues to completion after deleting rows that caused
2093** the constraint problem so INSERT OR REPLACE will always change
2094** the return value of this interface.)^
2095**
2096** ^For the purposes of this routine, an [INSERT] is considered to
2097** be successful even if it is subsequently rolled back.
2098**
2099** This function is accessible to SQL statements via the
2100** [last_insert_rowid() SQL function].
2101**
2102** If a separate thread performs a new [INSERT] on the same
2103** database connection while the [sqlite3_last_insert_rowid()]
2104** function is running and thus changes the last insert [rowid],
2105** then the value returned by [sqlite3_last_insert_rowid()] is
2106** unpredictable and might not equal either the old or the new
2107** last insert [rowid].
2108*/
2109SQLITE_API sqlite3_int64 sqlite3_last_insert_rowid(sqlite3*);
2110
2111/*
2112** CAPI3REF: Count The Number Of Rows Modified
2113**
2114** ^This function returns the number of database rows that were changed
2115** or inserted or deleted by the most recently completed SQL statement
2116** on the [database connection] specified by the first parameter.
2117** ^(Only changes that are directly specified by the [INSERT], [UPDATE],
2118** or [DELETE] statement are counted.  Auxiliary changes caused by
2119** triggers or [foreign key actions] are not counted.)^ Use the
2120** [sqlite3_total_changes()] function to find the total number of changes
2121** including changes caused by triggers and foreign key actions.
2122**
2123** ^Changes to a view that are simulated by an [INSTEAD OF trigger]
2124** are not counted.  Only real table changes are counted.
2125**
2126** ^(A "row change" is a change to a single row of a single table
2127** caused by an INSERT, DELETE, or UPDATE statement.  Rows that
2128** are changed as side effects of [REPLACE] constraint resolution,
2129** rollback, ABORT processing, [DROP TABLE], or by any other
2130** mechanisms do not count as direct row changes.)^
2131**
2132** A "trigger context" is a scope of execution that begins and
2133** ends with the script of a [CREATE TRIGGER | trigger].
2134** Most SQL statements are
2135** evaluated outside of any trigger.  This is the "top level"
2136** trigger context.  If a trigger fires from the top level, a
2137** new trigger context is entered for the duration of that one
2138** trigger.  Subtriggers create subcontexts for their duration.
2139**
2140** ^Calling [sqlite3_exec()] or [sqlite3_step()] recursively does
2141** not create a new trigger context.
2142**
2143** ^This function returns the number of direct row changes in the
2144** most recent INSERT, UPDATE, or DELETE statement within the same
2145** trigger context.
2146**
2147** ^Thus, when called from the top level, this function returns the
2148** number of changes in the most recent INSERT, UPDATE, or DELETE
2149** that also occurred at the top level.  ^(Within the body of a trigger,
2150** the sqlite3_changes() interface can be called to find the number of
2151** changes in the most recently completed INSERT, UPDATE, or DELETE
2152** statement within the body of the same trigger.
2153** However, the number returned does not include changes
2154** caused by subtriggers since those have their own context.)^
2155**
2156** See also the [sqlite3_total_changes()] interface, the
2157** [count_changes pragma], and the [changes() SQL function].
2158**
2159** If a separate thread makes changes on the same database connection
2160** while [sqlite3_changes()] is running then the value returned
2161** is unpredictable and not meaningful.
2162*/
2163SQLITE_API int sqlite3_changes(sqlite3*);
2164
2165/*
2166** CAPI3REF: Total Number Of Rows Modified
2167**
2168** ^This function returns the number of row changes caused by [INSERT],
2169** [UPDATE] or [DELETE] statements since the [database connection] was opened.
2170** ^(The count returned by sqlite3_total_changes() includes all changes
2171** from all [CREATE TRIGGER | trigger] contexts and changes made by
2172** [foreign key actions]. However,
2173** the count does not include changes used to implement [REPLACE] constraints,
2174** do rollbacks or ABORT processing, or [DROP TABLE] processing.  The
2175** count does not include rows of views that fire an [INSTEAD OF trigger],
2176** though if the INSTEAD OF trigger makes changes of its own, those changes
2177** are counted.)^
2178** ^The sqlite3_total_changes() function counts the changes as soon as
2179** the statement that makes them is completed (when the statement handle
2180** is passed to [sqlite3_reset()] or [sqlite3_finalize()]).
2181**
2182** See also the [sqlite3_changes()] interface, the
2183** [count_changes pragma], and the [total_changes() SQL function].
2184**
2185** If a separate thread makes changes on the same database connection
2186** while [sqlite3_total_changes()] is running then the value
2187** returned is unpredictable and not meaningful.
2188*/
2189SQLITE_API int sqlite3_total_changes(sqlite3*);
2190
2191/*
2192** CAPI3REF: Interrupt A Long-Running Query
2193**
2194** ^This function causes any pending database operation to abort and
2195** return at its earliest opportunity. This routine is typically
2196** called in response to a user action such as pressing "Cancel"
2197** or Ctrl-C where the user wants a long query operation to halt
2198** immediately.
2199**
2200** ^It is safe to call this routine from a thread different from the
2201** thread that is currently running the database operation.  But it
2202** is not safe to call this routine with a [database connection] that
2203** is closed or might close before sqlite3_interrupt() returns.
2204**
2205** ^If an SQL operation is very nearly finished at the time when
2206** sqlite3_interrupt() is called, then it might not have an opportunity
2207** to be interrupted and might continue to completion.
2208**
2209** ^An SQL operation that is interrupted will return [SQLITE_INTERRUPT].
2210** ^If the interrupted SQL operation is an INSERT, UPDATE, or DELETE
2211** that is inside an explicit transaction, then the entire transaction
2212** will be rolled back automatically.
2213**
2214** ^The sqlite3_interrupt(D) call is in effect until all currently running
2215** SQL statements on [database connection] D complete.  ^Any new SQL statements
2216** that are started after the sqlite3_interrupt() call and before the
2217** running statements reaches zero are interrupted as if they had been
2218** running prior to the sqlite3_interrupt() call.  ^New SQL statements
2219** that are started after the running statement count reaches zero are
2220** not effected by the sqlite3_interrupt().
2221** ^A call to sqlite3_interrupt(D) that occurs when there are no running
2222** SQL statements is a no-op and has no effect on SQL statements
2223** that are started after the sqlite3_interrupt() call returns.
2224**
2225** If the database connection closes while [sqlite3_interrupt()]
2226** is running then bad things will likely happen.
2227*/
2228SQLITE_API void sqlite3_interrupt(sqlite3*);
2229
2230/*
2231** CAPI3REF: Determine If An SQL Statement Is Complete
2232**
2233** These routines are useful during command-line input to determine if the
2234** currently entered text seems to form a complete SQL statement or
2235** if additional input is needed before sending the text into
2236** SQLite for parsing.  ^These routines return 1 if the input string
2237** appears to be a complete SQL statement.  ^A statement is judged to be
2238** complete if it ends with a semicolon token and is not a prefix of a
2239** well-formed CREATE TRIGGER statement.  ^Semicolons that are embedded within
2240** string literals or quoted identifier names or comments are not
2241** independent tokens (they are part of the token in which they are
2242** embedded) and thus do not count as a statement terminator.  ^Whitespace
2243** and comments that follow the final semicolon are ignored.
2244**
2245** ^These routines return 0 if the statement is incomplete.  ^If a
2246** memory allocation fails, then SQLITE_NOMEM is returned.
2247**
2248** ^These routines do not parse the SQL statements thus
2249** will not detect syntactically incorrect SQL.
2250**
2251** ^(If SQLite has not been initialized using [sqlite3_initialize()] prior
2252** to invoking sqlite3_complete16() then sqlite3_initialize() is invoked
2253** automatically by sqlite3_complete16().  If that initialization fails,
2254** then the return value from sqlite3_complete16() will be non-zero
2255** regardless of whether or not the input SQL is complete.)^
2256**
2257** The input to [sqlite3_complete()] must be a zero-terminated
2258** UTF-8 string.
2259**
2260** The input to [sqlite3_complete16()] must be a zero-terminated
2261** UTF-16 string in native byte order.
2262*/
2263SQLITE_API int sqlite3_complete(const char *sql);
2264SQLITE_API int sqlite3_complete16(const void *sql);
2265
2266/*
2267** CAPI3REF: Register A Callback To Handle SQLITE_BUSY Errors
2268**
2269** ^This routine sets a callback function that might be invoked whenever
2270** an attempt is made to open a database table that another thread
2271** or process has locked.
2272**
2273** ^If the busy callback is NULL, then [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED]
2274** is returned immediately upon encountering the lock.  ^If the busy callback
2275** is not NULL, then the callback might be invoked with two arguments.
2276**
2277** ^The first argument to the busy handler is a copy of the void* pointer which
2278** is the third argument to sqlite3_busy_handler().  ^The second argument to
2279** the busy handler callback is the number of times that the busy handler has
2280** been invoked for this locking event.  ^If the
2281** busy callback returns 0, then no additional attempts are made to
2282** access the database and [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED] is returned.
2283** ^If the callback returns non-zero, then another attempt
2284** is made to open the database for reading and the cycle repeats.
2285**
2286** The presence of a busy handler does not guarantee that it will be invoked
2287** when there is lock contention. ^If SQLite determines that invoking the busy
2288** handler could result in a deadlock, it will go ahead and return [SQLITE_BUSY]
2289** or [SQLITE_IOERR_BLOCKED] instead of invoking the busy handler.
2290** Consider a scenario where one process is holding a read lock that
2291** it is trying to promote to a reserved lock and
2292** a second process is holding a reserved lock that it is trying
2293** to promote to an exclusive lock.  The first process cannot proceed
2294** because it is blocked by the second and the second process cannot
2295** proceed because it is blocked by the first.  If both processes
2296** invoke the busy handlers, neither will make any progress.  Therefore,
2297** SQLite returns [SQLITE_BUSY] for the first process, hoping that this
2298** will induce the first process to release its read lock and allow
2299** the second process to proceed.
2300**
2301** ^The default busy callback is NULL.
2302**
2303** ^The [SQLITE_BUSY] error is converted to [SQLITE_IOERR_BLOCKED]
2304** when SQLite is in the middle of a large transaction where all the
2305** changes will not fit into the in-memory cache.  SQLite will
2306** already hold a RESERVED lock on the database file, but it needs
2307** to promote this lock to EXCLUSIVE so that it can spill cache
2308** pages into the database file without harm to concurrent
2309** readers.  ^If it is unable to promote the lock, then the in-memory
2310** cache will be left in an inconsistent state and so the error
2311** code is promoted from the relatively benign [SQLITE_BUSY] to
2312** the more severe [SQLITE_IOERR_BLOCKED].  ^This error code promotion
2313** forces an automatic rollback of the changes.  See the
2314** <a href="/cvstrac/wiki?p=CorruptionFollowingBusyError">
2315** CorruptionFollowingBusyError</a> wiki page for a discussion of why
2316** this is important.
2317**
2318** ^(There can only be a single busy handler defined for each
2319** [database connection].  Setting a new busy handler clears any
2320** previously set handler.)^  ^Note that calling [sqlite3_busy_timeout()]
2321** will also set or clear the busy handler.
2322**
2323** The busy callback should not take any actions which modify the
2324** database connection that invoked the busy handler.  Any such actions
2325** result in undefined behavior.
2326**
2327** A busy handler must not close the database connection
2328** or [prepared statement] that invoked the busy handler.
2329*/
2330SQLITE_API int sqlite3_busy_handler(sqlite3*, int(*)(void*,int), void*);
2331
2332/*
2333** CAPI3REF: Set A Busy Timeout
2334**
2335** ^This routine sets a [sqlite3_busy_handler | busy handler] that sleeps
2336** for a specified amount of time when a table is locked.  ^The handler
2337** will sleep multiple times until at least "ms" milliseconds of sleeping
2338** have accumulated.  ^After at least "ms" milliseconds of sleeping,
2339** the handler returns 0 which causes [sqlite3_step()] to return
2340** [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED].
2341**
2342** ^Calling this routine with an argument less than or equal to zero
2343** turns off all busy handlers.
2344**
2345** ^(There can only be a single busy handler for a particular
2346** [database connection] any any given moment.  If another busy handler
2347** was defined  (using [sqlite3_busy_handler()]) prior to calling
2348** this routine, that other busy handler is cleared.)^
2349*/
2350SQLITE_API int sqlite3_busy_timeout(sqlite3*, int ms);
2351
2352/*
2353** CAPI3REF: Convenience Routines For Running Queries
2354**
2355** This is a legacy interface that is preserved for backwards compatibility.
2356** Use of this interface is not recommended.
2357**
2358** Definition: A <b>result table</b> is memory data structure created by the
2359** [sqlite3_get_table()] interface.  A result table records the
2360** complete query results from one or more queries.
2361**
2362** The table conceptually has a number of rows and columns.  But
2363** these numbers are not part of the result table itself.  These
2364** numbers are obtained separately.  Let N be the number of rows
2365** and M be the number of columns.
2366**
2367** A result table is an array of pointers to zero-terminated UTF-8 strings.
2368** There are (N+1)*M elements in the array.  The first M pointers point
2369** to zero-terminated strings that  contain the names of the columns.
2370** The remaining entries all point to query results.  NULL values result
2371** in NULL pointers.  All other values are in their UTF-8 zero-terminated
2372** string representation as returned by [sqlite3_column_text()].
2373**
2374** A result table might consist of one or more memory allocations.
2375** It is not safe to pass a result table directly to [sqlite3_free()].
2376** A result table should be deallocated using [sqlite3_free_table()].
2377**
2378** ^(As an example of the result table format, suppose a query result
2379** is as follows:
2380**
2381** <blockquote><pre>
2382**        Name        | Age
2383**        -----------------------
2384**        Alice       | 43
2385**        Bob         | 28
2386**        Cindy       | 21
2387** </pre></blockquote>
2388**
2389** There are two column (M==2) and three rows (N==3).  Thus the
2390** result table has 8 entries.  Suppose the result table is stored
2391** in an array names azResult.  Then azResult holds this content:
2392**
2393** <blockquote><pre>
2394**        azResult&#91;0] = "Name";
2395**        azResult&#91;1] = "Age";
2396**        azResult&#91;2] = "Alice";
2397**        azResult&#91;3] = "43";
2398**        azResult&#91;4] = "Bob";
2399**        azResult&#91;5] = "28";
2400**        azResult&#91;6] = "Cindy";
2401**        azResult&#91;7] = "21";
2402** </pre></blockquote>)^
2403**
2404** ^The sqlite3_get_table() function evaluates one or more
2405** semicolon-separated SQL statements in the zero-terminated UTF-8
2406** string of its 2nd parameter and returns a result table to the
2407** pointer given in its 3rd parameter.
2408**
2409** After the application has finished with the result from sqlite3_get_table(),
2410** it must pass the result table pointer to sqlite3_free_table() in order to
2411** release the memory that was malloced.  Because of the way the
2412** [sqlite3_malloc()] happens within sqlite3_get_table(), the calling
2413** function must not try to call [sqlite3_free()] directly.  Only
2414** [sqlite3_free_table()] is able to release the memory properly and safely.
2415**
2416** The sqlite3_get_table() interface is implemented as a wrapper around
2417** [sqlite3_exec()].  The sqlite3_get_table() routine does not have access
2418** to any internal data structures of SQLite.  It uses only the public
2419** interface defined here.  As a consequence, errors that occur in the
2420** wrapper layer outside of the internal [sqlite3_exec()] call are not
2421** reflected in subsequent calls to [sqlite3_errcode()] or
2422** [sqlite3_errmsg()].
2423*/
2424SQLITE_API int sqlite3_get_table(
2425  sqlite3 *db,          /* An open database */
2426  const char *zSql,     /* SQL to be evaluated */
2427  char ***pazResult,    /* Results of the query */
2428  int *pnRow,           /* Number of result rows written here */
2429  int *pnColumn,        /* Number of result columns written here */
2430  char **pzErrmsg       /* Error msg written here */
2431);
2432SQLITE_API void sqlite3_free_table(char **result);
2433
2434/*
2435** CAPI3REF: Formatted String Printing Functions
2436**
2437** These routines are work-alikes of the "printf()" family of functions
2438** from the standard C library.
2439**
2440** ^The sqlite3_mprintf() and sqlite3_vmprintf() routines write their
2441** results into memory obtained from [sqlite3_malloc()].
2442** The strings returned by these two routines should be
2443** released by [sqlite3_free()].  ^Both routines return a
2444** NULL pointer if [sqlite3_malloc()] is unable to allocate enough
2445** memory to hold the resulting string.
2446**
2447** ^(The sqlite3_snprintf() routine is similar to "snprintf()" from
2448** the standard C library.  The result is written into the
2449** buffer supplied as the second parameter whose size is given by
2450** the first parameter. Note that the order of the
2451** first two parameters is reversed from snprintf().)^  This is an
2452** historical accident that cannot be fixed without breaking
2453** backwards compatibility.  ^(Note also that sqlite3_snprintf()
2454** returns a pointer to its buffer instead of the number of
2455** characters actually written into the buffer.)^  We admit that
2456** the number of characters written would be a more useful return
2457** value but we cannot change the implementation of sqlite3_snprintf()
2458** now without breaking compatibility.
2459**
2460** ^As long as the buffer size is greater than zero, sqlite3_snprintf()
2461** guarantees that the buffer is always zero-terminated.  ^The first
2462** parameter "n" is the total size of the buffer, including space for
2463** the zero terminator.  So the longest string that can be completely
2464** written will be n-1 characters.
2465**
2466** ^The sqlite3_vsnprintf() routine is a varargs version of sqlite3_snprintf().
2467**
2468** These routines all implement some additional formatting
2469** options that are useful for constructing SQL statements.
2470** All of the usual printf() formatting options apply.  In addition, there
2471** is are "%q", "%Q", and "%z" options.
2472**
2473** ^(The %q option works like %s in that it substitutes a null-terminated
2474** string from the argument list.  But %q also doubles every '\'' character.
2475** %q is designed for use inside a string literal.)^  By doubling each '\''
2476** character it escapes that character and allows it to be inserted into
2477** the string.
2478**
2479** For example, assume the string variable zText contains text as follows:
2480**
2481** <blockquote><pre>
2482**  char *zText = "It's a happy day!";
2483** </pre></blockquote>
2484**
2485** One can use this text in an SQL statement as follows:
2486**
2487** <blockquote><pre>
2488**  char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES('%q')", zText);
2489**  sqlite3_exec(db, zSQL, 0, 0, 0);
2490**  sqlite3_free(zSQL);
2491** </pre></blockquote>
2492**
2493** Because the %q format string is used, the '\'' character in zText
2494** is escaped and the SQL generated is as follows:
2495**
2496** <blockquote><pre>
2497**  INSERT INTO table1 VALUES('It''s a happy day!')
2498** </pre></blockquote>
2499**
2500** This is correct.  Had we used %s instead of %q, the generated SQL
2501** would have looked like this:
2502**
2503** <blockquote><pre>
2504**  INSERT INTO table1 VALUES('It's a happy day!');
2505** </pre></blockquote>
2506**
2507** This second example is an SQL syntax error.  As a general rule you should
2508** always use %q instead of %s when inserting text into a string literal.
2509**
2510** ^(The %Q option works like %q except it also adds single quotes around
2511** the outside of the total string.  Additionally, if the parameter in the
2512** argument list is a NULL pointer, %Q substitutes the text "NULL" (without
2513** single quotes).)^  So, for example, one could say:
2514**
2515** <blockquote><pre>
2516**  char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES(%Q)", zText);
2517**  sqlite3_exec(db, zSQL, 0, 0, 0);
2518**  sqlite3_free(zSQL);
2519** </pre></blockquote>
2520**
2521** The code above will render a correct SQL statement in the zSQL
2522** variable even if the zText variable is a NULL pointer.
2523**
2524** ^(The "%z" formatting option works like "%s" but with the
2525** addition that after the string has been read and copied into
2526** the result, [sqlite3_free()] is called on the input string.)^
2527*/
2528SQLITE_API char *sqlite3_mprintf(const char*,...);
2529SQLITE_API char *sqlite3_vmprintf(const char*, va_list);
2530SQLITE_API char *sqlite3_snprintf(int,char*,const char*, ...);
2531SQLITE_API char *sqlite3_vsnprintf(int,char*,const char*, va_list);
2532
2533/*
2534** CAPI3REF: Memory Allocation Subsystem
2535**
2536** The SQLite core uses these three routines for all of its own
2537** internal memory allocation needs. "Core" in the previous sentence
2538** does not include operating-system specific VFS implementation.  The
2539** Windows VFS uses native malloc() and free() for some operations.
2540**
2541** ^The sqlite3_malloc() routine returns a pointer to a block
2542** of memory at least N bytes in length, where N is the parameter.
2543** ^If sqlite3_malloc() is unable to obtain sufficient free
2544** memory, it returns a NULL pointer.  ^If the parameter N to
2545** sqlite3_malloc() is zero or negative then sqlite3_malloc() returns
2546** a NULL pointer.
2547**
2548** ^Calling sqlite3_free() with a pointer previously returned
2549** by sqlite3_malloc() or sqlite3_realloc() releases that memory so
2550** that it might be reused.  ^The sqlite3_free() routine is
2551** a no-op if is called with a NULL pointer.  Passing a NULL pointer
2552** to sqlite3_free() is harmless.  After being freed, memory
2553** should neither be read nor written.  Even reading previously freed
2554** memory might result in a segmentation fault or other severe error.
2555** Memory corruption, a segmentation fault, or other severe error
2556** might result if sqlite3_free() is called with a non-NULL pointer that
2557** was not obtained from sqlite3_malloc() or sqlite3_realloc().
2558**
2559** ^(The sqlite3_realloc() interface attempts to resize a
2560** prior memory allocation to be at least N bytes, where N is the
2561** second parameter.  The memory allocation to be resized is the first
2562** parameter.)^ ^ If the first parameter to sqlite3_realloc()
2563** is a NULL pointer then its behavior is identical to calling
2564** sqlite3_malloc(N) where N is the second parameter to sqlite3_realloc().
2565** ^If the second parameter to sqlite3_realloc() is zero or
2566** negative then the behavior is exactly the same as calling
2567** sqlite3_free(P) where P is the first parameter to sqlite3_realloc().
2568** ^sqlite3_realloc() returns a pointer to a memory allocation
2569** of at least N bytes in size or NULL if sufficient memory is unavailable.
2570** ^If M is the size of the prior allocation, then min(N,M) bytes
2571** of the prior allocation are copied into the beginning of buffer returned
2572** by sqlite3_realloc() and the prior allocation is freed.
2573** ^If sqlite3_realloc() returns NULL, then the prior allocation
2574** is not freed.
2575**
2576** ^The memory returned by sqlite3_malloc() and sqlite3_realloc()
2577** is always aligned to at least an 8 byte boundary, or to a
2578** 4 byte boundary if the [SQLITE_4_BYTE_ALIGNED_MALLOC] compile-time
2579** option is used.
2580**
2581** In SQLite version 3.5.0 and 3.5.1, it was possible to define
2582** the SQLITE_OMIT_MEMORY_ALLOCATION which would cause the built-in
2583** implementation of these routines to be omitted.  That capability
2584** is no longer provided.  Only built-in memory allocators can be used.
2585**
2586** The Windows OS interface layer calls
2587** the system malloc() and free() directly when converting
2588** filenames between the UTF-8 encoding used by SQLite
2589** and whatever filename encoding is used by the particular Windows
2590** installation.  Memory allocation errors are detected, but
2591** they are reported back as [SQLITE_CANTOPEN] or
2592** [SQLITE_IOERR] rather than [SQLITE_NOMEM].
2593**
2594** The pointer arguments to [sqlite3_free()] and [sqlite3_realloc()]
2595** must be either NULL or else pointers obtained from a prior
2596** invocation of [sqlite3_malloc()] or [sqlite3_realloc()] that have
2597** not yet been released.
2598**
2599** The application must not read or write any part of
2600** a block of memory after it has been released using
2601** [sqlite3_free()] or [sqlite3_realloc()].
2602*/
2603SQLITE_API void *sqlite3_malloc(int);
2604SQLITE_API void *sqlite3_realloc(void*, int);
2605SQLITE_API void sqlite3_free(void*);
2606
2607/*
2608** CAPI3REF: Memory Allocator Statistics
2609**
2610** SQLite provides these two interfaces for reporting on the status
2611** of the [sqlite3_malloc()], [sqlite3_free()], and [sqlite3_realloc()]
2612** routines, which form the built-in memory allocation subsystem.
2613**
2614** ^The [sqlite3_memory_used()] routine returns the number of bytes
2615** of memory currently outstanding (malloced but not freed).
2616** ^The [sqlite3_memory_highwater()] routine returns the maximum
2617** value of [sqlite3_memory_used()] since the high-water mark
2618** was last reset.  ^The values returned by [sqlite3_memory_used()] and
2619** [sqlite3_memory_highwater()] include any overhead
2620** added by SQLite in its implementation of [sqlite3_malloc()],
2621** but not overhead added by the any underlying system library
2622** routines that [sqlite3_malloc()] may call.
2623**
2624** ^The memory high-water mark is reset to the current value of
2625** [sqlite3_memory_used()] if and only if the parameter to
2626** [sqlite3_memory_highwater()] is true.  ^The value returned
2627** by [sqlite3_memory_highwater(1)] is the high-water mark
2628** prior to the reset.
2629*/
2630SQLITE_API sqlite3_int64 sqlite3_memory_used(void);
2631SQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag);
2632
2633/*
2634** CAPI3REF: Pseudo-Random Number Generator
2635**
2636** SQLite contains a high-quality pseudo-random number generator (PRNG) used to
2637** select random [ROWID | ROWIDs] when inserting new records into a table that
2638** already uses the largest possible [ROWID].  The PRNG is also used for
2639** the build-in random() and randomblob() SQL functions.  This interface allows
2640** applications to access the same PRNG for other purposes.
2641**
2642** ^A call to this routine stores N bytes of randomness into buffer P.
2643**
2644** ^The first time this routine is invoked (either internally or by
2645** the application) the PRNG is seeded using randomness obtained
2646** from the xRandomness method of the default [sqlite3_vfs] object.
2647** ^On all subsequent invocations, the pseudo-randomness is generated
2648** internally and without recourse to the [sqlite3_vfs] xRandomness
2649** method.
2650*/
2651SQLITE_API void sqlite3_randomness(int N, void *P);
2652
2653/*
2654** CAPI3REF: Compile-Time Authorization Callbacks
2655**
2656** ^This routine registers an authorizer callback with a particular
2657** [database connection], supplied in the first argument.
2658** ^The authorizer callback is invoked as SQL statements are being compiled
2659** by [sqlite3_prepare()] or its variants [sqlite3_prepare_v2()],
2660** [sqlite3_prepare16()] and [sqlite3_prepare16_v2()].  ^At various
2661** points during the compilation process, as logic is being created
2662** to perform various actions, the authorizer callback is invoked to
2663** see if those actions are allowed.  ^The authorizer callback should
2664** return [SQLITE_OK] to allow the action, [SQLITE_IGNORE] to disallow the
2665** specific action but allow the SQL statement to continue to be
2666** compiled, or [SQLITE_DENY] to cause the entire SQL statement to be
2667** rejected with an error.  ^If the authorizer callback returns
2668** any value other than [SQLITE_IGNORE], [SQLITE_OK], or [SQLITE_DENY]
2669** then the [sqlite3_prepare_v2()] or equivalent call that triggered
2670** the authorizer will fail with an error message.
2671**
2672** When the callback returns [SQLITE_OK], that means the operation
2673** requested is ok.  ^When the callback returns [SQLITE_DENY], the
2674** [sqlite3_prepare_v2()] or equivalent call that triggered the
2675** authorizer will fail with an error message explaining that
2676** access is denied.
2677**
2678** ^The first parameter to the authorizer callback is a copy of the third
2679** parameter to the sqlite3_set_authorizer() interface. ^The second parameter
2680** to the callback is an integer [SQLITE_COPY | action code] that specifies
2681** the particular action to be authorized. ^The third through sixth parameters
2682** to the callback are zero-terminated strings that contain additional
2683** details about the action to be authorized.
2684**
2685** ^If the action code is [SQLITE_READ]
2686** and the callback returns [SQLITE_IGNORE] then the
2687** [prepared statement] statement is constructed to substitute
2688** a NULL value in place of the table column that would have
2689** been read if [SQLITE_OK] had been returned.  The [SQLITE_IGNORE]
2690** return can be used to deny an untrusted user access to individual
2691** columns of a table.
2692** ^If the action code is [SQLITE_DELETE] and the callback returns
2693** [SQLITE_IGNORE] then the [DELETE] operation proceeds but the
2694** [truncate optimization] is disabled and all rows are deleted individually.
2695**
2696** An authorizer is used when [sqlite3_prepare | preparing]
2697** SQL statements from an untrusted source, to ensure that the SQL statements
2698** do not try to access data they are not allowed to see, or that they do not
2699** try to execute malicious statements that damage the database.  For
2700** example, an application may allow a user to enter arbitrary
2701** SQL queries for evaluation by a database.  But the application does
2702** not want the user to be able to make arbitrary changes to the
2703** database.  An authorizer could then be put in place while the
2704** user-entered SQL is being [sqlite3_prepare | prepared] that
2705** disallows everything except [SELECT] statements.
2706**
2707** Applications that need to process SQL from untrusted sources
2708** might also consider lowering resource limits using [sqlite3_limit()]
2709** and limiting database size using the [max_page_count] [PRAGMA]
2710** in addition to using an authorizer.
2711**
2712** ^(Only a single authorizer can be in place on a database connection
2713** at a time.  Each call to sqlite3_set_authorizer overrides the
2714** previous call.)^  ^Disable the authorizer by installing a NULL callback.
2715** The authorizer is disabled by default.
2716**
2717** The authorizer callback must not do anything that will modify
2718** the database connection that invoked the authorizer callback.
2719** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
2720** database connections for the meaning of "modify" in this paragraph.
2721**
2722** ^When [sqlite3_prepare_v2()] is used to prepare a statement, the
2723** statement might be re-prepared during [sqlite3_step()] due to a
2724** schema change.  Hence, the application should ensure that the
2725** correct authorizer callback remains in place during the [sqlite3_step()].
2726**
2727** ^Note that the authorizer callback is invoked only during
2728** [sqlite3_prepare()] or its variants.  Authorization is not
2729** performed during statement evaluation in [sqlite3_step()], unless
2730** as stated in the previous paragraph, sqlite3_step() invokes
2731** sqlite3_prepare_v2() to reprepare a statement after a schema change.
2732*/
2733SQLITE_API int sqlite3_set_authorizer(
2734  sqlite3*,
2735  int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
2736  void *pUserData
2737);
2738
2739/*
2740** CAPI3REF: Authorizer Return Codes
2741**
2742** The [sqlite3_set_authorizer | authorizer callback function] must
2743** return either [SQLITE_OK] or one of these two constants in order
2744** to signal SQLite whether or not the action is permitted.  See the
2745** [sqlite3_set_authorizer | authorizer documentation] for additional
2746** information.
2747*/
2748#define SQLITE_DENY   1   /* Abort the SQL statement with an error */
2749#define SQLITE_IGNORE 2   /* Don't allow access, but don't generate an error */
2750
2751/*
2752** CAPI3REF: Authorizer Action Codes
2753**
2754** The [sqlite3_set_authorizer()] interface registers a callback function
2755** that is invoked to authorize certain SQL statement actions.  The
2756** second parameter to the callback is an integer code that specifies
2757** what action is being authorized.  These are the integer action codes that
2758** the authorizer callback may be passed.
2759**
2760** These action code values signify what kind of operation is to be
2761** authorized.  The 3rd and 4th parameters to the authorization
2762** callback function will be parameters or NULL depending on which of these
2763** codes is used as the second parameter.  ^(The 5th parameter to the
2764** authorizer callback is the name of the database ("main", "temp",
2765** etc.) if applicable.)^  ^The 6th parameter to the authorizer callback
2766** is the name of the inner-most trigger or view that is responsible for
2767** the access attempt or NULL if this access attempt is directly from
2768** top-level SQL code.
2769*/
2770/******************************************* 3rd ************ 4th ***********/
2771#define SQLITE_CREATE_INDEX          1   /* Index Name      Table Name      */
2772#define SQLITE_CREATE_TABLE          2   /* Table Name      NULL            */
2773#define SQLITE_CREATE_TEMP_INDEX     3   /* Index Name      Table Name      */
2774#define SQLITE_CREATE_TEMP_TABLE     4   /* Table Name      NULL            */
2775#define SQLITE_CREATE_TEMP_TRIGGER   5   /* Trigger Name    Table Name      */
2776#define SQLITE_CREATE_TEMP_VIEW      6   /* View Name       NULL            */
2777#define SQLITE_CREATE_TRIGGER        7   /* Trigger Name    Table Name      */
2778#define SQLITE_CREATE_VIEW           8   /* View Name       NULL            */
2779#define SQLITE_DELETE                9   /* Table Name      NULL            */
2780#define SQLITE_DROP_INDEX           10   /* Index Name      Table Name      */
2781#define SQLITE_DROP_TABLE           11   /* Table Name      NULL            */
2782#define SQLITE_DROP_TEMP_INDEX      12   /* Index Name      Table Name      */
2783#define SQLITE_DROP_TEMP_TABLE      13   /* Table Name      NULL            */
2784#define SQLITE_DROP_TEMP_TRIGGER    14   /* Trigger Name    Table Name      */
2785#define SQLITE_DROP_TEMP_VIEW       15   /* View Name       NULL            */
2786#define SQLITE_DROP_TRIGGER         16   /* Trigger Name    Table Name      */
2787#define SQLITE_DROP_VIEW            17   /* View Name       NULL            */
2788#define SQLITE_INSERT               18   /* Table Name      NULL            */
2789#define SQLITE_PRAGMA               19   /* Pragma Name     1st arg or NULL */
2790#define SQLITE_READ                 20   /* Table Name      Column Name     */
2791#define SQLITE_SELECT               21   /* NULL            NULL            */
2792#define SQLITE_TRANSACTION          22   /* Operation       NULL            */
2793#define SQLITE_UPDATE               23   /* Table Name      Column Name     */
2794#define SQLITE_ATTACH               24   /* Filename        NULL            */
2795#define SQLITE_DETACH               25   /* Database Name   NULL            */
2796#define SQLITE_ALTER_TABLE          26   /* Database Name   Table Name      */
2797#define SQLITE_REINDEX              27   /* Index Name      NULL            */
2798#define SQLITE_ANALYZE              28   /* Table Name      NULL            */
2799#define SQLITE_CREATE_VTABLE        29   /* Table Name      Module Name     */
2800#define SQLITE_DROP_VTABLE          30   /* Table Name      Module Name     */
2801#define SQLITE_FUNCTION             31   /* NULL            Function Name   */
2802#define SQLITE_SAVEPOINT            32   /* Operation       Savepoint Name  */
2803#define SQLITE_COPY                  0   /* No longer used */
2804
2805/*
2806** CAPI3REF: Tracing And Profiling Functions
2807**
2808** These routines register callback functions that can be used for
2809** tracing and profiling the execution of SQL statements.
2810**
2811** ^The callback function registered by sqlite3_trace() is invoked at
2812** various times when an SQL statement is being run by [sqlite3_step()].
2813** ^The sqlite3_trace() callback is invoked with a UTF-8 rendering of the
2814** SQL statement text as the statement first begins executing.
2815** ^(Additional sqlite3_trace() callbacks might occur
2816** as each triggered subprogram is entered.  The callbacks for triggers
2817** contain a UTF-8 SQL comment that identifies the trigger.)^
2818**
2819** ^The callback function registered by sqlite3_profile() is invoked
2820** as each SQL statement finishes.  ^The profile callback contains
2821** the original statement text and an estimate of wall-clock time
2822** of how long that statement took to run.  ^The profile callback
2823** time is in units of nanoseconds, however the current implementation
2824** is only capable of millisecond resolution so the six least significant
2825** digits in the time are meaningless.  Future versions of SQLite
2826** might provide greater resolution on the profiler callback.  The
2827** sqlite3_profile() function is considered experimental and is
2828** subject to change in future versions of SQLite.
2829*/
2830SQLITE_API void *sqlite3_trace(sqlite3*, void(*xTrace)(void*,const char*), void*);
2831SQLITE_API SQLITE_EXPERIMENTAL void *sqlite3_profile(sqlite3*,
2832   void(*xProfile)(void*,const char*,sqlite3_uint64), void*);
2833
2834/*
2835** CAPI3REF: Query Progress Callbacks
2836**
2837** ^The sqlite3_progress_handler(D,N,X,P) interface causes the callback
2838** function X to be invoked periodically during long running calls to
2839** [sqlite3_exec()], [sqlite3_step()] and [sqlite3_get_table()] for
2840** database connection D.  An example use for this
2841** interface is to keep a GUI updated during a large query.
2842**
2843** ^The parameter P is passed through as the only parameter to the
2844** callback function X.  ^The parameter N is the number of
2845** [virtual machine instructions] that are evaluated between successive
2846** invocations of the callback X.
2847**
2848** ^Only a single progress handler may be defined at one time per
2849** [database connection]; setting a new progress handler cancels the
2850** old one.  ^Setting parameter X to NULL disables the progress handler.
2851** ^The progress handler is also disabled by setting N to a value less
2852** than 1.
2853**
2854** ^If the progress callback returns non-zero, the operation is
2855** interrupted.  This feature can be used to implement a
2856** "Cancel" button on a GUI progress dialog box.
2857**
2858** The progress handler callback must not do anything that will modify
2859** the database connection that invoked the progress handler.
2860** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
2861** database connections for the meaning of "modify" in this paragraph.
2862**
2863*/
2864SQLITE_API void sqlite3_progress_handler(sqlite3*, int, int(*)(void*), void*);
2865
2866/*
2867** CAPI3REF: Opening A New Database Connection
2868**
2869** ^These routines open an SQLite database file whose name is given by the
2870** filename argument. ^The filename argument is interpreted as UTF-8 for
2871** sqlite3_open() and sqlite3_open_v2() and as UTF-16 in the native byte
2872** order for sqlite3_open16(). ^(A [database connection] handle is usually
2873** returned in *ppDb, even if an error occurs.  The only exception is that
2874** if SQLite is unable to allocate memory to hold the [sqlite3] object,
2875** a NULL will be written into *ppDb instead of a pointer to the [sqlite3]
2876** object.)^ ^(If the database is opened (and/or created) successfully, then
2877** [SQLITE_OK] is returned.  Otherwise an [error code] is returned.)^ ^The
2878** [sqlite3_errmsg()] or [sqlite3_errmsg16()] routines can be used to obtain
2879** an English language description of the error following a failure of any
2880** of the sqlite3_open() routines.
2881**
2882** ^The default encoding for the database will be UTF-8 if
2883** sqlite3_open() or sqlite3_open_v2() is called and
2884** UTF-16 in the native byte order if sqlite3_open16() is used.
2885**
2886** Whether or not an error occurs when it is opened, resources
2887** associated with the [database connection] handle should be released by
2888** passing it to [sqlite3_close()] when it is no longer required.
2889**
2890** The sqlite3_open_v2() interface works like sqlite3_open()
2891** except that it accepts two additional parameters for additional control
2892** over the new database connection.  ^(The flags parameter to
2893** sqlite3_open_v2() can take one of
2894** the following three values, optionally combined with the
2895** [SQLITE_OPEN_NOMUTEX], [SQLITE_OPEN_FULLMUTEX], [SQLITE_OPEN_SHAREDCACHE],
2896** and/or [SQLITE_OPEN_PRIVATECACHE] flags:)^
2897**
2898** <dl>
2899** ^(<dt>[SQLITE_OPEN_READONLY]</dt>
2900** <dd>The database is opened in read-only mode.  If the database does not
2901** already exist, an error is returned.</dd>)^
2902**
2903** ^(<dt>[SQLITE_OPEN_READWRITE]</dt>
2904** <dd>The database is opened for reading and writing if possible, or reading
2905** only if the file is write protected by the operating system.  In either
2906** case the database must already exist, otherwise an error is returned.</dd>)^
2907**
2908** ^(<dt>[SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE]</dt>
2909** <dd>The database is opened for reading and writing, and is created if
2910** it does not already exist. This is the behavior that is always used for
2911** sqlite3_open() and sqlite3_open16().</dd>)^
2912** </dl>
2913**
2914** If the 3rd parameter to sqlite3_open_v2() is not one of the
2915** combinations shown above or one of the combinations shown above combined
2916** with the [SQLITE_OPEN_NOMUTEX], [SQLITE_OPEN_FULLMUTEX],
2917** [SQLITE_OPEN_SHAREDCACHE] and/or [SQLITE_OPEN_PRIVATECACHE] flags,
2918** then the behavior is undefined.
2919**
2920** ^If the [SQLITE_OPEN_NOMUTEX] flag is set, then the database connection
2921** opens in the multi-thread [threading mode] as long as the single-thread
2922** mode has not been set at compile-time or start-time.  ^If the
2923** [SQLITE_OPEN_FULLMUTEX] flag is set then the database connection opens
2924** in the serialized [threading mode] unless single-thread was
2925** previously selected at compile-time or start-time.
2926** ^The [SQLITE_OPEN_SHAREDCACHE] flag causes the database connection to be
2927** eligible to use [shared cache mode], regardless of whether or not shared
2928** cache is enabled using [sqlite3_enable_shared_cache()].  ^The
2929** [SQLITE_OPEN_PRIVATECACHE] flag causes the database connection to not
2930** participate in [shared cache mode] even if it is enabled.
2931**
2932** ^If the filename is ":memory:", then a private, temporary in-memory database
2933** is created for the connection.  ^This in-memory database will vanish when
2934** the database connection is closed.  Future versions of SQLite might
2935** make use of additional special filenames that begin with the ":" character.
2936** It is recommended that when a database filename actually does begin with
2937** a ":" character you should prefix the filename with a pathname such as
2938** "./" to avoid ambiguity.
2939**
2940** ^If the filename is an empty string, then a private, temporary
2941** on-disk database will be created.  ^This private database will be
2942** automatically deleted as soon as the database connection is closed.
2943**
2944** ^The fourth parameter to sqlite3_open_v2() is the name of the
2945** [sqlite3_vfs] object that defines the operating system interface that
2946** the new database connection should use.  ^If the fourth parameter is
2947** a NULL pointer then the default [sqlite3_vfs] object is used.
2948**
2949** <b>Note to Windows users:</b>  The encoding used for the filename argument
2950** of sqlite3_open() and sqlite3_open_v2() must be UTF-8, not whatever
2951** codepage is currently defined.  Filenames containing international
2952** characters must be converted to UTF-8 prior to passing them into
2953** sqlite3_open() or sqlite3_open_v2().
2954*/
2955SQLITE_API int sqlite3_open(
2956  const char *filename,   /* Database filename (UTF-8) */
2957  sqlite3 **ppDb          /* OUT: SQLite db handle */
2958);
2959SQLITE_API int sqlite3_open16(
2960  const void *filename,   /* Database filename (UTF-16) */
2961  sqlite3 **ppDb          /* OUT: SQLite db handle */
2962);
2963SQLITE_API int sqlite3_open_v2(
2964  const char *filename,   /* Database filename (UTF-8) */
2965  sqlite3 **ppDb,         /* OUT: SQLite db handle */
2966  int flags,              /* Flags */
2967  const char *zVfs        /* Name of VFS module to use */
2968);
2969
2970/*
2971** CAPI3REF: Error Codes And Messages
2972**
2973** ^The sqlite3_errcode() interface returns the numeric [result code] or
2974** [extended result code] for the most recent failed sqlite3_* API call
2975** associated with a [database connection]. If a prior API call failed
2976** but the most recent API call succeeded, the return value from
2977** sqlite3_errcode() is undefined.  ^The sqlite3_extended_errcode()
2978** interface is the same except that it always returns the
2979** [extended result code] even when extended result codes are
2980** disabled.
2981**
2982** ^The sqlite3_errmsg() and sqlite3_errmsg16() return English-language
2983** text that describes the error, as either UTF-8 or UTF-16 respectively.
2984** ^(Memory to hold the error message string is managed internally.
2985** The application does not need to worry about freeing the result.
2986** However, the error string might be overwritten or deallocated by
2987** subsequent calls to other SQLite interface functions.)^
2988**
2989** When the serialized [threading mode] is in use, it might be the
2990** case that a second error occurs on a separate thread in between
2991** the time of the first error and the call to these interfaces.
2992** When that happens, the second error will be reported since these
2993** interfaces always report the most recent result.  To avoid
2994** this, each thread can obtain exclusive use of the [database connection] D
2995** by invoking [sqlite3_mutex_enter]([sqlite3_db_mutex](D)) before beginning
2996** to use D and invoking [sqlite3_mutex_leave]([sqlite3_db_mutex](D)) after
2997** all calls to the interfaces listed here are completed.
2998**
2999** If an interface fails with SQLITE_MISUSE, that means the interface
3000** was invoked incorrectly by the application.  In that case, the
3001** error code and message may or may not be set.
3002*/
3003SQLITE_API int sqlite3_errcode(sqlite3 *db);
3004SQLITE_API int sqlite3_extended_errcode(sqlite3 *db);
3005SQLITE_API const char *sqlite3_errmsg(sqlite3*);
3006SQLITE_API const void *sqlite3_errmsg16(sqlite3*);
3007
3008/*
3009** CAPI3REF: SQL Statement Object
3010** KEYWORDS: {prepared statement} {prepared statements}
3011**
3012** An instance of this object represents a single SQL statement.
3013** This object is variously known as a "prepared statement" or a
3014** "compiled SQL statement" or simply as a "statement".
3015**
3016** The life of a statement object goes something like this:
3017**
3018** <ol>
3019** <li> Create the object using [sqlite3_prepare_v2()] or a related
3020**      function.
3021** <li> Bind values to [host parameters] using the sqlite3_bind_*()
3022**      interfaces.
3023** <li> Run the SQL by calling [sqlite3_step()] one or more times.
3024** <li> Reset the statement using [sqlite3_reset()] then go back
3025**      to step 2.  Do this zero or more times.
3026** <li> Destroy the object using [sqlite3_finalize()].
3027** </ol>
3028**
3029** Refer to documentation on individual methods above for additional
3030** information.
3031*/
3032typedef struct sqlite3_stmt sqlite3_stmt;
3033
3034/*
3035** CAPI3REF: Run-time Limits
3036**
3037** ^(This interface allows the size of various constructs to be limited
3038** on a connection by connection basis.  The first parameter is the
3039** [database connection] whose limit is to be set or queried.  The
3040** second parameter is one of the [limit categories] that define a
3041** class of constructs to be size limited.  The third parameter is the
3042** new limit for that construct.)^
3043**
3044** ^If the new limit is a negative number, the limit is unchanged.
3045** ^(For each limit category SQLITE_LIMIT_<i>NAME</i> there is a
3046** [limits | hard upper bound]
3047** set at compile-time by a C preprocessor macro called
3048** [limits | SQLITE_MAX_<i>NAME</i>].
3049** (The "_LIMIT_" in the name is changed to "_MAX_".))^
3050** ^Attempts to increase a limit above its hard upper bound are
3051** silently truncated to the hard upper bound.
3052**
3053** ^Regardless of whether or not the limit was changed, the
3054** [sqlite3_limit()] interface returns the prior value of the limit.
3055** ^Hence, to find the current value of a limit without changing it,
3056** simply invoke this interface with the third parameter set to -1.
3057**
3058** Run-time limits are intended for use in applications that manage
3059** both their own internal database and also databases that are controlled
3060** by untrusted external sources.  An example application might be a
3061** web browser that has its own databases for storing history and
3062** separate databases controlled by JavaScript applications downloaded
3063** off the Internet.  The internal databases can be given the
3064** large, default limits.  Databases managed by external sources can
3065** be given much smaller limits designed to prevent a denial of service
3066** attack.  Developers might also want to use the [sqlite3_set_authorizer()]
3067** interface to further control untrusted SQL.  The size of the database
3068** created by an untrusted script can be contained using the
3069** [max_page_count] [PRAGMA].
3070**
3071** New run-time limit categories may be added in future releases.
3072*/
3073SQLITE_API int sqlite3_limit(sqlite3*, int id, int newVal);
3074
3075/*
3076** CAPI3REF: Run-Time Limit Categories
3077** KEYWORDS: {limit category} {*limit categories}
3078**
3079** These constants define various performance limits
3080** that can be lowered at run-time using [sqlite3_limit()].
3081** The synopsis of the meanings of the various limits is shown below.
3082** Additional information is available at [limits | Limits in SQLite].
3083**
3084** <dl>
3085** ^(<dt>SQLITE_LIMIT_LENGTH</dt>
3086** <dd>The maximum size of any string or BLOB or table row, in bytes.<dd>)^
3087**
3088** ^(<dt>SQLITE_LIMIT_SQL_LENGTH</dt>
3089** <dd>The maximum length of an SQL statement, in bytes.</dd>)^
3090**
3091** ^(<dt>SQLITE_LIMIT_COLUMN</dt>
3092** <dd>The maximum number of columns in a table definition or in the
3093** result set of a [SELECT] or the maximum number of columns in an index
3094** or in an ORDER BY or GROUP BY clause.</dd>)^
3095**
3096** ^(<dt>SQLITE_LIMIT_EXPR_DEPTH</dt>
3097** <dd>The maximum depth of the parse tree on any expression.</dd>)^
3098**
3099** ^(<dt>SQLITE_LIMIT_COMPOUND_SELECT</dt>
3100** <dd>The maximum number of terms in a compound SELECT statement.</dd>)^
3101**
3102** ^(<dt>SQLITE_LIMIT_VDBE_OP</dt>
3103** <dd>The maximum number of instructions in a virtual machine program
3104** used to implement an SQL statement.  This limit is not currently
3105** enforced, though that might be added in some future release of
3106** SQLite.</dd>)^
3107**
3108** ^(<dt>SQLITE_LIMIT_FUNCTION_ARG</dt>
3109** <dd>The maximum number of arguments on a function.</dd>)^
3110**
3111** ^(<dt>SQLITE_LIMIT_ATTACHED</dt>
3112** <dd>The maximum number of [ATTACH | attached databases].)^</dd>
3113**
3114** ^(<dt>SQLITE_LIMIT_LIKE_PATTERN_LENGTH</dt>
3115** <dd>The maximum length of the pattern argument to the [LIKE] or
3116** [GLOB] operators.</dd>)^
3117**
3118** ^(<dt>SQLITE_LIMIT_VARIABLE_NUMBER</dt>
3119** <dd>The maximum index number of any [parameter] in an SQL statement.)^
3120**
3121** ^(<dt>SQLITE_LIMIT_TRIGGER_DEPTH</dt>
3122** <dd>The maximum depth of recursion for triggers.</dd>)^
3123** </dl>
3124*/
3125#define SQLITE_LIMIT_LENGTH                    0
3126#define SQLITE_LIMIT_SQL_LENGTH                1
3127#define SQLITE_LIMIT_COLUMN                    2
3128#define SQLITE_LIMIT_EXPR_DEPTH                3
3129#define SQLITE_LIMIT_COMPOUND_SELECT           4
3130#define SQLITE_LIMIT_VDBE_OP                   5
3131#define SQLITE_LIMIT_FUNCTION_ARG              6
3132#define SQLITE_LIMIT_ATTACHED                  7
3133#define SQLITE_LIMIT_LIKE_PATTERN_LENGTH       8
3134#define SQLITE_LIMIT_VARIABLE_NUMBER           9
3135#define SQLITE_LIMIT_TRIGGER_DEPTH            10
3136
3137/*
3138** CAPI3REF: Compiling An SQL Statement
3139** KEYWORDS: {SQL statement compiler}
3140**
3141** To execute an SQL query, it must first be compiled into a byte-code
3142** program using one of these routines.
3143**
3144** The first argument, "db", is a [database connection] obtained from a
3145** prior successful call to [sqlite3_open()], [sqlite3_open_v2()] or
3146** [sqlite3_open16()].  The database connection must not have been closed.
3147**
3148** The second argument, "zSql", is the statement to be compiled, encoded
3149** as either UTF-8 or UTF-16.  The sqlite3_prepare() and sqlite3_prepare_v2()
3150** interfaces use UTF-8, and sqlite3_prepare16() and sqlite3_prepare16_v2()
3151** use UTF-16.
3152**
3153** ^If the nByte argument is less than zero, then zSql is read up to the
3154** first zero terminator. ^If nByte is non-negative, then it is the maximum
3155** number of  bytes read from zSql.  ^When nByte is non-negative, the
3156** zSql string ends at either the first '\000' or '\u0000' character or
3157** the nByte-th byte, whichever comes first. If the caller knows
3158** that the supplied string is nul-terminated, then there is a small
3159** performance advantage to be gained by passing an nByte parameter that
3160** is equal to the number of bytes in the input string <i>including</i>
3161** the nul-terminator bytes.
3162**
3163** ^If pzTail is not NULL then *pzTail is made to point to the first byte
3164** past the end of the first SQL statement in zSql.  These routines only
3165** compile the first statement in zSql, so *pzTail is left pointing to
3166** what remains uncompiled.
3167**
3168** ^*ppStmt is left pointing to a compiled [prepared statement] that can be
3169** executed using [sqlite3_step()].  ^If there is an error, *ppStmt is set
3170** to NULL.  ^If the input text contains no SQL (if the input is an empty
3171** string or a comment) then *ppStmt is set to NULL.
3172** The calling procedure is responsible for deleting the compiled
3173** SQL statement using [sqlite3_finalize()] after it has finished with it.
3174** ppStmt may not be NULL.
3175**
3176** ^On success, the sqlite3_prepare() family of routines return [SQLITE_OK];
3177** otherwise an [error code] is returned.
3178**
3179** The sqlite3_prepare_v2() and sqlite3_prepare16_v2() interfaces are
3180** recommended for all new programs. The two older interfaces are retained
3181** for backwards compatibility, but their use is discouraged.
3182** ^In the "v2" interfaces, the prepared statement
3183** that is returned (the [sqlite3_stmt] object) contains a copy of the
3184** original SQL text. This causes the [sqlite3_step()] interface to
3185** behave differently in three ways:
3186**
3187** <ol>
3188** <li>
3189** ^If the database schema changes, instead of returning [SQLITE_SCHEMA] as it
3190** always used to do, [sqlite3_step()] will automatically recompile the SQL
3191** statement and try to run it again.
3192** </li>
3193**
3194** <li>
3195** ^When an error occurs, [sqlite3_step()] will return one of the detailed
3196** [error codes] or [extended error codes].  ^The legacy behavior was that
3197** [sqlite3_step()] would only return a generic [SQLITE_ERROR] result code
3198** and the application would have to make a second call to [sqlite3_reset()]
3199** in order to find the underlying cause of the problem. With the "v2" prepare
3200** interfaces, the underlying reason for the error is returned immediately.
3201** </li>
3202**
3203** <li>
3204** ^If the specific value bound to [parameter | host parameter] in the
3205** WHERE clause might influence the choice of query plan for a statement,
3206** then the statement will be automatically recompiled, as if there had been
3207** a schema change, on the first  [sqlite3_step()] call following any change
3208** to the [sqlite3_bind_text | bindings] of that [parameter].
3209** ^The specific value of WHERE-clause [parameter] might influence the
3210** choice of query plan if the parameter is the left-hand side of a [LIKE]
3211** or [GLOB] operator or if the parameter is compared to an indexed column
3212** and the [SQLITE_ENABLE_STAT2] compile-time option is enabled.
3213** the
3214** </li>
3215** </ol>
3216*/
3217SQLITE_API int sqlite3_prepare(
3218  sqlite3 *db,            /* Database handle */
3219  const char *zSql,       /* SQL statement, UTF-8 encoded */
3220  int nByte,              /* Maximum length of zSql in bytes. */
3221  sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
3222  const char **pzTail     /* OUT: Pointer to unused portion of zSql */
3223);
3224SQLITE_API int sqlite3_prepare_v2(
3225  sqlite3 *db,            /* Database handle */
3226  const char *zSql,       /* SQL statement, UTF-8 encoded */
3227  int nByte,              /* Maximum length of zSql in bytes. */
3228  sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
3229  const char **pzTail     /* OUT: Pointer to unused portion of zSql */
3230);
3231SQLITE_API int sqlite3_prepare16(
3232  sqlite3 *db,            /* Database handle */
3233  const void *zSql,       /* SQL statement, UTF-16 encoded */
3234  int nByte,              /* Maximum length of zSql in bytes. */
3235  sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
3236  const void **pzTail     /* OUT: Pointer to unused portion of zSql */
3237);
3238SQLITE_API int sqlite3_prepare16_v2(
3239  sqlite3 *db,            /* Database handle */
3240  const void *zSql,       /* SQL statement, UTF-16 encoded */
3241  int nByte,              /* Maximum length of zSql in bytes. */
3242  sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
3243  const void **pzTail     /* OUT: Pointer to unused portion of zSql */
3244);
3245
3246/*
3247** CAPI3REF: Retrieving Statement SQL
3248**
3249** ^This interface can be used to retrieve a saved copy of the original
3250** SQL text used to create a [prepared statement] if that statement was
3251** compiled using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()].
3252*/
3253SQLITE_API const char *sqlite3_sql(sqlite3_stmt *pStmt);
3254
3255/*
3256** CAPI3REF: Determine If An SQL Statement Writes The Database
3257**
3258** ^The sqlite3_stmt_readonly(X) interface returns true (non-zero) if
3259** and only if the [prepared statement] X makes no direct changes to
3260** the content of the database file.
3261**
3262** Note that [application-defined SQL functions] or
3263** [virtual tables] might change the database indirectly as a side effect.
3264** ^(For example, if an application defines a function "eval()" that
3265** calls [sqlite3_exec()], then the following SQL statement would
3266** change the database file through side-effects:
3267**
3268** <blockquote><pre>
3269**    SELECT eval('DELETE FROM t1') FROM t2;
3270** </pre></blockquote>
3271**
3272** But because the [SELECT] statement does not change the database file
3273** directly, sqlite3_stmt_readonly() would still return true.)^
3274**
3275** ^Transaction control statements such as [BEGIN], [COMMIT], [ROLLBACK],
3276** [SAVEPOINT], and [RELEASE] cause sqlite3_stmt_readonly() to return true,
3277** since the statements themselves do not actually modify the database but
3278** rather they control the timing of when other statements modify the
3279** database.  ^The [ATTACH] and [DETACH] statements also cause
3280** sqlite3_stmt_readonly() to return true since, while those statements
3281** change the configuration of a database connection, they do not make
3282** changes to the content of the database files on disk.
3283*/
3284SQLITE_API int sqlite3_stmt_readonly(sqlite3_stmt *pStmt);
3285
3286/*
3287** CAPI3REF: Dynamically Typed Value Object
3288** KEYWORDS: {protected sqlite3_value} {unprotected sqlite3_value}
3289**
3290** SQLite uses the sqlite3_value object to represent all values
3291** that can be stored in a database table. SQLite uses dynamic typing
3292** for the values it stores.  ^Values stored in sqlite3_value objects
3293** can be integers, floating point values, strings, BLOBs, or NULL.
3294**
3295** An sqlite3_value object may be either "protected" or "unprotected".
3296** Some interfaces require a protected sqlite3_value.  Other interfaces
3297** will accept either a protected or an unprotected sqlite3_value.
3298** Every interface that accepts sqlite3_value arguments specifies
3299** whether or not it requires a protected sqlite3_value.
3300**
3301** The terms "protected" and "unprotected" refer to whether or not
3302** a mutex is held.  An internal mutex is held for a protected
3303** sqlite3_value object but no mutex is held for an unprotected
3304** sqlite3_value object.  If SQLite is compiled to be single-threaded
3305** (with [SQLITE_THREADSAFE=0] and with [sqlite3_threadsafe()] returning 0)
3306** or if SQLite is run in one of reduced mutex modes
3307** [SQLITE_CONFIG_SINGLETHREAD] or [SQLITE_CONFIG_MULTITHREAD]
3308** then there is no distinction between protected and unprotected
3309** sqlite3_value objects and they can be used interchangeably.  However,
3310** for maximum code portability it is recommended that applications
3311** still make the distinction between protected and unprotected
3312** sqlite3_value objects even when not strictly required.
3313**
3314** ^The sqlite3_value objects that are passed as parameters into the
3315** implementation of [application-defined SQL functions] are protected.
3316** ^The sqlite3_value object returned by
3317** [sqlite3_column_value()] is unprotected.
3318** Unprotected sqlite3_value objects may only be used with
3319** [sqlite3_result_value()] and [sqlite3_bind_value()].
3320** The [sqlite3_value_blob | sqlite3_value_type()] family of
3321** interfaces require protected sqlite3_value objects.
3322*/
3323typedef struct Mem sqlite3_value;
3324
3325/*
3326** CAPI3REF: SQL Function Context Object
3327**
3328** The context in which an SQL function executes is stored in an
3329** sqlite3_context object.  ^A pointer to an sqlite3_context object
3330** is always first parameter to [application-defined SQL functions].
3331** The application-defined SQL function implementation will pass this
3332** pointer through into calls to [sqlite3_result_int | sqlite3_result()],
3333** [sqlite3_aggregate_context()], [sqlite3_user_data()],
3334** [sqlite3_context_db_handle()], [sqlite3_get_auxdata()],
3335** and/or [sqlite3_set_auxdata()].
3336*/
3337typedef struct sqlite3_context sqlite3_context;
3338
3339/*
3340** CAPI3REF: Binding Values To Prepared Statements
3341** KEYWORDS: {host parameter} {host parameters} {host parameter name}
3342** KEYWORDS: {SQL parameter} {SQL parameters} {parameter binding}
3343**
3344** ^(In the SQL statement text input to [sqlite3_prepare_v2()] and its variants,
3345** literals may be replaced by a [parameter] that matches one of following
3346** templates:
3347**
3348** <ul>
3349** <li>  ?
3350** <li>  ?NNN
3351** <li>  :VVV
3352** <li>  @VVV
3353** <li>  $VVV
3354** </ul>
3355**
3356** In the templates above, NNN represents an integer literal,
3357** and VVV represents an alphanumeric identifier.)^  ^The values of these
3358** parameters (also called "host parameter names" or "SQL parameters")
3359** can be set using the sqlite3_bind_*() routines defined here.
3360**
3361** ^The first argument to the sqlite3_bind_*() routines is always
3362** a pointer to the [sqlite3_stmt] object returned from
3363** [sqlite3_prepare_v2()] or its variants.
3364**
3365** ^The second argument is the index of the SQL parameter to be set.
3366** ^The leftmost SQL parameter has an index of 1.  ^When the same named
3367** SQL parameter is used more than once, second and subsequent
3368** occurrences have the same index as the first occurrence.
3369** ^The index for named parameters can be looked up using the
3370** [sqlite3_bind_parameter_index()] API if desired.  ^The index
3371** for "?NNN" parameters is the value of NNN.
3372** ^The NNN value must be between 1 and the [sqlite3_limit()]
3373** parameter [SQLITE_LIMIT_VARIABLE_NUMBER] (default value: 999).
3374**
3375** ^The third argument is the value to bind to the parameter.
3376**
3377** ^(In those routines that have a fourth argument, its value is the
3378** number of bytes in the parameter.  To be clear: the value is the
3379** number of <u>bytes</u> in the value, not the number of characters.)^
3380** ^If the fourth parameter is negative, the length of the string is
3381** the number of bytes up to the first zero terminator.
3382**
3383** ^The fifth argument to sqlite3_bind_blob(), sqlite3_bind_text(), and
3384** sqlite3_bind_text16() is a destructor used to dispose of the BLOB or
3385** string after SQLite has finished with it.  ^The destructor is called
3386** to dispose of the BLOB or string even if the call to sqlite3_bind_blob(),
3387** sqlite3_bind_text(), or sqlite3_bind_text16() fails.
3388** ^If the fifth argument is
3389** the special value [SQLITE_STATIC], then SQLite assumes that the
3390** information is in static, unmanaged space and does not need to be freed.
3391** ^If the fifth argument has the value [SQLITE_TRANSIENT], then
3392** SQLite makes its own private copy of the data immediately, before
3393** the sqlite3_bind_*() routine returns.
3394**
3395** ^The sqlite3_bind_zeroblob() routine binds a BLOB of length N that
3396** is filled with zeroes.  ^A zeroblob uses a fixed amount of memory
3397** (just an integer to hold its size) while it is being processed.
3398** Zeroblobs are intended to serve as placeholders for BLOBs whose
3399** content is later written using
3400** [sqlite3_blob_open | incremental BLOB I/O] routines.
3401** ^A negative value for the zeroblob results in a zero-length BLOB.
3402**
3403** ^If any of the sqlite3_bind_*() routines are called with a NULL pointer
3404** for the [prepared statement] or with a prepared statement for which
3405** [sqlite3_step()] has been called more recently than [sqlite3_reset()],
3406** then the call will return [SQLITE_MISUSE].  If any sqlite3_bind_()
3407** routine is passed a [prepared statement] that has been finalized, the
3408** result is undefined and probably harmful.
3409**
3410** ^Bindings are not cleared by the [sqlite3_reset()] routine.
3411** ^Unbound parameters are interpreted as NULL.
3412**
3413** ^The sqlite3_bind_* routines return [SQLITE_OK] on success or an
3414** [error code] if anything goes wrong.
3415** ^[SQLITE_RANGE] is returned if the parameter
3416** index is out of range.  ^[SQLITE_NOMEM] is returned if malloc() fails.
3417**
3418** See also: [sqlite3_bind_parameter_count()],
3419** [sqlite3_bind_parameter_name()], and [sqlite3_bind_parameter_index()].
3420*/
3421SQLITE_API int sqlite3_bind_blob(sqlite3_stmt*, int, const void*, int n, void(*)(void*));
3422SQLITE_API int sqlite3_bind_double(sqlite3_stmt*, int, double);
3423SQLITE_API int sqlite3_bind_int(sqlite3_stmt*, int, int);
3424SQLITE_API int sqlite3_bind_int64(sqlite3_stmt*, int, sqlite3_int64);
3425SQLITE_API int sqlite3_bind_null(sqlite3_stmt*, int);
3426SQLITE_API int sqlite3_bind_text(sqlite3_stmt*, int, const char*, int n, void(*)(void*));
3427SQLITE_API int sqlite3_bind_text16(sqlite3_stmt*, int, const void*, int, void(*)(void*));
3428SQLITE_API int sqlite3_bind_value(sqlite3_stmt*, int, const sqlite3_value*);
3429SQLITE_API int sqlite3_bind_zeroblob(sqlite3_stmt*, int, int n);
3430
3431/*
3432** CAPI3REF: Number Of SQL Parameters
3433**
3434** ^This routine can be used to find the number of [SQL parameters]
3435** in a [prepared statement].  SQL parameters are tokens of the
3436** form "?", "?NNN", ":AAA", "$AAA", or "@AAA" that serve as
3437** placeholders for values that are [sqlite3_bind_blob | bound]
3438** to the parameters at a later time.
3439**
3440** ^(This routine actually returns the index of the largest (rightmost)
3441** parameter. For all forms except ?NNN, this will correspond to the
3442** number of unique parameters.  If parameters of the ?NNN form are used,
3443** there may be gaps in the list.)^
3444**
3445** See also: [sqlite3_bind_blob|sqlite3_bind()],
3446** [sqlite3_bind_parameter_name()], and
3447** [sqlite3_bind_parameter_index()].
3448*/
3449SQLITE_API int sqlite3_bind_parameter_count(sqlite3_stmt*);
3450
3451/*
3452** CAPI3REF: Name Of A Host Parameter
3453**
3454** ^The sqlite3_bind_parameter_name(P,N) interface returns
3455** the name of the N-th [SQL parameter] in the [prepared statement] P.
3456** ^(SQL parameters of the form "?NNN" or ":AAA" or "@AAA" or "$AAA"
3457** have a name which is the string "?NNN" or ":AAA" or "@AAA" or "$AAA"
3458** respectively.
3459** In other words, the initial ":" or "$" or "@" or "?"
3460** is included as part of the name.)^
3461** ^Parameters of the form "?" without a following integer have no name
3462** and are referred to as "nameless" or "anonymous parameters".
3463**
3464** ^The first host parameter has an index of 1, not 0.
3465**
3466** ^If the value N is out of range or if the N-th parameter is
3467** nameless, then NULL is returned.  ^The returned string is
3468** always in UTF-8 encoding even if the named parameter was
3469** originally specified as UTF-16 in [sqlite3_prepare16()] or
3470** [sqlite3_prepare16_v2()].
3471**
3472** See also: [sqlite3_bind_blob|sqlite3_bind()],
3473** [sqlite3_bind_parameter_count()], and
3474** [sqlite3_bind_parameter_index()].
3475*/
3476SQLITE_API const char *sqlite3_bind_parameter_name(sqlite3_stmt*, int);
3477
3478/*
3479** CAPI3REF: Index Of A Parameter With A Given Name
3480**
3481** ^Return the index of an SQL parameter given its name.  ^The
3482** index value returned is suitable for use as the second
3483** parameter to [sqlite3_bind_blob|sqlite3_bind()].  ^A zero
3484** is returned if no matching parameter is found.  ^The parameter
3485** name must be given in UTF-8 even if the original statement
3486** was prepared from UTF-16 text using [sqlite3_prepare16_v2()].
3487**
3488** See also: [sqlite3_bind_blob|sqlite3_bind()],
3489** [sqlite3_bind_parameter_count()], and
3490** [sqlite3_bind_parameter_index()].
3491*/
3492SQLITE_API int sqlite3_bind_parameter_index(sqlite3_stmt*, const char *zName);
3493
3494/*
3495** CAPI3REF: Reset All Bindings On A Prepared Statement
3496**
3497** ^Contrary to the intuition of many, [sqlite3_reset()] does not reset
3498** the [sqlite3_bind_blob | bindings] on a [prepared statement].
3499** ^Use this routine to reset all host parameters to NULL.
3500*/
3501SQLITE_API int sqlite3_clear_bindings(sqlite3_stmt*);
3502
3503/*
3504** CAPI3REF: Number Of Columns In A Result Set
3505**
3506** ^Return the number of columns in the result set returned by the
3507** [prepared statement]. ^This routine returns 0 if pStmt is an SQL
3508** statement that does not return data (for example an [UPDATE]).
3509**
3510** See also: [sqlite3_data_count()]
3511*/
3512SQLITE_API int sqlite3_column_count(sqlite3_stmt *pStmt);
3513
3514/*
3515** CAPI3REF: Column Names In A Result Set
3516**
3517** ^These routines return the name assigned to a particular column
3518** in the result set of a [SELECT] statement.  ^The sqlite3_column_name()
3519** interface returns a pointer to a zero-terminated UTF-8 string
3520** and sqlite3_column_name16() returns a pointer to a zero-terminated
3521** UTF-16 string.  ^The first parameter is the [prepared statement]
3522** that implements the [SELECT] statement. ^The second parameter is the
3523** column number.  ^The leftmost column is number 0.
3524**
3525** ^The returned string pointer is valid until either the [prepared statement]
3526** is destroyed by [sqlite3_finalize()] or until the statement is automatically
3527** reprepared by the first call to [sqlite3_step()] for a particular run
3528** or until the next call to
3529** sqlite3_column_name() or sqlite3_column_name16() on the same column.
3530**
3531** ^If sqlite3_malloc() fails during the processing of either routine
3532** (for example during a conversion from UTF-8 to UTF-16) then a
3533** NULL pointer is returned.
3534**
3535** ^The name of a result column is the value of the "AS" clause for
3536** that column, if there is an AS clause.  If there is no AS clause
3537** then the name of the column is unspecified and may change from
3538** one release of SQLite to the next.
3539*/
3540SQLITE_API const char *sqlite3_column_name(sqlite3_stmt*, int N);
3541SQLITE_API const void *sqlite3_column_name16(sqlite3_stmt*, int N);
3542
3543/*
3544** CAPI3REF: Source Of Data In A Query Result
3545**
3546** ^These routines provide a means to determine the database, table, and
3547** table column that is the origin of a particular result column in
3548** [SELECT] statement.
3549** ^The name of the database or table or column can be returned as
3550** either a UTF-8 or UTF-16 string.  ^The _database_ routines return
3551** the database name, the _table_ routines return the table name, and
3552** the origin_ routines return the column name.
3553** ^The returned string is valid until the [prepared statement] is destroyed
3554** using [sqlite3_finalize()] or until the statement is automatically
3555** reprepared by the first call to [sqlite3_step()] for a particular run
3556** or until the same information is requested
3557** again in a different encoding.
3558**
3559** ^The names returned are the original un-aliased names of the
3560** database, table, and column.
3561**
3562** ^The first argument to these interfaces is a [prepared statement].
3563** ^These functions return information about the Nth result column returned by
3564** the statement, where N is the second function argument.
3565** ^The left-most column is column 0 for these routines.
3566**
3567** ^If the Nth column returned by the statement is an expression or
3568** subquery and is not a column value, then all of these functions return
3569** NULL.  ^These routine might also return NULL if a memory allocation error
3570** occurs.  ^Otherwise, they return the name of the attached database, table,
3571** or column that query result column was extracted from.
3572**
3573** ^As with all other SQLite APIs, those whose names end with "16" return
3574** UTF-16 encoded strings and the other functions return UTF-8.
3575**
3576** ^These APIs are only available if the library was compiled with the
3577** [SQLITE_ENABLE_COLUMN_METADATA] C-preprocessor symbol.
3578**
3579** If two or more threads call one or more of these routines against the same
3580** prepared statement and column at the same time then the results are
3581** undefined.
3582**
3583** If two or more threads call one or more
3584** [sqlite3_column_database_name | column metadata interfaces]
3585** for the same [prepared statement] and result column
3586** at the same time then the results are undefined.
3587*/
3588SQLITE_API const char *sqlite3_column_database_name(sqlite3_stmt*,int);
3589SQLITE_API const void *sqlite3_column_database_name16(sqlite3_stmt*,int);
3590SQLITE_API const char *sqlite3_column_table_name(sqlite3_stmt*,int);
3591SQLITE_API const void *sqlite3_column_table_name16(sqlite3_stmt*,int);
3592SQLITE_API const char *sqlite3_column_origin_name(sqlite3_stmt*,int);
3593SQLITE_API const void *sqlite3_column_origin_name16(sqlite3_stmt*,int);
3594
3595/*
3596** CAPI3REF: Declared Datatype Of A Query Result
3597**
3598** ^(The first parameter is a [prepared statement].
3599** If this statement is a [SELECT] statement and the Nth column of the
3600** returned result set of that [SELECT] is a table column (not an
3601** expression or subquery) then the declared type of the table
3602** column is returned.)^  ^If the Nth column of the result set is an
3603** expression or subquery, then a NULL pointer is returned.
3604** ^The returned string is always UTF-8 encoded.
3605**
3606** ^(For example, given the database schema:
3607**
3608** CREATE TABLE t1(c1 VARIANT);
3609**
3610** and the following statement to be compiled:
3611**
3612** SELECT c1 + 1, c1 FROM t1;
3613**
3614** this routine would return the string "VARIANT" for the second result
3615** column (i==1), and a NULL pointer for the first result column (i==0).)^
3616**
3617** ^SQLite uses dynamic run-time typing.  ^So just because a column
3618** is declared to contain a particular type does not mean that the
3619** data stored in that column is of the declared type.  SQLite is
3620** strongly typed, but the typing is dynamic not static.  ^Type
3621** is associated with individual values, not with the containers
3622** used to hold those values.
3623*/
3624SQLITE_API const char *sqlite3_column_decltype(sqlite3_stmt*,int);
3625SQLITE_API const void *sqlite3_column_decltype16(sqlite3_stmt*,int);
3626
3627/*
3628** CAPI3REF: Evaluate An SQL Statement
3629**
3630** After a [prepared statement] has been prepared using either
3631** [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] or one of the legacy
3632** interfaces [sqlite3_prepare()] or [sqlite3_prepare16()], this function
3633** must be called one or more times to evaluate the statement.
3634**
3635** The details of the behavior of the sqlite3_step() interface depend
3636** on whether the statement was prepared using the newer "v2" interface
3637** [sqlite3_prepare_v2()] and [sqlite3_prepare16_v2()] or the older legacy
3638** interface [sqlite3_prepare()] and [sqlite3_prepare16()].  The use of the
3639** new "v2" interface is recommended for new applications but the legacy
3640** interface will continue to be supported.
3641**
3642** ^In the legacy interface, the return value will be either [SQLITE_BUSY],
3643** [SQLITE_DONE], [SQLITE_ROW], [SQLITE_ERROR], or [SQLITE_MISUSE].
3644** ^With the "v2" interface, any of the other [result codes] or
3645** [extended result codes] might be returned as well.
3646**
3647** ^[SQLITE_BUSY] means that the database engine was unable to acquire the
3648** database locks it needs to do its job.  ^If the statement is a [COMMIT]
3649** or occurs outside of an explicit transaction, then you can retry the
3650** statement.  If the statement is not a [COMMIT] and occurs within a
3651** explicit transaction then you should rollback the transaction before
3652** continuing.
3653**
3654** ^[SQLITE_DONE] means that the statement has finished executing
3655** successfully.  sqlite3_step() should not be called again on this virtual
3656** machine without first calling [sqlite3_reset()] to reset the virtual
3657** machine back to its initial state.
3658**
3659** ^If the SQL statement being executed returns any data, then [SQLITE_ROW]
3660** is returned each time a new row of data is ready for processing by the
3661** caller. The values may be accessed using the [column access functions].
3662** sqlite3_step() is called again to retrieve the next row of data.
3663**
3664** ^[SQLITE_ERROR] means that a run-time error (such as a constraint
3665** violation) has occurred.  sqlite3_step() should not be called again on
3666** the VM. More information may be found by calling [sqlite3_errmsg()].
3667** ^With the legacy interface, a more specific error code (for example,
3668** [SQLITE_INTERRUPT], [SQLITE_SCHEMA], [SQLITE_CORRUPT], and so forth)
3669** can be obtained by calling [sqlite3_reset()] on the
3670** [prepared statement].  ^In the "v2" interface,
3671** the more specific error code is returned directly by sqlite3_step().
3672**
3673** [SQLITE_MISUSE] means that the this routine was called inappropriately.
3674** Perhaps it was called on a [prepared statement] that has
3675** already been [sqlite3_finalize | finalized] or on one that had
3676** previously returned [SQLITE_ERROR] or [SQLITE_DONE].  Or it could
3677** be the case that the same database connection is being used by two or
3678** more threads at the same moment in time.
3679**
3680** For all versions of SQLite up to and including 3.6.23.1, a call to
3681** [sqlite3_reset()] was required after sqlite3_step() returned anything
3682** other than [SQLITE_ROW] before any subsequent invocation of
3683** sqlite3_step().  Failure to reset the prepared statement using
3684** [sqlite3_reset()] would result in an [SQLITE_MISUSE] return from
3685** sqlite3_step().  But after version 3.6.23.1, sqlite3_step() began
3686** calling [sqlite3_reset()] automatically in this circumstance rather
3687** than returning [SQLITE_MISUSE].  This is not considered a compatibility
3688** break because any application that ever receives an SQLITE_MISUSE error
3689** is broken by definition.  The [SQLITE_OMIT_AUTORESET] compile-time option
3690** can be used to restore the legacy behavior.
3691**
3692** <b>Goofy Interface Alert:</b> In the legacy interface, the sqlite3_step()
3693** API always returns a generic error code, [SQLITE_ERROR], following any
3694** error other than [SQLITE_BUSY] and [SQLITE_MISUSE].  You must call
3695** [sqlite3_reset()] or [sqlite3_finalize()] in order to find one of the
3696** specific [error codes] that better describes the error.
3697** We admit that this is a goofy design.  The problem has been fixed
3698** with the "v2" interface.  If you prepare all of your SQL statements
3699** using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] instead
3700** of the legacy [sqlite3_prepare()] and [sqlite3_prepare16()] interfaces,
3701** then the more specific [error codes] are returned directly
3702** by sqlite3_step().  The use of the "v2" interface is recommended.
3703*/
3704SQLITE_API int sqlite3_step(sqlite3_stmt*);
3705
3706/*
3707** CAPI3REF: Number of columns in a result set
3708**
3709** ^The sqlite3_data_count(P) interface returns the number of columns in the
3710** current row of the result set of [prepared statement] P.
3711** ^If prepared statement P does not have results ready to return
3712** (via calls to the [sqlite3_column_int | sqlite3_column_*()] of
3713** interfaces) then sqlite3_data_count(P) returns 0.
3714** ^The sqlite3_data_count(P) routine also returns 0 if P is a NULL pointer.
3715**
3716** See also: [sqlite3_column_count()]
3717*/
3718SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt);
3719
3720/*
3721** CAPI3REF: Fundamental Datatypes
3722** KEYWORDS: SQLITE_TEXT
3723**
3724** ^(Every value in SQLite has one of five fundamental datatypes:
3725**
3726** <ul>
3727** <li> 64-bit signed integer
3728** <li> 64-bit IEEE floating point number
3729** <li> string
3730** <li> BLOB
3731** <li> NULL
3732** </ul>)^
3733**
3734** These constants are codes for each of those types.
3735**
3736** Note that the SQLITE_TEXT constant was also used in SQLite version 2
3737** for a completely different meaning.  Software that links against both
3738** SQLite version 2 and SQLite version 3 should use SQLITE3_TEXT, not
3739** SQLITE_TEXT.
3740*/
3741#define SQLITE_INTEGER  1
3742#define SQLITE_FLOAT    2
3743#define SQLITE_BLOB     4
3744#define SQLITE_NULL     5
3745#ifdef SQLITE_TEXT
3746# undef SQLITE_TEXT
3747#else
3748# define SQLITE_TEXT     3
3749#endif
3750#define SQLITE3_TEXT     3
3751
3752/*
3753** CAPI3REF: Result Values From A Query
3754** KEYWORDS: {column access functions}
3755**
3756** These routines form the "result set" interface.
3757**
3758** ^These routines return information about a single column of the current
3759** result row of a query.  ^In every case the first argument is a pointer
3760** to the [prepared statement] that is being evaluated (the [sqlite3_stmt*]
3761** that was returned from [sqlite3_prepare_v2()] or one of its variants)
3762** and the second argument is the index of the column for which information
3763** should be returned. ^The leftmost column of the result set has the index 0.
3764** ^The number of columns in the result can be determined using
3765** [sqlite3_column_count()].
3766**
3767** If the SQL statement does not currently point to a valid row, or if the
3768** column index is out of range, the result is undefined.
3769** These routines may only be called when the most recent call to
3770** [sqlite3_step()] has returned [SQLITE_ROW] and neither
3771** [sqlite3_reset()] nor [sqlite3_finalize()] have been called subsequently.
3772** If any of these routines are called after [sqlite3_reset()] or
3773** [sqlite3_finalize()] or after [sqlite3_step()] has returned
3774** something other than [SQLITE_ROW], the results are undefined.
3775** If [sqlite3_step()] or [sqlite3_reset()] or [sqlite3_finalize()]
3776** are called from a different thread while any of these routines
3777** are pending, then the results are undefined.
3778**
3779** ^The sqlite3_column_type() routine returns the
3780** [SQLITE_INTEGER | datatype code] for the initial data type
3781** of the result column.  ^The returned value is one of [SQLITE_INTEGER],
3782** [SQLITE_FLOAT], [SQLITE_TEXT], [SQLITE_BLOB], or [SQLITE_NULL].  The value
3783** returned by sqlite3_column_type() is only meaningful if no type
3784** conversions have occurred as described below.  After a type conversion,
3785** the value returned by sqlite3_column_type() is undefined.  Future
3786** versions of SQLite may change the behavior of sqlite3_column_type()
3787** following a type conversion.
3788**
3789** ^If the result is a BLOB or UTF-8 string then the sqlite3_column_bytes()
3790** routine returns the number of bytes in that BLOB or string.
3791** ^If the result is a UTF-16 string, then sqlite3_column_bytes() converts
3792** the string to UTF-8 and then returns the number of bytes.
3793** ^If the result is a numeric value then sqlite3_column_bytes() uses
3794** [sqlite3_snprintf()] to convert that value to a UTF-8 string and returns
3795** the number of bytes in that string.
3796** ^If the result is NULL, then sqlite3_column_bytes() returns zero.
3797**
3798** ^If the result is a BLOB or UTF-16 string then the sqlite3_column_bytes16()
3799** routine returns the number of bytes in that BLOB or string.
3800** ^If the result is a UTF-8 string, then sqlite3_column_bytes16() converts
3801** the string to UTF-16 and then returns the number of bytes.
3802** ^If the result is a numeric value then sqlite3_column_bytes16() uses
3803** [sqlite3_snprintf()] to convert that value to a UTF-16 string and returns
3804** the number of bytes in that string.
3805** ^If the result is NULL, then sqlite3_column_bytes16() returns zero.
3806**
3807** ^The values returned by [sqlite3_column_bytes()] and
3808** [sqlite3_column_bytes16()] do not include the zero terminators at the end
3809** of the string.  ^For clarity: the values returned by
3810** [sqlite3_column_bytes()] and [sqlite3_column_bytes16()] are the number of
3811** bytes in the string, not the number of characters.
3812**
3813** ^Strings returned by sqlite3_column_text() and sqlite3_column_text16(),
3814** even empty strings, are always zero terminated.  ^The return
3815** value from sqlite3_column_blob() for a zero-length BLOB is a NULL pointer.
3816**
3817** ^The object returned by [sqlite3_column_value()] is an
3818** [unprotected sqlite3_value] object.  An unprotected sqlite3_value object
3819** may only be used with [sqlite3_bind_value()] and [sqlite3_result_value()].
3820** If the [unprotected sqlite3_value] object returned by
3821** [sqlite3_column_value()] is used in any other way, including calls
3822** to routines like [sqlite3_value_int()], [sqlite3_value_text()],
3823** or [sqlite3_value_bytes()], then the behavior is undefined.
3824**
3825** These routines attempt to convert the value where appropriate.  ^For
3826** example, if the internal representation is FLOAT and a text result
3827** is requested, [sqlite3_snprintf()] is used internally to perform the
3828** conversion automatically.  ^(The following table details the conversions
3829** that are applied:
3830**
3831** <blockquote>
3832** <table border="1">
3833** <tr><th> Internal<br>Type <th> Requested<br>Type <th>  Conversion
3834**
3835** <tr><td>  NULL    <td> INTEGER   <td> Result is 0
3836** <tr><td>  NULL    <td>  FLOAT    <td> Result is 0.0
3837** <tr><td>  NULL    <td>   TEXT    <td> Result is NULL pointer
3838** <tr><td>  NULL    <td>   BLOB    <td> Result is NULL pointer
3839** <tr><td> INTEGER  <td>  FLOAT    <td> Convert from integer to float
3840** <tr><td> INTEGER  <td>   TEXT    <td> ASCII rendering of the integer
3841** <tr><td> INTEGER  <td>   BLOB    <td> Same as INTEGER->TEXT
3842** <tr><td>  FLOAT   <td> INTEGER   <td> Convert from float to integer
3843** <tr><td>  FLOAT   <td>   TEXT    <td> ASCII rendering of the float
3844** <tr><td>  FLOAT   <td>   BLOB    <td> Same as FLOAT->TEXT
3845** <tr><td>  TEXT    <td> INTEGER   <td> Use atoi()
3846** <tr><td>  TEXT    <td>  FLOAT    <td> Use atof()
3847** <tr><td>  TEXT    <td>   BLOB    <td> No change
3848** <tr><td>  BLOB    <td> INTEGER   <td> Convert to TEXT then use atoi()
3849** <tr><td>  BLOB    <td>  FLOAT    <td> Convert to TEXT then use atof()
3850** <tr><td>  BLOB    <td>   TEXT    <td> Add a zero terminator if needed
3851** </table>
3852** </blockquote>)^
3853**
3854** The table above makes reference to standard C library functions atoi()
3855** and atof().  SQLite does not really use these functions.  It has its
3856** own equivalent internal routines.  The atoi() and atof() names are
3857** used in the table for brevity and because they are familiar to most
3858** C programmers.
3859**
3860** Note that when type conversions occur, pointers returned by prior
3861** calls to sqlite3_column_blob(), sqlite3_column_text(), and/or
3862** sqlite3_column_text16() may be invalidated.
3863** Type conversions and pointer invalidations might occur
3864** in the following cases:
3865**
3866** <ul>
3867** <li> The initial content is a BLOB and sqlite3_column_text() or
3868**      sqlite3_column_text16() is called.  A zero-terminator might
3869**      need to be added to the string.</li>
3870** <li> The initial content is UTF-8 text and sqlite3_column_bytes16() or
3871**      sqlite3_column_text16() is called.  The content must be converted
3872**      to UTF-16.</li>
3873** <li> The initial content is UTF-16 text and sqlite3_column_bytes() or
3874**      sqlite3_column_text() is called.  The content must be converted
3875**      to UTF-8.</li>
3876** </ul>
3877**
3878** ^Conversions between UTF-16be and UTF-16le are always done in place and do
3879** not invalidate a prior pointer, though of course the content of the buffer
3880** that the prior pointer references will have been modified.  Other kinds
3881** of conversion are done in place when it is possible, but sometimes they
3882** are not possible and in those cases prior pointers are invalidated.
3883**
3884** The safest and easiest to remember policy is to invoke these routines
3885** in one of the following ways:
3886**
3887** <ul>
3888**  <li>sqlite3_column_text() followed by sqlite3_column_bytes()</li>
3889**  <li>sqlite3_column_blob() followed by sqlite3_column_bytes()</li>
3890**  <li>sqlite3_column_text16() followed by sqlite3_column_bytes16()</li>
3891** </ul>
3892**
3893** In other words, you should call sqlite3_column_text(),
3894** sqlite3_column_blob(), or sqlite3_column_text16() first to force the result
3895** into the desired format, then invoke sqlite3_column_bytes() or
3896** sqlite3_column_bytes16() to find the size of the result.  Do not mix calls
3897** to sqlite3_column_text() or sqlite3_column_blob() with calls to
3898** sqlite3_column_bytes16(), and do not mix calls to sqlite3_column_text16()
3899** with calls to sqlite3_column_bytes().
3900**
3901** ^The pointers returned are valid until a type conversion occurs as
3902** described above, or until [sqlite3_step()] or [sqlite3_reset()] or
3903** [sqlite3_finalize()] is called.  ^The memory space used to hold strings
3904** and BLOBs is freed automatically.  Do <b>not</b> pass the pointers returned
3905** [sqlite3_column_blob()], [sqlite3_column_text()], etc. into
3906** [sqlite3_free()].
3907**
3908** ^(If a memory allocation error occurs during the evaluation of any
3909** of these routines, a default value is returned.  The default value
3910** is either the integer 0, the floating point number 0.0, or a NULL
3911** pointer.  Subsequent calls to [sqlite3_errcode()] will return
3912** [SQLITE_NOMEM].)^
3913*/
3914SQLITE_API const void *sqlite3_column_blob(sqlite3_stmt*, int iCol);
3915SQLITE_API int sqlite3_column_bytes(sqlite3_stmt*, int iCol);
3916SQLITE_API int sqlite3_column_bytes16(sqlite3_stmt*, int iCol);
3917SQLITE_API double sqlite3_column_double(sqlite3_stmt*, int iCol);
3918SQLITE_API int sqlite3_column_int(sqlite3_stmt*, int iCol);
3919SQLITE_API sqlite3_int64 sqlite3_column_int64(sqlite3_stmt*, int iCol);
3920SQLITE_API const unsigned char *sqlite3_column_text(sqlite3_stmt*, int iCol);
3921SQLITE_API const void *sqlite3_column_text16(sqlite3_stmt*, int iCol);
3922SQLITE_API int sqlite3_column_type(sqlite3_stmt*, int iCol);
3923SQLITE_API sqlite3_value *sqlite3_column_value(sqlite3_stmt*, int iCol);
3924
3925/*
3926** CAPI3REF: Destroy A Prepared Statement Object
3927**
3928** ^The sqlite3_finalize() function is called to delete a [prepared statement].
3929** ^If the most recent evaluation of the statement encountered no errors or
3930** or if the statement is never been evaluated, then sqlite3_finalize() returns
3931** SQLITE_OK.  ^If the most recent evaluation of statement S failed, then
3932** sqlite3_finalize(S) returns the appropriate [error code] or
3933** [extended error code].
3934**
3935** ^The sqlite3_finalize(S) routine can be called at any point during
3936** the life cycle of [prepared statement] S:
3937** before statement S is ever evaluated, after
3938** one or more calls to [sqlite3_reset()], or after any call
3939** to [sqlite3_step()] regardless of whether or not the statement has
3940** completed execution.
3941**
3942** ^Invoking sqlite3_finalize() on a NULL pointer is a harmless no-op.
3943**
3944** The application must finalize every [prepared statement] in order to avoid
3945** resource leaks.  It is a grievous error for the application to try to use
3946** a prepared statement after it has been finalized.  Any use of a prepared
3947** statement after it has been finalized can result in undefined and
3948** undesirable behavior such as segfaults and heap corruption.
3949*/
3950SQLITE_API int sqlite3_finalize(sqlite3_stmt *pStmt);
3951
3952/*
3953** CAPI3REF: Reset A Prepared Statement Object
3954**
3955** The sqlite3_reset() function is called to reset a [prepared statement]
3956** object back to its initial state, ready to be re-executed.
3957** ^Any SQL statement variables that had values bound to them using
3958** the [sqlite3_bind_blob | sqlite3_bind_*() API] retain their values.
3959** Use [sqlite3_clear_bindings()] to reset the bindings.
3960**
3961** ^The [sqlite3_reset(S)] interface resets the [prepared statement] S
3962** back to the beginning of its program.
3963**
3964** ^If the most recent call to [sqlite3_step(S)] for the
3965** [prepared statement] S returned [SQLITE_ROW] or [SQLITE_DONE],
3966** or if [sqlite3_step(S)] has never before been called on S,
3967** then [sqlite3_reset(S)] returns [SQLITE_OK].
3968**
3969** ^If the most recent call to [sqlite3_step(S)] for the
3970** [prepared statement] S indicated an error, then
3971** [sqlite3_reset(S)] returns an appropriate [error code].
3972**
3973** ^The [sqlite3_reset(S)] interface does not change the values
3974** of any [sqlite3_bind_blob|bindings] on the [prepared statement] S.
3975*/
3976SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt);
3977
3978/*
3979** CAPI3REF: Create Or Redefine SQL Functions
3980** KEYWORDS: {function creation routines}
3981** KEYWORDS: {application-defined SQL function}
3982** KEYWORDS: {application-defined SQL functions}
3983**
3984** ^These functions (collectively known as "function creation routines")
3985** are used to add SQL functions or aggregates or to redefine the behavior
3986** of existing SQL functions or aggregates.  The only differences between
3987** these routines are the text encoding expected for
3988** the second parameter (the name of the function being created)
3989** and the presence or absence of a destructor callback for
3990** the application data pointer.
3991**
3992** ^The first parameter is the [database connection] to which the SQL
3993** function is to be added.  ^If an application uses more than one database
3994** connection then application-defined SQL functions must be added
3995** to each database connection separately.
3996**
3997** ^The second parameter is the name of the SQL function to be created or
3998** redefined.  ^The length of the name is limited to 255 bytes in a UTF-8
3999** representation, exclusive of the zero-terminator.  ^Note that the name
4000** length limit is in UTF-8 bytes, not characters nor UTF-16 bytes.
4001** ^Any attempt to create a function with a longer name
4002** will result in [SQLITE_MISUSE] being returned.
4003**
4004** ^The third parameter (nArg)
4005** is the number of arguments that the SQL function or
4006** aggregate takes. ^If this parameter is -1, then the SQL function or
4007** aggregate may take any number of arguments between 0 and the limit
4008** set by [sqlite3_limit]([SQLITE_LIMIT_FUNCTION_ARG]).  If the third
4009** parameter is less than -1 or greater than 127 then the behavior is
4010** undefined.
4011**
4012** ^The fourth parameter, eTextRep, specifies what
4013** [SQLITE_UTF8 | text encoding] this SQL function prefers for
4014** its parameters.  Every SQL function implementation must be able to work
4015** with UTF-8, UTF-16le, or UTF-16be.  But some implementations may be
4016** more efficient with one encoding than another.  ^An application may
4017** invoke sqlite3_create_function() or sqlite3_create_function16() multiple
4018** times with the same function but with different values of eTextRep.
4019** ^When multiple implementations of the same function are available, SQLite
4020** will pick the one that involves the least amount of data conversion.
4021** If there is only a single implementation which does not care what text
4022** encoding is used, then the fourth argument should be [SQLITE_ANY].
4023**
4024** ^(The fifth parameter is an arbitrary pointer.  The implementation of the
4025** function can gain access to this pointer using [sqlite3_user_data()].)^
4026**
4027** ^The sixth, seventh and eighth parameters, xFunc, xStep and xFinal, are
4028** pointers to C-language functions that implement the SQL function or
4029** aggregate. ^A scalar SQL function requires an implementation of the xFunc
4030** callback only; NULL pointers must be passed as the xStep and xFinal
4031** parameters. ^An aggregate SQL function requires an implementation of xStep
4032** and xFinal and NULL pointer must be passed for xFunc. ^To delete an existing
4033** SQL function or aggregate, pass NULL pointers for all three function
4034** callbacks.
4035**
4036** ^(If the ninth parameter to sqlite3_create_function_v2() is not NULL,
4037** then it is destructor for the application data pointer.
4038** The destructor is invoked when the function is deleted, either by being
4039** overloaded or when the database connection closes.)^
4040** ^The destructor is also invoked if the call to
4041** sqlite3_create_function_v2() fails.
4042** ^When the destructor callback of the tenth parameter is invoked, it
4043** is passed a single argument which is a copy of the application data
4044** pointer which was the fifth parameter to sqlite3_create_function_v2().
4045**
4046** ^It is permitted to register multiple implementations of the same
4047** functions with the same name but with either differing numbers of
4048** arguments or differing preferred text encodings.  ^SQLite will use
4049** the implementation that most closely matches the way in which the
4050** SQL function is used.  ^A function implementation with a non-negative
4051** nArg parameter is a better match than a function implementation with
4052** a negative nArg.  ^A function where the preferred text encoding
4053** matches the database encoding is a better
4054** match than a function where the encoding is different.
4055** ^A function where the encoding difference is between UTF16le and UTF16be
4056** is a closer match than a function where the encoding difference is
4057** between UTF8 and UTF16.
4058**
4059** ^Built-in functions may be overloaded by new application-defined functions.
4060**
4061** ^An application-defined function is permitted to call other
4062** SQLite interfaces.  However, such calls must not
4063** close the database connection nor finalize or reset the prepared
4064** statement in which the function is running.
4065*/
4066SQLITE_API int sqlite3_create_function(
4067  sqlite3 *db,
4068  const char *zFunctionName,
4069  int nArg,
4070  int eTextRep,
4071  void *pApp,
4072  void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
4073  void (*xStep)(sqlite3_context*,int,sqlite3_value**),
4074  void (*xFinal)(sqlite3_context*)
4075);
4076SQLITE_API int sqlite3_create_function16(
4077  sqlite3 *db,
4078  const void *zFunctionName,
4079  int nArg,
4080  int eTextRep,
4081  void *pApp,
4082  void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
4083  void (*xStep)(sqlite3_context*,int,sqlite3_value**),
4084  void (*xFinal)(sqlite3_context*)
4085);
4086SQLITE_API int sqlite3_create_function_v2(
4087  sqlite3 *db,
4088  const char *zFunctionName,
4089  int nArg,
4090  int eTextRep,
4091  void *pApp,
4092  void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
4093  void (*xStep)(sqlite3_context*,int,sqlite3_value**),
4094  void (*xFinal)(sqlite3_context*),
4095  void(*xDestroy)(void*)
4096);
4097
4098/*
4099** CAPI3REF: Text Encodings
4100**
4101** These constant define integer codes that represent the various
4102** text encodings supported by SQLite.
4103*/
4104#define SQLITE_UTF8           1
4105#define SQLITE_UTF16LE        2
4106#define SQLITE_UTF16BE        3
4107#define SQLITE_UTF16          4    /* Use native byte order */
4108#define SQLITE_ANY            5    /* sqlite3_create_function only */
4109#define SQLITE_UTF16_ALIGNED  8    /* sqlite3_create_collation only */
4110
4111/*
4112** CAPI3REF: Deprecated Functions
4113** DEPRECATED
4114**
4115** These functions are [deprecated].  In order to maintain
4116** backwards compatibility with older code, these functions continue
4117** to be supported.  However, new applications should avoid
4118** the use of these functions.  To help encourage people to avoid
4119** using these functions, we are not going to tell you what they do.
4120*/
4121#ifndef SQLITE_OMIT_DEPRECATED
4122SQLITE_API SQLITE_DEPRECATED int sqlite3_aggregate_count(sqlite3_context*);
4123SQLITE_API SQLITE_DEPRECATED int sqlite3_expired(sqlite3_stmt*);
4124SQLITE_API SQLITE_DEPRECATED int sqlite3_transfer_bindings(sqlite3_stmt*, sqlite3_stmt*);
4125SQLITE_API SQLITE_DEPRECATED int sqlite3_global_recover(void);
4126SQLITE_API SQLITE_DEPRECATED void sqlite3_thread_cleanup(void);
4127SQLITE_API SQLITE_DEPRECATED int sqlite3_memory_alarm(void(*)(void*,sqlite3_int64,int),void*,sqlite3_int64);
4128#endif
4129
4130/*
4131** CAPI3REF: Obtaining SQL Function Parameter Values
4132**
4133** The C-language implementation of SQL functions and aggregates uses
4134** this set of interface routines to access the parameter values on
4135** the function or aggregate.
4136**
4137** The xFunc (for scalar functions) or xStep (for aggregates) parameters
4138** to [sqlite3_create_function()] and [sqlite3_create_function16()]
4139** define callbacks that implement the SQL functions and aggregates.
4140** The 3rd parameter to these callbacks is an array of pointers to
4141** [protected sqlite3_value] objects.  There is one [sqlite3_value] object for
4142** each parameter to the SQL function.  These routines are used to
4143** extract values from the [sqlite3_value] objects.
4144**
4145** These routines work only with [protected sqlite3_value] objects.
4146** Any attempt to use these routines on an [unprotected sqlite3_value]
4147** object results in undefined behavior.
4148**
4149** ^These routines work just like the corresponding [column access functions]
4150** except that  these routines take a single [protected sqlite3_value] object
4151** pointer instead of a [sqlite3_stmt*] pointer and an integer column number.
4152**
4153** ^The sqlite3_value_text16() interface extracts a UTF-16 string
4154** in the native byte-order of the host machine.  ^The
4155** sqlite3_value_text16be() and sqlite3_value_text16le() interfaces
4156** extract UTF-16 strings as big-endian and little-endian respectively.
4157**
4158** ^(The sqlite3_value_numeric_type() interface attempts to apply
4159** numeric affinity to the value.  This means that an attempt is
4160** made to convert the value to an integer or floating point.  If
4161** such a conversion is possible without loss of information (in other
4162** words, if the value is a string that looks like a number)
4163** then the conversion is performed.  Otherwise no conversion occurs.
4164** The [SQLITE_INTEGER | datatype] after conversion is returned.)^
4165**
4166** Please pay particular attention to the fact that the pointer returned
4167** from [sqlite3_value_blob()], [sqlite3_value_text()], or
4168** [sqlite3_value_text16()] can be invalidated by a subsequent call to
4169** [sqlite3_value_bytes()], [sqlite3_value_bytes16()], [sqlite3_value_text()],
4170** or [sqlite3_value_text16()].
4171**
4172** These routines must be called from the same thread as
4173** the SQL function that supplied the [sqlite3_value*] parameters.
4174*/
4175SQLITE_API const void *sqlite3_value_blob(sqlite3_value*);
4176SQLITE_API int sqlite3_value_bytes(sqlite3_value*);
4177SQLITE_API int sqlite3_value_bytes16(sqlite3_value*);
4178SQLITE_API double sqlite3_value_double(sqlite3_value*);
4179SQLITE_API int sqlite3_value_int(sqlite3_value*);
4180SQLITE_API sqlite3_int64 sqlite3_value_int64(sqlite3_value*);
4181SQLITE_API const unsigned char *sqlite3_value_text(sqlite3_value*);
4182SQLITE_API const void *sqlite3_value_text16(sqlite3_value*);
4183SQLITE_API const void *sqlite3_value_text16le(sqlite3_value*);
4184SQLITE_API const void *sqlite3_value_text16be(sqlite3_value*);
4185SQLITE_API int sqlite3_value_type(sqlite3_value*);
4186SQLITE_API int sqlite3_value_numeric_type(sqlite3_value*);
4187
4188/*
4189** CAPI3REF: Obtain Aggregate Function Context
4190**
4191** Implementations of aggregate SQL functions use this
4192** routine to allocate memory for storing their state.
4193**
4194** ^The first time the sqlite3_aggregate_context(C,N) routine is called
4195** for a particular aggregate function, SQLite
4196** allocates N of memory, zeroes out that memory, and returns a pointer
4197** to the new memory. ^On second and subsequent calls to
4198** sqlite3_aggregate_context() for the same aggregate function instance,
4199** the same buffer is returned.  Sqlite3_aggregate_context() is normally
4200** called once for each invocation of the xStep callback and then one
4201** last time when the xFinal callback is invoked.  ^(When no rows match
4202** an aggregate query, the xStep() callback of the aggregate function
4203** implementation is never called and xFinal() is called exactly once.
4204** In those cases, sqlite3_aggregate_context() might be called for the
4205** first time from within xFinal().)^
4206**
4207** ^The sqlite3_aggregate_context(C,N) routine returns a NULL pointer if N is
4208** less than or equal to zero or if a memory allocate error occurs.
4209**
4210** ^(The amount of space allocated by sqlite3_aggregate_context(C,N) is
4211** determined by the N parameter on first successful call.  Changing the
4212** value of N in subsequent call to sqlite3_aggregate_context() within
4213** the same aggregate function instance will not resize the memory
4214** allocation.)^
4215**
4216** ^SQLite automatically frees the memory allocated by
4217** sqlite3_aggregate_context() when the aggregate query concludes.
4218**
4219** The first parameter must be a copy of the
4220** [sqlite3_context | SQL function context] that is the first parameter
4221** to the xStep or xFinal callback routine that implements the aggregate
4222** function.
4223**
4224** This routine must be called from the same thread in which
4225** the aggregate SQL function is running.
4226*/
4227SQLITE_API void *sqlite3_aggregate_context(sqlite3_context*, int nBytes);
4228
4229/*
4230** CAPI3REF: User Data For Functions
4231**
4232** ^The sqlite3_user_data() interface returns a copy of
4233** the pointer that was the pUserData parameter (the 5th parameter)
4234** of the [sqlite3_create_function()]
4235** and [sqlite3_create_function16()] routines that originally
4236** registered the application defined function.
4237**
4238** This routine must be called from the same thread in which
4239** the application-defined function is running.
4240*/
4241SQLITE_API void *sqlite3_user_data(sqlite3_context*);
4242
4243/*
4244** CAPI3REF: Database Connection For Functions
4245**
4246** ^The sqlite3_context_db_handle() interface returns a copy of
4247** the pointer to the [database connection] (the 1st parameter)
4248** of the [sqlite3_create_function()]
4249** and [sqlite3_create_function16()] routines that originally
4250** registered the application defined function.
4251*/
4252SQLITE_API sqlite3 *sqlite3_context_db_handle(sqlite3_context*);
4253
4254/*
4255** CAPI3REF: Function Auxiliary Data
4256**
4257** The following two functions may be used by scalar SQL functions to
4258** associate metadata with argument values. If the same value is passed to
4259** multiple invocations of the same SQL function during query execution, under
4260** some circumstances the associated metadata may be preserved. This may
4261** be used, for example, to add a regular-expression matching scalar
4262** function. The compiled version of the regular expression is stored as
4263** metadata associated with the SQL value passed as the regular expression
4264** pattern.  The compiled regular expression can be reused on multiple
4265** invocations of the same function so that the original pattern string
4266** does not need to be recompiled on each invocation.
4267**
4268** ^The sqlite3_get_auxdata() interface returns a pointer to the metadata
4269** associated by the sqlite3_set_auxdata() function with the Nth argument
4270** value to the application-defined function. ^If no metadata has been ever
4271** been set for the Nth argument of the function, or if the corresponding
4272** function parameter has changed since the meta-data was set,
4273** then sqlite3_get_auxdata() returns a NULL pointer.
4274**
4275** ^The sqlite3_set_auxdata() interface saves the metadata
4276** pointed to by its 3rd parameter as the metadata for the N-th
4277** argument of the application-defined function.  Subsequent
4278** calls to sqlite3_get_auxdata() might return this data, if it has
4279** not been destroyed.
4280** ^If it is not NULL, SQLite will invoke the destructor
4281** function given by the 4th parameter to sqlite3_set_auxdata() on
4282** the metadata when the corresponding function parameter changes
4283** or when the SQL statement completes, whichever comes first.
4284**
4285** SQLite is free to call the destructor and drop metadata on any
4286** parameter of any function at any time.  ^The only guarantee is that
4287** the destructor will be called before the metadata is dropped.
4288**
4289** ^(In practice, metadata is preserved between function calls for
4290** expressions that are constant at compile time. This includes literal
4291** values and [parameters].)^
4292**
4293** These routines must be called from the same thread in which
4294** the SQL function is running.
4295*/
4296SQLITE_API void *sqlite3_get_auxdata(sqlite3_context*, int N);
4297SQLITE_API void sqlite3_set_auxdata(sqlite3_context*, int N, void*, void (*)(void*));
4298
4299
4300/*
4301** CAPI3REF: Constants Defining Special Destructor Behavior
4302**
4303** These are special values for the destructor that is passed in as the
4304** final argument to routines like [sqlite3_result_blob()].  ^If the destructor
4305** argument is SQLITE_STATIC, it means that the content pointer is constant
4306** and will never change.  It does not need to be destroyed.  ^The
4307** SQLITE_TRANSIENT value means that the content will likely change in
4308** the near future and that SQLite should make its own private copy of
4309** the content before returning.
4310**
4311** The typedef is necessary to work around problems in certain
4312** C++ compilers.  See ticket #2191.
4313*/
4314typedef void (*sqlite3_destructor_type)(void*);
4315#define SQLITE_STATIC      ((sqlite3_destructor_type)0)
4316#define SQLITE_TRANSIENT   ((sqlite3_destructor_type)-1)
4317
4318/*
4319** CAPI3REF: Setting The Result Of An SQL Function
4320**
4321** These routines are used by the xFunc or xFinal callbacks that
4322** implement SQL functions and aggregates.  See
4323** [sqlite3_create_function()] and [sqlite3_create_function16()]
4324** for additional information.
4325**
4326** These functions work very much like the [parameter binding] family of
4327** functions used to bind values to host parameters in prepared statements.
4328** Refer to the [SQL parameter] documentation for additional information.
4329**
4330** ^The sqlite3_result_blob() interface sets the result from
4331** an application-defined function to be the BLOB whose content is pointed
4332** to by the second parameter and which is N bytes long where N is the
4333** third parameter.
4334**
4335** ^The sqlite3_result_zeroblob() interfaces set the result of
4336** the application-defined function to be a BLOB containing all zero
4337** bytes and N bytes in size, where N is the value of the 2nd parameter.
4338**
4339** ^The sqlite3_result_double() interface sets the result from
4340** an application-defined function to be a floating point value specified
4341** by its 2nd argument.
4342**
4343** ^The sqlite3_result_error() and sqlite3_result_error16() functions
4344** cause the implemented SQL function to throw an exception.
4345** ^SQLite uses the string pointed to by the
4346** 2nd parameter of sqlite3_result_error() or sqlite3_result_error16()
4347** as the text of an error message.  ^SQLite interprets the error
4348** message string from sqlite3_result_error() as UTF-8. ^SQLite
4349** interprets the string from sqlite3_result_error16() as UTF-16 in native
4350** byte order.  ^If the third parameter to sqlite3_result_error()
4351** or sqlite3_result_error16() is negative then SQLite takes as the error
4352** message all text up through the first zero character.
4353** ^If the third parameter to sqlite3_result_error() or
4354** sqlite3_result_error16() is non-negative then SQLite takes that many
4355** bytes (not characters) from the 2nd parameter as the error message.
4356** ^The sqlite3_result_error() and sqlite3_result_error16()
4357** routines make a private copy of the error message text before
4358** they return.  Hence, the calling function can deallocate or
4359** modify the text after they return without harm.
4360** ^The sqlite3_result_error_code() function changes the error code
4361** returned by SQLite as a result of an error in a function.  ^By default,
4362** the error code is SQLITE_ERROR.  ^A subsequent call to sqlite3_result_error()
4363** or sqlite3_result_error16() resets the error code to SQLITE_ERROR.
4364**
4365** ^The sqlite3_result_toobig() interface causes SQLite to throw an error
4366** indicating that a string or BLOB is too long to represent.
4367**
4368** ^The sqlite3_result_nomem() interface causes SQLite to throw an error
4369** indicating that a memory allocation failed.
4370**
4371** ^The sqlite3_result_int() interface sets the return value
4372** of the application-defined function to be the 32-bit signed integer
4373** value given in the 2nd argument.
4374** ^The sqlite3_result_int64() interface sets the return value
4375** of the application-defined function to be the 64-bit signed integer
4376** value given in the 2nd argument.
4377**
4378** ^The sqlite3_result_null() interface sets the return value
4379** of the application-defined function to be NULL.
4380**
4381** ^The sqlite3_result_text(), sqlite3_result_text16(),
4382** sqlite3_result_text16le(), and sqlite3_result_text16be() interfaces
4383** set the return value of the application-defined function to be
4384** a text string which is represented as UTF-8, UTF-16 native byte order,
4385** UTF-16 little endian, or UTF-16 big endian, respectively.
4386** ^SQLite takes the text result from the application from
4387** the 2nd parameter of the sqlite3_result_text* interfaces.
4388** ^If the 3rd parameter to the sqlite3_result_text* interfaces
4389** is negative, then SQLite takes result text from the 2nd parameter
4390** through the first zero character.
4391** ^If the 3rd parameter to the sqlite3_result_text* interfaces
4392** is non-negative, then as many bytes (not characters) of the text
4393** pointed to by the 2nd parameter are taken as the application-defined
4394** function result.
4395** ^If the 4th parameter to the sqlite3_result_text* interfaces
4396** or sqlite3_result_blob is a non-NULL pointer, then SQLite calls that
4397** function as the destructor on the text or BLOB result when it has
4398** finished using that result.
4399** ^If the 4th parameter to the sqlite3_result_text* interfaces or to
4400** sqlite3_result_blob is the special constant SQLITE_STATIC, then SQLite
4401** assumes that the text or BLOB result is in constant space and does not
4402** copy the content of the parameter nor call a destructor on the content
4403** when it has finished using that result.
4404** ^If the 4th parameter to the sqlite3_result_text* interfaces
4405** or sqlite3_result_blob is the special constant SQLITE_TRANSIENT
4406** then SQLite makes a copy of the result into space obtained from
4407** from [sqlite3_malloc()] before it returns.
4408**
4409** ^The sqlite3_result_value() interface sets the result of
4410** the application-defined function to be a copy the
4411** [unprotected sqlite3_value] object specified by the 2nd parameter.  ^The
4412** sqlite3_result_value() interface makes a copy of the [sqlite3_value]
4413** so that the [sqlite3_value] specified in the parameter may change or
4414** be deallocated after sqlite3_result_value() returns without harm.
4415** ^A [protected sqlite3_value] object may always be used where an
4416** [unprotected sqlite3_value] object is required, so either
4417** kind of [sqlite3_value] object can be used with this interface.
4418**
4419** If these routines are called from within the different thread
4420** than the one containing the application-defined function that received
4421** the [sqlite3_context] pointer, the results are undefined.
4422*/
4423SQLITE_API void sqlite3_result_blob(sqlite3_context*, const void*, int, void(*)(void*));
4424SQLITE_API void sqlite3_result_double(sqlite3_context*, double);
4425SQLITE_API void sqlite3_result_error(sqlite3_context*, const char*, int);
4426SQLITE_API void sqlite3_result_error16(sqlite3_context*, const void*, int);
4427SQLITE_API void sqlite3_result_error_toobig(sqlite3_context*);
4428SQLITE_API void sqlite3_result_error_nomem(sqlite3_context*);
4429SQLITE_API void sqlite3_result_error_code(sqlite3_context*, int);
4430SQLITE_API void sqlite3_result_int(sqlite3_context*, int);
4431SQLITE_API void sqlite3_result_int64(sqlite3_context*, sqlite3_int64);
4432SQLITE_API void sqlite3_result_null(sqlite3_context*);
4433SQLITE_API void sqlite3_result_text(sqlite3_context*, const char*, int, void(*)(void*));
4434SQLITE_API void sqlite3_result_text16(sqlite3_context*, const void*, int, void(*)(void*));
4435SQLITE_API void sqlite3_result_text16le(sqlite3_context*, const void*, int,void(*)(void*));
4436SQLITE_API void sqlite3_result_text16be(sqlite3_context*, const void*, int,void(*)(void*));
4437SQLITE_API void sqlite3_result_value(sqlite3_context*, sqlite3_value*);
4438SQLITE_API void sqlite3_result_zeroblob(sqlite3_context*, int n);
4439
4440/*
4441** CAPI3REF: Define New Collating Sequences
4442**
4443** ^These functions add, remove, or modify a [collation] associated
4444** with the [database connection] specified as the first argument.
4445**
4446** ^The name of the collation is a UTF-8 string
4447** for sqlite3_create_collation() and sqlite3_create_collation_v2()
4448** and a UTF-16 string in native byte order for sqlite3_create_collation16().
4449** ^Collation names that compare equal according to [sqlite3_strnicmp()] are
4450** considered to be the same name.
4451**
4452** ^(The third argument (eTextRep) must be one of the constants:
4453** <ul>
4454** <li> [SQLITE_UTF8],
4455** <li> [SQLITE_UTF16LE],
4456** <li> [SQLITE_UTF16BE],
4457** <li> [SQLITE_UTF16], or
4458** <li> [SQLITE_UTF16_ALIGNED].
4459** </ul>)^
4460** ^The eTextRep argument determines the encoding of strings passed
4461** to the collating function callback, xCallback.
4462** ^The [SQLITE_UTF16] and [SQLITE_UTF16_ALIGNED] values for eTextRep
4463** force strings to be UTF16 with native byte order.
4464** ^The [SQLITE_UTF16_ALIGNED] value for eTextRep forces strings to begin
4465** on an even byte address.
4466**
4467** ^The fourth argument, pArg, is an application data pointer that is passed
4468** through as the first argument to the collating function callback.
4469**
4470** ^The fifth argument, xCallback, is a pointer to the collating function.
4471** ^Multiple collating functions can be registered using the same name but
4472** with different eTextRep parameters and SQLite will use whichever
4473** function requires the least amount of data transformation.
4474** ^If the xCallback argument is NULL then the collating function is
4475** deleted.  ^When all collating functions having the same name are deleted,
4476** that collation is no longer usable.
4477**
4478** ^The collating function callback is invoked with a copy of the pArg
4479** application data pointer and with two strings in the encoding specified
4480** by the eTextRep argument.  The collating function must return an
4481** integer that is negative, zero, or positive
4482** if the first string is less than, equal to, or greater than the second,
4483** respectively.  A collating function must always return the same answer
4484** given the same inputs.  If two or more collating functions are registered
4485** to the same collation name (using different eTextRep values) then all
4486** must give an equivalent answer when invoked with equivalent strings.
4487** The collating function must obey the following properties for all
4488** strings A, B, and C:
4489**
4490** <ol>
4491** <li> If A==B then B==A.
4492** <li> If A==B and B==C then A==C.
4493** <li> If A&lt;B THEN B&gt;A.
4494** <li> If A&lt;B and B&lt;C then A&lt;C.
4495** </ol>
4496**
4497** If a collating function fails any of the above constraints and that
4498** collating function is  registered and used, then the behavior of SQLite
4499** is undefined.
4500**
4501** ^The sqlite3_create_collation_v2() works like sqlite3_create_collation()
4502** with the addition that the xDestroy callback is invoked on pArg when
4503** the collating function is deleted.
4504** ^Collating functions are deleted when they are overridden by later
4505** calls to the collation creation functions or when the
4506** [database connection] is closed using [sqlite3_close()].
4507**
4508** ^The xDestroy callback is <u>not</u> called if the
4509** sqlite3_create_collation_v2() function fails.  Applications that invoke
4510** sqlite3_create_collation_v2() with a non-NULL xDestroy argument should
4511** check the return code and dispose of the application data pointer
4512** themselves rather than expecting SQLite to deal with it for them.
4513** This is different from every other SQLite interface.  The inconsistency
4514** is unfortunate but cannot be changed without breaking backwards
4515** compatibility.
4516**
4517** See also:  [sqlite3_collation_needed()] and [sqlite3_collation_needed16()].
4518*/
4519SQLITE_API int sqlite3_create_collation(
4520  sqlite3*,
4521  const char *zName,
4522  int eTextRep,
4523  void *pArg,
4524  int(*xCompare)(void*,int,const void*,int,const void*)
4525);
4526SQLITE_API int sqlite3_create_collation_v2(
4527  sqlite3*,
4528  const char *zName,
4529  int eTextRep,
4530  void *pArg,
4531  int(*xCompare)(void*,int,const void*,int,const void*),
4532  void(*xDestroy)(void*)
4533);
4534SQLITE_API int sqlite3_create_collation16(
4535  sqlite3*,
4536  const void *zName,
4537  int eTextRep,
4538  void *pArg,
4539  int(*xCompare)(void*,int,const void*,int,const void*)
4540);
4541
4542/*
4543** CAPI3REF: Collation Needed Callbacks
4544**
4545** ^To avoid having to register all collation sequences before a database
4546** can be used, a single callback function may be registered with the
4547** [database connection] to be invoked whenever an undefined collation
4548** sequence is required.
4549**
4550** ^If the function is registered using the sqlite3_collation_needed() API,
4551** then it is passed the names of undefined collation sequences as strings
4552** encoded in UTF-8. ^If sqlite3_collation_needed16() is used,
4553** the names are passed as UTF-16 in machine native byte order.
4554** ^A call to either function replaces the existing collation-needed callback.
4555**
4556** ^(When the callback is invoked, the first argument passed is a copy
4557** of the second argument to sqlite3_collation_needed() or
4558** sqlite3_collation_needed16().  The second argument is the database
4559** connection.  The third argument is one of [SQLITE_UTF8], [SQLITE_UTF16BE],
4560** or [SQLITE_UTF16LE], indicating the most desirable form of the collation
4561** sequence function required.  The fourth parameter is the name of the
4562** required collation sequence.)^
4563**
4564** The callback function should register the desired collation using
4565** [sqlite3_create_collation()], [sqlite3_create_collation16()], or
4566** [sqlite3_create_collation_v2()].
4567*/
4568SQLITE_API int sqlite3_collation_needed(
4569  sqlite3*,
4570  void*,
4571  void(*)(void*,sqlite3*,int eTextRep,const char*)
4572);
4573SQLITE_API int sqlite3_collation_needed16(
4574  sqlite3*,
4575  void*,
4576  void(*)(void*,sqlite3*,int eTextRep,const void*)
4577);
4578
4579#ifdef SQLITE_HAS_CODEC
4580/*
4581** Specify the key for an encrypted database.  This routine should be
4582** called right after sqlite3_open().
4583**
4584** The code to implement this API is not available in the public release
4585** of SQLite.
4586*/
4587SQLITE_API int sqlite3_key(
4588  sqlite3 *db,                   /* Database to be rekeyed */
4589  const void *pKey, int nKey     /* The key */
4590);
4591
4592/*
4593** Change the key on an open database.  If the current database is not
4594** encrypted, this routine will encrypt it.  If pNew==0 or nNew==0, the
4595** database is decrypted.
4596**
4597** The code to implement this API is not available in the public release
4598** of SQLite.
4599*/
4600SQLITE_API int sqlite3_rekey(
4601  sqlite3 *db,                   /* Database to be rekeyed */
4602  const void *pKey, int nKey     /* The new key */
4603);
4604
4605/*
4606** Specify the activation key for a SEE database.  Unless
4607** activated, none of the SEE routines will work.
4608*/
4609SQLITE_API void sqlite3_activate_see(
4610  const char *zPassPhrase        /* Activation phrase */
4611);
4612#endif
4613
4614#ifdef SQLITE_ENABLE_CEROD
4615/*
4616** Specify the activation key for a CEROD database.  Unless
4617** activated, none of the CEROD routines will work.
4618*/
4619SQLITE_API void sqlite3_activate_cerod(
4620  const char *zPassPhrase        /* Activation phrase */
4621);
4622#endif
4623
4624/*
4625** CAPI3REF: Suspend Execution For A Short Time
4626**
4627** The sqlite3_sleep() function causes the current thread to suspend execution
4628** for at least a number of milliseconds specified in its parameter.
4629**
4630** If the operating system does not support sleep requests with
4631** millisecond time resolution, then the time will be rounded up to
4632** the nearest second. The number of milliseconds of sleep actually
4633** requested from the operating system is returned.
4634**
4635** ^SQLite implements this interface by calling the xSleep()
4636** method of the default [sqlite3_vfs] object.  If the xSleep() method
4637** of the default VFS is not implemented correctly, or not implemented at
4638** all, then the behavior of sqlite3_sleep() may deviate from the description
4639** in the previous paragraphs.
4640*/
4641SQLITE_API int sqlite3_sleep(int);
4642
4643/*
4644** CAPI3REF: Name Of The Folder Holding Temporary Files
4645**
4646** ^(If this global variable is made to point to a string which is
4647** the name of a folder (a.k.a. directory), then all temporary files
4648** created by SQLite when using a built-in [sqlite3_vfs | VFS]
4649** will be placed in that directory.)^  ^If this variable
4650** is a NULL pointer, then SQLite performs a search for an appropriate
4651** temporary file directory.
4652**
4653** It is not safe to read or modify this variable in more than one
4654** thread at a time.  It is not safe to read or modify this variable
4655** if a [database connection] is being used at the same time in a separate
4656** thread.
4657** It is intended that this variable be set once
4658** as part of process initialization and before any SQLite interface
4659** routines have been called and that this variable remain unchanged
4660** thereafter.
4661**
4662** ^The [temp_store_directory pragma] may modify this variable and cause
4663** it to point to memory obtained from [sqlite3_malloc].  ^Furthermore,
4664** the [temp_store_directory pragma] always assumes that any string
4665** that this variable points to is held in memory obtained from
4666** [sqlite3_malloc] and the pragma may attempt to free that memory
4667** using [sqlite3_free].
4668** Hence, if this variable is modified directly, either it should be
4669** made NULL or made to point to memory obtained from [sqlite3_malloc]
4670** or else the use of the [temp_store_directory pragma] should be avoided.
4671*/
4672SQLITE_API char *sqlite3_temp_directory;
4673
4674/*
4675** CAPI3REF: Test For Auto-Commit Mode
4676** KEYWORDS: {autocommit mode}
4677**
4678** ^The sqlite3_get_autocommit() interface returns non-zero or
4679** zero if the given database connection is or is not in autocommit mode,
4680** respectively.  ^Autocommit mode is on by default.
4681** ^Autocommit mode is disabled by a [BEGIN] statement.
4682** ^Autocommit mode is re-enabled by a [COMMIT] or [ROLLBACK].
4683**
4684** If certain kinds of errors occur on a statement within a multi-statement
4685** transaction (errors including [SQLITE_FULL], [SQLITE_IOERR],
4686** [SQLITE_NOMEM], [SQLITE_BUSY], and [SQLITE_INTERRUPT]) then the
4687** transaction might be rolled back automatically.  The only way to
4688** find out whether SQLite automatically rolled back the transaction after
4689** an error is to use this function.
4690**
4691** If another thread changes the autocommit status of the database
4692** connection while this routine is running, then the return value
4693** is undefined.
4694*/
4695SQLITE_API int sqlite3_get_autocommit(sqlite3*);
4696
4697/*
4698** CAPI3REF: Find The Database Handle Of A Prepared Statement
4699**
4700** ^The sqlite3_db_handle interface returns the [database connection] handle
4701** to which a [prepared statement] belongs.  ^The [database connection]
4702** returned by sqlite3_db_handle is the same [database connection]
4703** that was the first argument
4704** to the [sqlite3_prepare_v2()] call (or its variants) that was used to
4705** create the statement in the first place.
4706*/
4707SQLITE_API sqlite3 *sqlite3_db_handle(sqlite3_stmt*);
4708
4709/*
4710** CAPI3REF: Find the next prepared statement
4711**
4712** ^This interface returns a pointer to the next [prepared statement] after
4713** pStmt associated with the [database connection] pDb.  ^If pStmt is NULL
4714** then this interface returns a pointer to the first prepared statement
4715** associated with the database connection pDb.  ^If no prepared statement
4716** satisfies the conditions of this routine, it returns NULL.
4717**
4718** The [database connection] pointer D in a call to
4719** [sqlite3_next_stmt(D,S)] must refer to an open database
4720** connection and in particular must not be a NULL pointer.
4721*/
4722SQLITE_API sqlite3_stmt *sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt);
4723
4724/*
4725** CAPI3REF: Commit And Rollback Notification Callbacks
4726**
4727** ^The sqlite3_commit_hook() interface registers a callback
4728** function to be invoked whenever a transaction is [COMMIT | committed].
4729** ^Any callback set by a previous call to sqlite3_commit_hook()
4730** for the same database connection is overridden.
4731** ^The sqlite3_rollback_hook() interface registers a callback
4732** function to be invoked whenever a transaction is [ROLLBACK | rolled back].
4733** ^Any callback set by a previous call to sqlite3_rollback_hook()
4734** for the same database connection is overridden.
4735** ^The pArg argument is passed through to the callback.
4736** ^If the callback on a commit hook function returns non-zero,
4737** then the commit is converted into a rollback.
4738**
4739** ^The sqlite3_commit_hook(D,C,P) and sqlite3_rollback_hook(D,C,P) functions
4740** return the P argument from the previous call of the same function
4741** on the same [database connection] D, or NULL for
4742** the first call for each function on D.
4743**
4744** The callback implementation must not do anything that will modify
4745** the database connection that invoked the callback.  Any actions
4746** to modify the database connection must be deferred until after the
4747** completion of the [sqlite3_step()] call that triggered the commit
4748** or rollback hook in the first place.
4749** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
4750** database connections for the meaning of "modify" in this paragraph.
4751**
4752** ^Registering a NULL function disables the callback.
4753**
4754** ^When the commit hook callback routine returns zero, the [COMMIT]
4755** operation is allowed to continue normally.  ^If the commit hook
4756** returns non-zero, then the [COMMIT] is converted into a [ROLLBACK].
4757** ^The rollback hook is invoked on a rollback that results from a commit
4758** hook returning non-zero, just as it would be with any other rollback.
4759**
4760** ^For the purposes of this API, a transaction is said to have been
4761** rolled back if an explicit "ROLLBACK" statement is executed, or
4762** an error or constraint causes an implicit rollback to occur.
4763** ^The rollback callback is not invoked if a transaction is
4764** automatically rolled back because the database connection is closed.
4765**
4766** See also the [sqlite3_update_hook()] interface.
4767*/
4768SQLITE_API void *sqlite3_commit_hook(sqlite3*, int(*)(void*), void*);
4769SQLITE_API void *sqlite3_rollback_hook(sqlite3*, void(*)(void *), void*);
4770
4771/*
4772** CAPI3REF: Data Change Notification Callbacks
4773**
4774** ^The sqlite3_update_hook() interface registers a callback function
4775** with the [database connection] identified by the first argument
4776** to be invoked whenever a row is updated, inserted or deleted.
4777** ^Any callback set by a previous call to this function
4778** for the same database connection is overridden.
4779**
4780** ^The second argument is a pointer to the function to invoke when a
4781** row is updated, inserted or deleted.
4782** ^The first argument to the callback is a copy of the third argument
4783** to sqlite3_update_hook().
4784** ^The second callback argument is one of [SQLITE_INSERT], [SQLITE_DELETE],
4785** or [SQLITE_UPDATE], depending on the operation that caused the callback
4786** to be invoked.
4787** ^The third and fourth arguments to the callback contain pointers to the
4788** database and table name containing the affected row.
4789** ^The final callback parameter is the [rowid] of the row.
4790** ^In the case of an update, this is the [rowid] after the update takes place.
4791**
4792** ^(The update hook is not invoked when internal system tables are
4793** modified (i.e. sqlite_master and sqlite_sequence).)^
4794**
4795** ^In the current implementation, the update hook
4796** is not invoked when duplication rows are deleted because of an
4797** [ON CONFLICT | ON CONFLICT REPLACE] clause.  ^Nor is the update hook
4798** invoked when rows are deleted using the [truncate optimization].
4799** The exceptions defined in this paragraph might change in a future
4800** release of SQLite.
4801**
4802** The update hook implementation must not do anything that will modify
4803** the database connection that invoked the update hook.  Any actions
4804** to modify the database connection must be deferred until after the
4805** completion of the [sqlite3_step()] call that triggered the update hook.
4806** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
4807** database connections for the meaning of "modify" in this paragraph.
4808**
4809** ^The sqlite3_update_hook(D,C,P) function
4810** returns the P argument from the previous call
4811** on the same [database connection] D, or NULL for
4812** the first call on D.
4813**
4814** See also the [sqlite3_commit_hook()] and [sqlite3_rollback_hook()]
4815** interfaces.
4816*/
4817SQLITE_API void *sqlite3_update_hook(
4818  sqlite3*,
4819  void(*)(void *,int ,char const *,char const *,sqlite3_int64),
4820  void*
4821);
4822
4823/*
4824** CAPI3REF: Enable Or Disable Shared Pager Cache
4825** KEYWORDS: {shared cache}
4826**
4827** ^(This routine enables or disables the sharing of the database cache
4828** and schema data structures between [database connection | connections]
4829** to the same database. Sharing is enabled if the argument is true
4830** and disabled if the argument is false.)^
4831**
4832** ^Cache sharing is enabled and disabled for an entire process.
4833** This is a change as of SQLite version 3.5.0. In prior versions of SQLite,
4834** sharing was enabled or disabled for each thread separately.
4835**
4836** ^(The cache sharing mode set by this interface effects all subsequent
4837** calls to [sqlite3_open()], [sqlite3_open_v2()], and [sqlite3_open16()].
4838** Existing database connections continue use the sharing mode
4839** that was in effect at the time they were opened.)^
4840**
4841** ^(This routine returns [SQLITE_OK] if shared cache was enabled or disabled
4842** successfully.  An [error code] is returned otherwise.)^
4843**
4844** ^Shared cache is disabled by default. But this might change in
4845** future releases of SQLite.  Applications that care about shared
4846** cache setting should set it explicitly.
4847**
4848** See Also:  [SQLite Shared-Cache Mode]
4849*/
4850SQLITE_API int sqlite3_enable_shared_cache(int);
4851
4852/*
4853** CAPI3REF: Attempt To Free Heap Memory
4854**
4855** ^The sqlite3_release_memory() interface attempts to free N bytes
4856** of heap memory by deallocating non-essential memory allocations
4857** held by the database library.   Memory used to cache database
4858** pages to improve performance is an example of non-essential memory.
4859** ^sqlite3_release_memory() returns the number of bytes actually freed,
4860** which might be more or less than the amount requested.
4861** ^The sqlite3_release_memory() routine is a no-op returning zero
4862** if SQLite is not compiled with [SQLITE_ENABLE_MEMORY_MANAGEMENT].
4863*/
4864SQLITE_API int sqlite3_release_memory(int);
4865
4866/*
4867** CAPI3REF: Impose A Limit On Heap Size
4868**
4869** ^The sqlite3_soft_heap_limit64() interface sets and/or queries the
4870** soft limit on the amount of heap memory that may be allocated by SQLite.
4871** ^SQLite strives to keep heap memory utilization below the soft heap
4872** limit by reducing the number of pages held in the page cache
4873** as heap memory usages approaches the limit.
4874** ^The soft heap limit is "soft" because even though SQLite strives to stay
4875** below the limit, it will exceed the limit rather than generate
4876** an [SQLITE_NOMEM] error.  In other words, the soft heap limit
4877** is advisory only.
4878**
4879** ^The return value from sqlite3_soft_heap_limit64() is the size of
4880** the soft heap limit prior to the call.  ^If the argument N is negative
4881** then no change is made to the soft heap limit.  Hence, the current
4882** size of the soft heap limit can be determined by invoking
4883** sqlite3_soft_heap_limit64() with a negative argument.
4884**
4885** ^If the argument N is zero then the soft heap limit is disabled.
4886**
4887** ^(The soft heap limit is not enforced in the current implementation
4888** if one or more of following conditions are true:
4889**
4890** <ul>
4891** <li> The soft heap limit is set to zero.
4892** <li> Memory accounting is disabled using a combination of the
4893**      [sqlite3_config]([SQLITE_CONFIG_MEMSTATUS],...) start-time option and
4894**      the [SQLITE_DEFAULT_MEMSTATUS] compile-time option.
4895** <li> An alternative page cache implementation is specified using
4896**      [sqlite3_config]([SQLITE_CONFIG_PCACHE],...).
4897** <li> The page cache allocates from its own memory pool supplied
4898**      by [sqlite3_config]([SQLITE_CONFIG_PAGECACHE],...) rather than
4899**      from the heap.
4900** </ul>)^
4901**
4902** Beginning with SQLite version 3.7.3, the soft heap limit is enforced
4903** regardless of whether or not the [SQLITE_ENABLE_MEMORY_MANAGEMENT]
4904** compile-time option is invoked.  With [SQLITE_ENABLE_MEMORY_MANAGEMENT],
4905** the soft heap limit is enforced on every memory allocation.  Without
4906** [SQLITE_ENABLE_MEMORY_MANAGEMENT], the soft heap limit is only enforced
4907** when memory is allocated by the page cache.  Testing suggests that because
4908** the page cache is the predominate memory user in SQLite, most
4909** applications will achieve adequate soft heap limit enforcement without
4910** the use of [SQLITE_ENABLE_MEMORY_MANAGEMENT].
4911**
4912** The circumstances under which SQLite will enforce the soft heap limit may
4913** changes in future releases of SQLite.
4914*/
4915SQLITE_API sqlite3_int64 sqlite3_soft_heap_limit64(sqlite3_int64 N);
4916
4917/*
4918** CAPI3REF: Deprecated Soft Heap Limit Interface
4919** DEPRECATED
4920**
4921** This is a deprecated version of the [sqlite3_soft_heap_limit64()]
4922** interface.  This routine is provided for historical compatibility
4923** only.  All new applications should use the
4924** [sqlite3_soft_heap_limit64()] interface rather than this one.
4925*/
4926SQLITE_API SQLITE_DEPRECATED void sqlite3_soft_heap_limit(int N);
4927
4928
4929/*
4930** CAPI3REF: Extract Metadata About A Column Of A Table
4931**
4932** ^This routine returns metadata about a specific column of a specific
4933** database table accessible using the [database connection] handle
4934** passed as the first function argument.
4935**
4936** ^The column is identified by the second, third and fourth parameters to
4937** this function. ^The second parameter is either the name of the database
4938** (i.e. "main", "temp", or an attached database) containing the specified
4939** table or NULL. ^If it is NULL, then all attached databases are searched
4940** for the table using the same algorithm used by the database engine to
4941** resolve unqualified table references.
4942**
4943** ^The third and fourth parameters to this function are the table and column
4944** name of the desired column, respectively. Neither of these parameters
4945** may be NULL.
4946**
4947** ^Metadata is returned by writing to the memory locations passed as the 5th
4948** and subsequent parameters to this function. ^Any of these arguments may be
4949** NULL, in which case the corresponding element of metadata is omitted.
4950**
4951** ^(<blockquote>
4952** <table border="1">
4953** <tr><th> Parameter <th> Output<br>Type <th>  Description
4954**
4955** <tr><td> 5th <td> const char* <td> Data type
4956** <tr><td> 6th <td> const char* <td> Name of default collation sequence
4957** <tr><td> 7th <td> int         <td> True if column has a NOT NULL constraint
4958** <tr><td> 8th <td> int         <td> True if column is part of the PRIMARY KEY
4959** <tr><td> 9th <td> int         <td> True if column is [AUTOINCREMENT]
4960** </table>
4961** </blockquote>)^
4962**
4963** ^The memory pointed to by the character pointers returned for the
4964** declaration type and collation sequence is valid only until the next
4965** call to any SQLite API function.
4966**
4967** ^If the specified table is actually a view, an [error code] is returned.
4968**
4969** ^If the specified column is "rowid", "oid" or "_rowid_" and an
4970** [INTEGER PRIMARY KEY] column has been explicitly declared, then the output
4971** parameters are set for the explicitly declared column. ^(If there is no
4972** explicitly declared [INTEGER PRIMARY KEY] column, then the output
4973** parameters are set as follows:
4974**
4975** <pre>
4976**     data type: "INTEGER"
4977**     collation sequence: "BINARY"
4978**     not null: 0
4979**     primary key: 1
4980**     auto increment: 0
4981** </pre>)^
4982**
4983** ^(This function may load one or more schemas from database files. If an
4984** error occurs during this process, or if the requested table or column
4985** cannot be found, an [error code] is returned and an error message left
4986** in the [database connection] (to be retrieved using sqlite3_errmsg()).)^
4987**
4988** ^This API is only available if the library was compiled with the
4989** [SQLITE_ENABLE_COLUMN_METADATA] C-preprocessor symbol defined.
4990*/
4991SQLITE_API int sqlite3_table_column_metadata(
4992  sqlite3 *db,                /* Connection handle */
4993  const char *zDbName,        /* Database name or NULL */
4994  const char *zTableName,     /* Table name */
4995  const char *zColumnName,    /* Column name */
4996  char const **pzDataType,    /* OUTPUT: Declared data type */
4997  char const **pzCollSeq,     /* OUTPUT: Collation sequence name */
4998  int *pNotNull,              /* OUTPUT: True if NOT NULL constraint exists */
4999  int *pPrimaryKey,           /* OUTPUT: True if column part of PK */
5000  int *pAutoinc               /* OUTPUT: True if column is auto-increment */
5001);
5002
5003/*
5004** CAPI3REF: Load An Extension
5005**
5006** ^This interface loads an SQLite extension library from the named file.
5007**
5008** ^The sqlite3_load_extension() interface attempts to load an
5009** SQLite extension library contained in the file zFile.
5010**
5011** ^The entry point is zProc.
5012** ^zProc may be 0, in which case the name of the entry point
5013** defaults to "sqlite3_extension_init".
5014** ^The sqlite3_load_extension() interface returns
5015** [SQLITE_OK] on success and [SQLITE_ERROR] if something goes wrong.
5016** ^If an error occurs and pzErrMsg is not 0, then the
5017** [sqlite3_load_extension()] interface shall attempt to
5018** fill *pzErrMsg with error message text stored in memory
5019** obtained from [sqlite3_malloc()]. The calling function
5020** should free this memory by calling [sqlite3_free()].
5021**
5022** ^Extension loading must be enabled using
5023** [sqlite3_enable_load_extension()] prior to calling this API,
5024** otherwise an error will be returned.
5025**
5026** See also the [load_extension() SQL function].
5027*/
5028SQLITE_API int sqlite3_load_extension(
5029  sqlite3 *db,          /* Load the extension into this database connection */
5030  const char *zFile,    /* Name of the shared library containing extension */
5031  const char *zProc,    /* Entry point.  Derived from zFile if 0 */
5032  char **pzErrMsg       /* Put error message here if not 0 */
5033);
5034
5035/*
5036** CAPI3REF: Enable Or Disable Extension Loading
5037**
5038** ^So as not to open security holes in older applications that are
5039** unprepared to deal with extension loading, and as a means of disabling
5040** extension loading while evaluating user-entered SQL, the following API
5041** is provided to turn the [sqlite3_load_extension()] mechanism on and off.
5042**
5043** ^Extension loading is off by default. See ticket #1863.
5044** ^Call the sqlite3_enable_load_extension() routine with onoff==1
5045** to turn extension loading on and call it with onoff==0 to turn
5046** it back off again.
5047*/
5048SQLITE_API int sqlite3_enable_load_extension(sqlite3 *db, int onoff);
5049
5050/*
5051** CAPI3REF: Automatically Load Statically Linked Extensions
5052**
5053** ^This interface causes the xEntryPoint() function to be invoked for
5054** each new [database connection] that is created.  The idea here is that
5055** xEntryPoint() is the entry point for a statically linked SQLite extension
5056** that is to be automatically loaded into all new database connections.
5057**
5058** ^(Even though the function prototype shows that xEntryPoint() takes
5059** no arguments and returns void, SQLite invokes xEntryPoint() with three
5060** arguments and expects and integer result as if the signature of the
5061** entry point where as follows:
5062**
5063** <blockquote><pre>
5064** &nbsp;  int xEntryPoint(
5065** &nbsp;    sqlite3 *db,
5066** &nbsp;    const char **pzErrMsg,
5067** &nbsp;    const struct sqlite3_api_routines *pThunk
5068** &nbsp;  );
5069** </pre></blockquote>)^
5070**
5071** If the xEntryPoint routine encounters an error, it should make *pzErrMsg
5072** point to an appropriate error message (obtained from [sqlite3_mprintf()])
5073** and return an appropriate [error code].  ^SQLite ensures that *pzErrMsg
5074** is NULL before calling the xEntryPoint().  ^SQLite will invoke
5075** [sqlite3_free()] on *pzErrMsg after xEntryPoint() returns.  ^If any
5076** xEntryPoint() returns an error, the [sqlite3_open()], [sqlite3_open16()],
5077** or [sqlite3_open_v2()] call that provoked the xEntryPoint() will fail.
5078**
5079** ^Calling sqlite3_auto_extension(X) with an entry point X that is already
5080** on the list of automatic extensions is a harmless no-op. ^No entry point
5081** will be called more than once for each database connection that is opened.
5082**
5083** See also: [sqlite3_reset_auto_extension()].
5084*/
5085SQLITE_API int sqlite3_auto_extension(void (*xEntryPoint)(void));
5086
5087/*
5088** CAPI3REF: Reset Automatic Extension Loading
5089**
5090** ^This interface disables all automatic extensions previously
5091** registered using [sqlite3_auto_extension()].
5092*/
5093SQLITE_API void sqlite3_reset_auto_extension(void);
5094
5095/*
5096** The interface to the virtual-table mechanism is currently considered
5097** to be experimental.  The interface might change in incompatible ways.
5098** If this is a problem for you, do not use the interface at this time.
5099**
5100** When the virtual-table mechanism stabilizes, we will declare the
5101** interface fixed, support it indefinitely, and remove this comment.
5102*/
5103
5104/*
5105** Structures used by the virtual table interface
5106*/
5107typedef struct sqlite3_vtab sqlite3_vtab;
5108typedef struct sqlite3_index_info sqlite3_index_info;
5109typedef struct sqlite3_vtab_cursor sqlite3_vtab_cursor;
5110typedef struct sqlite3_module sqlite3_module;
5111
5112/*
5113** CAPI3REF: Virtual Table Object
5114** KEYWORDS: sqlite3_module {virtual table module}
5115**
5116** This structure, sometimes called a "virtual table module",
5117** defines the implementation of a [virtual tables].
5118** This structure consists mostly of methods for the module.
5119**
5120** ^A virtual table module is created by filling in a persistent
5121** instance of this structure and passing a pointer to that instance
5122** to [sqlite3_create_module()] or [sqlite3_create_module_v2()].
5123** ^The registration remains valid until it is replaced by a different
5124** module or until the [database connection] closes.  The content
5125** of this structure must not change while it is registered with
5126** any database connection.
5127*/
5128struct sqlite3_module {
5129  int iVersion;
5130  int (*xCreate)(sqlite3*, void *pAux,
5131               int argc, const char *const*argv,
5132               sqlite3_vtab **ppVTab, char**);
5133  int (*xConnect)(sqlite3*, void *pAux,
5134               int argc, const char *const*argv,
5135               sqlite3_vtab **ppVTab, char**);
5136  int (*xBestIndex)(sqlite3_vtab *pVTab, sqlite3_index_info*);
5137  int (*xDisconnect)(sqlite3_vtab *pVTab);
5138  int (*xDestroy)(sqlite3_vtab *pVTab);
5139  int (*xOpen)(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor);
5140  int (*xClose)(sqlite3_vtab_cursor*);
5141  int (*xFilter)(sqlite3_vtab_cursor*, int idxNum, const char *idxStr,
5142                int argc, sqlite3_value **argv);
5143  int (*xNext)(sqlite3_vtab_cursor*);
5144  int (*xEof)(sqlite3_vtab_cursor*);
5145  int (*xColumn)(sqlite3_vtab_cursor*, sqlite3_context*, int);
5146  int (*xRowid)(sqlite3_vtab_cursor*, sqlite3_int64 *pRowid);
5147  int (*xUpdate)(sqlite3_vtab *, int, sqlite3_value **, sqlite3_int64 *);
5148  int (*xBegin)(sqlite3_vtab *pVTab);
5149  int (*xSync)(sqlite3_vtab *pVTab);
5150  int (*xCommit)(sqlite3_vtab *pVTab);
5151  int (*xRollback)(sqlite3_vtab *pVTab);
5152  int (*xFindFunction)(sqlite3_vtab *pVtab, int nArg, const char *zName,
5153                       void (**pxFunc)(sqlite3_context*,int,sqlite3_value**),
5154                       void **ppArg);
5155  int (*xRename)(sqlite3_vtab *pVtab, const char *zNew);
5156};
5157
5158/*
5159** CAPI3REF: Virtual Table Indexing Information
5160** KEYWORDS: sqlite3_index_info
5161**
5162** The sqlite3_index_info structure and its substructures is used as part
5163** of the [virtual table] interface to
5164** pass information into and receive the reply from the [xBestIndex]
5165** method of a [virtual table module].  The fields under **Inputs** are the
5166** inputs to xBestIndex and are read-only.  xBestIndex inserts its
5167** results into the **Outputs** fields.
5168**
5169** ^(The aConstraint[] array records WHERE clause constraints of the form:
5170**
5171** <blockquote>column OP expr</blockquote>
5172**
5173** where OP is =, &lt;, &lt;=, &gt;, or &gt;=.)^  ^(The particular operator is
5174** stored in aConstraint[].op using one of the
5175** [SQLITE_INDEX_CONSTRAINT_EQ | SQLITE_INDEX_CONSTRAINT_ values].)^
5176** ^(The index of the column is stored in
5177** aConstraint[].iColumn.)^  ^(aConstraint[].usable is TRUE if the
5178** expr on the right-hand side can be evaluated (and thus the constraint
5179** is usable) and false if it cannot.)^
5180**
5181** ^The optimizer automatically inverts terms of the form "expr OP column"
5182** and makes other simplifications to the WHERE clause in an attempt to
5183** get as many WHERE clause terms into the form shown above as possible.
5184** ^The aConstraint[] array only reports WHERE clause terms that are
5185** relevant to the particular virtual table being queried.
5186**
5187** ^Information about the ORDER BY clause is stored in aOrderBy[].
5188** ^Each term of aOrderBy records a column of the ORDER BY clause.
5189**
5190** The [xBestIndex] method must fill aConstraintUsage[] with information
5191** about what parameters to pass to xFilter.  ^If argvIndex>0 then
5192** the right-hand side of the corresponding aConstraint[] is evaluated
5193** and becomes the argvIndex-th entry in argv.  ^(If aConstraintUsage[].omit
5194** is true, then the constraint is assumed to be fully handled by the
5195** virtual table and is not checked again by SQLite.)^
5196**
5197** ^The idxNum and idxPtr values are recorded and passed into the
5198** [xFilter] method.
5199** ^[sqlite3_free()] is used to free idxPtr if and only if
5200** needToFreeIdxPtr is true.
5201**
5202** ^The orderByConsumed means that output from [xFilter]/[xNext] will occur in
5203** the correct order to satisfy the ORDER BY clause so that no separate
5204** sorting step is required.
5205**
5206** ^The estimatedCost value is an estimate of the cost of doing the
5207** particular lookup.  A full scan of a table with N entries should have
5208** a cost of N.  A binary search of a table of N entries should have a
5209** cost of approximately log(N).
5210*/
5211struct sqlite3_index_info {
5212  /* Inputs */
5213  int nConstraint;           /* Number of entries in aConstraint */
5214  struct sqlite3_index_constraint {
5215     int iColumn;              /* Column on left-hand side of constraint */
5216     unsigned char op;         /* Constraint operator */
5217     unsigned char usable;     /* True if this constraint is usable */
5218     int iTermOffset;          /* Used internally - xBestIndex should ignore */
5219  } *aConstraint;            /* Table of WHERE clause constraints */
5220  int nOrderBy;              /* Number of terms in the ORDER BY clause */
5221  struct sqlite3_index_orderby {
5222     int iColumn;              /* Column number */
5223     unsigned char desc;       /* True for DESC.  False for ASC. */
5224  } *aOrderBy;               /* The ORDER BY clause */
5225  /* Outputs */
5226  struct sqlite3_index_constraint_usage {
5227    int argvIndex;           /* if >0, constraint is part of argv to xFilter */
5228    unsigned char omit;      /* Do not code a test for this constraint */
5229  } *aConstraintUsage;
5230  int idxNum;                /* Number used to identify the index */
5231  char *idxStr;              /* String, possibly obtained from sqlite3_malloc */
5232  int needToFreeIdxStr;      /* Free idxStr using sqlite3_free() if true */
5233  int orderByConsumed;       /* True if output is already ordered */
5234  double estimatedCost;      /* Estimated cost of using this index */
5235};
5236
5237/*
5238** CAPI3REF: Virtual Table Constraint Operator Codes
5239**
5240** These macros defined the allowed values for the
5241** [sqlite3_index_info].aConstraint[].op field.  Each value represents
5242** an operator that is part of a constraint term in the wHERE clause of
5243** a query that uses a [virtual table].
5244*/
5245#define SQLITE_INDEX_CONSTRAINT_EQ    2
5246#define SQLITE_INDEX_CONSTRAINT_GT    4
5247#define SQLITE_INDEX_CONSTRAINT_LE    8
5248#define SQLITE_INDEX_CONSTRAINT_LT    16
5249#define SQLITE_INDEX_CONSTRAINT_GE    32
5250#define SQLITE_INDEX_CONSTRAINT_MATCH 64
5251
5252/*
5253** CAPI3REF: Register A Virtual Table Implementation
5254**
5255** ^These routines are used to register a new [virtual table module] name.
5256** ^Module names must be registered before
5257** creating a new [virtual table] using the module and before using a
5258** preexisting [virtual table] for the module.
5259**
5260** ^The module name is registered on the [database connection] specified
5261** by the first parameter.  ^The name of the module is given by the
5262** second parameter.  ^The third parameter is a pointer to
5263** the implementation of the [virtual table module].   ^The fourth
5264** parameter is an arbitrary client data pointer that is passed through
5265** into the [xCreate] and [xConnect] methods of the virtual table module
5266** when a new virtual table is be being created or reinitialized.
5267**
5268** ^The sqlite3_create_module_v2() interface has a fifth parameter which
5269** is a pointer to a destructor for the pClientData.  ^SQLite will
5270** invoke the destructor function (if it is not NULL) when SQLite
5271** no longer needs the pClientData pointer.  ^The destructor will also
5272** be invoked if the call to sqlite3_create_module_v2() fails.
5273** ^The sqlite3_create_module()
5274** interface is equivalent to sqlite3_create_module_v2() with a NULL
5275** destructor.
5276*/
5277SQLITE_API int sqlite3_create_module(
5278  sqlite3 *db,               /* SQLite connection to register module with */
5279  const char *zName,         /* Name of the module */
5280  const sqlite3_module *p,   /* Methods for the module */
5281  void *pClientData          /* Client data for xCreate/xConnect */
5282);
5283SQLITE_API int sqlite3_create_module_v2(
5284  sqlite3 *db,               /* SQLite connection to register module with */
5285  const char *zName,         /* Name of the module */
5286  const sqlite3_module *p,   /* Methods for the module */
5287  void *pClientData,         /* Client data for xCreate/xConnect */
5288  void(*xDestroy)(void*)     /* Module destructor function */
5289);
5290
5291/*
5292** CAPI3REF: Virtual Table Instance Object
5293** KEYWORDS: sqlite3_vtab
5294**
5295** Every [virtual table module] implementation uses a subclass
5296** of this object to describe a particular instance
5297** of the [virtual table].  Each subclass will
5298** be tailored to the specific needs of the module implementation.
5299** The purpose of this superclass is to define certain fields that are
5300** common to all module implementations.
5301**
5302** ^Virtual tables methods can set an error message by assigning a
5303** string obtained from [sqlite3_mprintf()] to zErrMsg.  The method should
5304** take care that any prior string is freed by a call to [sqlite3_free()]
5305** prior to assigning a new string to zErrMsg.  ^After the error message
5306** is delivered up to the client application, the string will be automatically
5307** freed by sqlite3_free() and the zErrMsg field will be zeroed.
5308*/
5309struct sqlite3_vtab {
5310  const sqlite3_module *pModule;  /* The module for this virtual table */
5311  int nRef;                       /* NO LONGER USED */
5312  char *zErrMsg;                  /* Error message from sqlite3_mprintf() */
5313  /* Virtual table implementations will typically add additional fields */
5314};
5315
5316/*
5317** CAPI3REF: Virtual Table Cursor Object
5318** KEYWORDS: sqlite3_vtab_cursor {virtual table cursor}
5319**
5320** Every [virtual table module] implementation uses a subclass of the
5321** following structure to describe cursors that point into the
5322** [virtual table] and are used
5323** to loop through the virtual table.  Cursors are created using the
5324** [sqlite3_module.xOpen | xOpen] method of the module and are destroyed
5325** by the [sqlite3_module.xClose | xClose] method.  Cursors are used
5326** by the [xFilter], [xNext], [xEof], [xColumn], and [xRowid] methods
5327** of the module.  Each module implementation will define
5328** the content of a cursor structure to suit its own needs.
5329**
5330** This superclass exists in order to define fields of the cursor that
5331** are common to all implementations.
5332*/
5333struct sqlite3_vtab_cursor {
5334  sqlite3_vtab *pVtab;      /* Virtual table of this cursor */
5335  /* Virtual table implementations will typically add additional fields */
5336};
5337
5338/*
5339** CAPI3REF: Declare The Schema Of A Virtual Table
5340**
5341** ^The [xCreate] and [xConnect] methods of a
5342** [virtual table module] call this interface
5343** to declare the format (the names and datatypes of the columns) of
5344** the virtual tables they implement.
5345*/
5346SQLITE_API int sqlite3_declare_vtab(sqlite3*, const char *zSQL);
5347
5348/*
5349** CAPI3REF: Overload A Function For A Virtual Table
5350**
5351** ^(Virtual tables can provide alternative implementations of functions
5352** using the [xFindFunction] method of the [virtual table module].
5353** But global versions of those functions
5354** must exist in order to be overloaded.)^
5355**
5356** ^(This API makes sure a global version of a function with a particular
5357** name and number of parameters exists.  If no such function exists
5358** before this API is called, a new function is created.)^  ^The implementation
5359** of the new function always causes an exception to be thrown.  So
5360** the new function is not good for anything by itself.  Its only
5361** purpose is to be a placeholder function that can be overloaded
5362** by a [virtual table].
5363*/
5364SQLITE_API int sqlite3_overload_function(sqlite3*, const char *zFuncName, int nArg);
5365
5366/*
5367** The interface to the virtual-table mechanism defined above (back up
5368** to a comment remarkably similar to this one) is currently considered
5369** to be experimental.  The interface might change in incompatible ways.
5370** If this is a problem for you, do not use the interface at this time.
5371**
5372** When the virtual-table mechanism stabilizes, we will declare the
5373** interface fixed, support it indefinitely, and remove this comment.
5374*/
5375
5376/*
5377** CAPI3REF: A Handle To An Open BLOB
5378** KEYWORDS: {BLOB handle} {BLOB handles}
5379**
5380** An instance of this object represents an open BLOB on which
5381** [sqlite3_blob_open | incremental BLOB I/O] can be performed.
5382** ^Objects of this type are created by [sqlite3_blob_open()]
5383** and destroyed by [sqlite3_blob_close()].
5384** ^The [sqlite3_blob_read()] and [sqlite3_blob_write()] interfaces
5385** can be used to read or write small subsections of the BLOB.
5386** ^The [sqlite3_blob_bytes()] interface returns the size of the BLOB in bytes.
5387*/
5388typedef struct sqlite3_blob sqlite3_blob;
5389
5390/*
5391** CAPI3REF: Open A BLOB For Incremental I/O
5392**
5393** ^(This interfaces opens a [BLOB handle | handle] to the BLOB located
5394** in row iRow, column zColumn, table zTable in database zDb;
5395** in other words, the same BLOB that would be selected by:
5396**
5397** <pre>
5398**     SELECT zColumn FROM zDb.zTable WHERE [rowid] = iRow;
5399** </pre>)^
5400**
5401** ^If the flags parameter is non-zero, then the BLOB is opened for read
5402** and write access. ^If it is zero, the BLOB is opened for read access.
5403** ^It is not possible to open a column that is part of an index or primary
5404** key for writing. ^If [foreign key constraints] are enabled, it is
5405** not possible to open a column that is part of a [child key] for writing.
5406**
5407** ^Note that the database name is not the filename that contains
5408** the database but rather the symbolic name of the database that
5409** appears after the AS keyword when the database is connected using [ATTACH].
5410** ^For the main database file, the database name is "main".
5411** ^For TEMP tables, the database name is "temp".
5412**
5413** ^(On success, [SQLITE_OK] is returned and the new [BLOB handle] is written
5414** to *ppBlob. Otherwise an [error code] is returned and *ppBlob is set
5415** to be a null pointer.)^
5416** ^This function sets the [database connection] error code and message
5417** accessible via [sqlite3_errcode()] and [sqlite3_errmsg()] and related
5418** functions. ^Note that the *ppBlob variable is always initialized in a
5419** way that makes it safe to invoke [sqlite3_blob_close()] on *ppBlob
5420** regardless of the success or failure of this routine.
5421**
5422** ^(If the row that a BLOB handle points to is modified by an
5423** [UPDATE], [DELETE], or by [ON CONFLICT] side-effects
5424** then the BLOB handle is marked as "expired".
5425** This is true if any column of the row is changed, even a column
5426** other than the one the BLOB handle is open on.)^
5427** ^Calls to [sqlite3_blob_read()] and [sqlite3_blob_write()] for
5428** an expired BLOB handle fail with a return code of [SQLITE_ABORT].
5429** ^(Changes written into a BLOB prior to the BLOB expiring are not
5430** rolled back by the expiration of the BLOB.  Such changes will eventually
5431** commit if the transaction continues to completion.)^
5432**
5433** ^Use the [sqlite3_blob_bytes()] interface to determine the size of
5434** the opened blob.  ^The size of a blob may not be changed by this
5435** interface.  Use the [UPDATE] SQL command to change the size of a
5436** blob.
5437**
5438** ^The [sqlite3_bind_zeroblob()] and [sqlite3_result_zeroblob()] interfaces
5439** and the built-in [zeroblob] SQL function can be used, if desired,
5440** to create an empty, zero-filled blob in which to read or write using
5441** this interface.
5442**
5443** To avoid a resource leak, every open [BLOB handle] should eventually
5444** be released by a call to [sqlite3_blob_close()].
5445*/
5446SQLITE_API int sqlite3_blob_open(
5447  sqlite3*,
5448  const char *zDb,
5449  const char *zTable,
5450  const char *zColumn,
5451  sqlite3_int64 iRow,
5452  int flags,
5453  sqlite3_blob **ppBlob
5454);
5455
5456/*
5457** CAPI3REF: Move a BLOB Handle to a New Row
5458**
5459** ^This function is used to move an existing blob handle so that it points
5460** to a different row of the same database table. ^The new row is identified
5461** by the rowid value passed as the second argument. Only the row can be
5462** changed. ^The database, table and column on which the blob handle is open
5463** remain the same. Moving an existing blob handle to a new row can be
5464** faster than closing the existing handle and opening a new one.
5465**
5466** ^(The new row must meet the same criteria as for [sqlite3_blob_open()] -
5467** it must exist and there must be either a blob or text value stored in
5468** the nominated column.)^ ^If the new row is not present in the table, or if
5469** it does not contain a blob or text value, or if another error occurs, an
5470** SQLite error code is returned and the blob handle is considered aborted.
5471** ^All subsequent calls to [sqlite3_blob_read()], [sqlite3_blob_write()] or
5472** [sqlite3_blob_reopen()] on an aborted blob handle immediately return
5473** SQLITE_ABORT. ^Calling [sqlite3_blob_bytes()] on an aborted blob handle
5474** always returns zero.
5475**
5476** ^This function sets the database handle error code and message.
5477*/
5478SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_blob_reopen(sqlite3_blob *, sqlite3_int64);
5479
5480/*
5481** CAPI3REF: Close A BLOB Handle
5482**
5483** ^Closes an open [BLOB handle].
5484**
5485** ^Closing a BLOB shall cause the current transaction to commit
5486** if there are no other BLOBs, no pending prepared statements, and the
5487** database connection is in [autocommit mode].
5488** ^If any writes were made to the BLOB, they might be held in cache
5489** until the close operation if they will fit.
5490**
5491** ^(Closing the BLOB often forces the changes
5492** out to disk and so if any I/O errors occur, they will likely occur
5493** at the time when the BLOB is closed.  Any errors that occur during
5494** closing are reported as a non-zero return value.)^
5495**
5496** ^(The BLOB is closed unconditionally.  Even if this routine returns
5497** an error code, the BLOB is still closed.)^
5498**
5499** ^Calling this routine with a null pointer (such as would be returned
5500** by a failed call to [sqlite3_blob_open()]) is a harmless no-op.
5501*/
5502SQLITE_API int sqlite3_blob_close(sqlite3_blob *);
5503
5504/*
5505** CAPI3REF: Return The Size Of An Open BLOB
5506**
5507** ^Returns the size in bytes of the BLOB accessible via the
5508** successfully opened [BLOB handle] in its only argument.  ^The
5509** incremental blob I/O routines can only read or overwriting existing
5510** blob content; they cannot change the size of a blob.
5511**
5512** This routine only works on a [BLOB handle] which has been created
5513** by a prior successful call to [sqlite3_blob_open()] and which has not
5514** been closed by [sqlite3_blob_close()].  Passing any other pointer in
5515** to this routine results in undefined and probably undesirable behavior.
5516*/
5517SQLITE_API int sqlite3_blob_bytes(sqlite3_blob *);
5518
5519/*
5520** CAPI3REF: Read Data From A BLOB Incrementally
5521**
5522** ^(This function is used to read data from an open [BLOB handle] into a
5523** caller-supplied buffer. N bytes of data are copied into buffer Z
5524** from the open BLOB, starting at offset iOffset.)^
5525**
5526** ^If offset iOffset is less than N bytes from the end of the BLOB,
5527** [SQLITE_ERROR] is returned and no data is read.  ^If N or iOffset is
5528** less than zero, [SQLITE_ERROR] is returned and no data is read.
5529** ^The size of the blob (and hence the maximum value of N+iOffset)
5530** can be determined using the [sqlite3_blob_bytes()] interface.
5531**
5532** ^An attempt to read from an expired [BLOB handle] fails with an
5533** error code of [SQLITE_ABORT].
5534**
5535** ^(On success, sqlite3_blob_read() returns SQLITE_OK.
5536** Otherwise, an [error code] or an [extended error code] is returned.)^
5537**
5538** This routine only works on a [BLOB handle] which has been created
5539** by a prior successful call to [sqlite3_blob_open()] and which has not
5540** been closed by [sqlite3_blob_close()].  Passing any other pointer in
5541** to this routine results in undefined and probably undesirable behavior.
5542**
5543** See also: [sqlite3_blob_write()].
5544*/
5545SQLITE_API int sqlite3_blob_read(sqlite3_blob *, void *Z, int N, int iOffset);
5546
5547/*
5548** CAPI3REF: Write Data Into A BLOB Incrementally
5549**
5550** ^This function is used to write data into an open [BLOB handle] from a
5551** caller-supplied buffer. ^N bytes of data are copied from the buffer Z
5552** into the open BLOB, starting at offset iOffset.
5553**
5554** ^If the [BLOB handle] passed as the first argument was not opened for
5555** writing (the flags parameter to [sqlite3_blob_open()] was zero),
5556** this function returns [SQLITE_READONLY].
5557**
5558** ^This function may only modify the contents of the BLOB; it is
5559** not possible to increase the size of a BLOB using this API.
5560** ^If offset iOffset is less than N bytes from the end of the BLOB,
5561** [SQLITE_ERROR] is returned and no data is written.  ^If N is
5562** less than zero [SQLITE_ERROR] is returned and no data is written.
5563** The size of the BLOB (and hence the maximum value of N+iOffset)
5564** can be determined using the [sqlite3_blob_bytes()] interface.
5565**
5566** ^An attempt to write to an expired [BLOB handle] fails with an
5567** error code of [SQLITE_ABORT].  ^Writes to the BLOB that occurred
5568** before the [BLOB handle] expired are not rolled back by the
5569** expiration of the handle, though of course those changes might
5570** have been overwritten by the statement that expired the BLOB handle
5571** or by other independent statements.
5572**
5573** ^(On success, sqlite3_blob_write() returns SQLITE_OK.
5574** Otherwise, an  [error code] or an [extended error code] is returned.)^
5575**
5576** This routine only works on a [BLOB handle] which has been created
5577** by a prior successful call to [sqlite3_blob_open()] and which has not
5578** been closed by [sqlite3_blob_close()].  Passing any other pointer in
5579** to this routine results in undefined and probably undesirable behavior.
5580**
5581** See also: [sqlite3_blob_read()].
5582*/
5583SQLITE_API int sqlite3_blob_write(sqlite3_blob *, const void *z, int n, int iOffset);
5584
5585/*
5586** CAPI3REF: Virtual File System Objects
5587**
5588** A virtual filesystem (VFS) is an [sqlite3_vfs] object
5589** that SQLite uses to interact
5590** with the underlying operating system.  Most SQLite builds come with a
5591** single default VFS that is appropriate for the host computer.
5592** New VFSes can be registered and existing VFSes can be unregistered.
5593** The following interfaces are provided.
5594**
5595** ^The sqlite3_vfs_find() interface returns a pointer to a VFS given its name.
5596** ^Names are case sensitive.
5597** ^Names are zero-terminated UTF-8 strings.
5598** ^If there is no match, a NULL pointer is returned.
5599** ^If zVfsName is NULL then the default VFS is returned.
5600**
5601** ^New VFSes are registered with sqlite3_vfs_register().
5602** ^Each new VFS becomes the default VFS if the makeDflt flag is set.
5603** ^The same VFS can be registered multiple times without injury.
5604** ^To make an existing VFS into the default VFS, register it again
5605** with the makeDflt flag set.  If two different VFSes with the
5606** same name are registered, the behavior is undefined.  If a
5607** VFS is registered with a name that is NULL or an empty string,
5608** then the behavior is undefined.
5609**
5610** ^Unregister a VFS with the sqlite3_vfs_unregister() interface.
5611** ^(If the default VFS is unregistered, another VFS is chosen as
5612** the default.  The choice for the new VFS is arbitrary.)^
5613*/
5614SQLITE_API sqlite3_vfs *sqlite3_vfs_find(const char *zVfsName);
5615SQLITE_API int sqlite3_vfs_register(sqlite3_vfs*, int makeDflt);
5616SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs*);
5617
5618/*
5619** CAPI3REF: Mutexes
5620**
5621** The SQLite core uses these routines for thread
5622** synchronization. Though they are intended for internal
5623** use by SQLite, code that links against SQLite is
5624** permitted to use any of these routines.
5625**
5626** The SQLite source code contains multiple implementations
5627** of these mutex routines.  An appropriate implementation
5628** is selected automatically at compile-time.  ^(The following
5629** implementations are available in the SQLite core:
5630**
5631** <ul>
5632** <li>   SQLITE_MUTEX_OS2
5633** <li>   SQLITE_MUTEX_PTHREAD
5634** <li>   SQLITE_MUTEX_W32
5635** <li>   SQLITE_MUTEX_NOOP
5636** </ul>)^
5637**
5638** ^The SQLITE_MUTEX_NOOP implementation is a set of routines
5639** that does no real locking and is appropriate for use in
5640** a single-threaded application.  ^The SQLITE_MUTEX_OS2,
5641** SQLITE_MUTEX_PTHREAD, and SQLITE_MUTEX_W32 implementations
5642** are appropriate for use on OS/2, Unix, and Windows.
5643**
5644** ^(If SQLite is compiled with the SQLITE_MUTEX_APPDEF preprocessor
5645** macro defined (with "-DSQLITE_MUTEX_APPDEF=1"), then no mutex
5646** implementation is included with the library. In this case the
5647** application must supply a custom mutex implementation using the
5648** [SQLITE_CONFIG_MUTEX] option of the sqlite3_config() function
5649** before calling sqlite3_initialize() or any other public sqlite3_
5650** function that calls sqlite3_initialize().)^
5651**
5652** ^The sqlite3_mutex_alloc() routine allocates a new
5653** mutex and returns a pointer to it. ^If it returns NULL
5654** that means that a mutex could not be allocated.  ^SQLite
5655** will unwind its stack and return an error.  ^(The argument
5656** to sqlite3_mutex_alloc() is one of these integer constants:
5657**
5658** <ul>
5659** <li>  SQLITE_MUTEX_FAST
5660** <li>  SQLITE_MUTEX_RECURSIVE
5661** <li>  SQLITE_MUTEX_STATIC_MASTER
5662** <li>  SQLITE_MUTEX_STATIC_MEM
5663** <li>  SQLITE_MUTEX_STATIC_MEM2
5664** <li>  SQLITE_MUTEX_STATIC_PRNG
5665** <li>  SQLITE_MUTEX_STATIC_LRU
5666** <li>  SQLITE_MUTEX_STATIC_LRU2
5667** </ul>)^
5668**
5669** ^The first two constants (SQLITE_MUTEX_FAST and SQLITE_MUTEX_RECURSIVE)
5670** cause sqlite3_mutex_alloc() to create
5671** a new mutex.  ^The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
5672** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
5673** The mutex implementation does not need to make a distinction
5674** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
5675** not want to.  ^SQLite will only request a recursive mutex in
5676** cases where it really needs one.  ^If a faster non-recursive mutex
5677** implementation is available on the host platform, the mutex subsystem
5678** might return such a mutex in response to SQLITE_MUTEX_FAST.
5679**
5680** ^The other allowed parameters to sqlite3_mutex_alloc() (anything other
5681** than SQLITE_MUTEX_FAST and SQLITE_MUTEX_RECURSIVE) each return
5682** a pointer to a static preexisting mutex.  ^Six static mutexes are
5683** used by the current version of SQLite.  Future versions of SQLite
5684** may add additional static mutexes.  Static mutexes are for internal
5685** use by SQLite only.  Applications that use SQLite mutexes should
5686** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
5687** SQLITE_MUTEX_RECURSIVE.
5688**
5689** ^Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
5690** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
5691** returns a different mutex on every call.  ^But for the static
5692** mutex types, the same mutex is returned on every call that has
5693** the same type number.
5694**
5695** ^The sqlite3_mutex_free() routine deallocates a previously
5696** allocated dynamic mutex.  ^SQLite is careful to deallocate every
5697** dynamic mutex that it allocates.  The dynamic mutexes must not be in
5698** use when they are deallocated.  Attempting to deallocate a static
5699** mutex results in undefined behavior.  ^SQLite never deallocates
5700** a static mutex.
5701**
5702** ^The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
5703** to enter a mutex.  ^If another thread is already within the mutex,
5704** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
5705** SQLITE_BUSY.  ^The sqlite3_mutex_try() interface returns [SQLITE_OK]
5706** upon successful entry.  ^(Mutexes created using
5707** SQLITE_MUTEX_RECURSIVE can be entered multiple times by the same thread.
5708** In such cases the,
5709** mutex must be exited an equal number of times before another thread
5710** can enter.)^  ^(If the same thread tries to enter any other
5711** kind of mutex more than once, the behavior is undefined.
5712** SQLite will never exhibit
5713** such behavior in its own use of mutexes.)^
5714**
5715** ^(Some systems (for example, Windows 95) do not support the operation
5716** implemented by sqlite3_mutex_try().  On those systems, sqlite3_mutex_try()
5717** will always return SQLITE_BUSY.  The SQLite core only ever uses
5718** sqlite3_mutex_try() as an optimization so this is acceptable behavior.)^
5719**
5720** ^The sqlite3_mutex_leave() routine exits a mutex that was
5721** previously entered by the same thread.   ^(The behavior
5722** is undefined if the mutex is not currently entered by the
5723** calling thread or is not currently allocated.  SQLite will
5724** never do either.)^
5725**
5726** ^If the argument to sqlite3_mutex_enter(), sqlite3_mutex_try(), or
5727** sqlite3_mutex_leave() is a NULL pointer, then all three routines
5728** behave as no-ops.
5729**
5730** See also: [sqlite3_mutex_held()] and [sqlite3_mutex_notheld()].
5731*/
5732SQLITE_API sqlite3_mutex *sqlite3_mutex_alloc(int);
5733SQLITE_API void sqlite3_mutex_free(sqlite3_mutex*);
5734SQLITE_API void sqlite3_mutex_enter(sqlite3_mutex*);
5735SQLITE_API int sqlite3_mutex_try(sqlite3_mutex*);
5736SQLITE_API void sqlite3_mutex_leave(sqlite3_mutex*);
5737
5738/*
5739** CAPI3REF: Mutex Methods Object
5740**
5741** An instance of this structure defines the low-level routines
5742** used to allocate and use mutexes.
5743**
5744** Usually, the default mutex implementations provided by SQLite are
5745** sufficient, however the user has the option of substituting a custom
5746** implementation for specialized deployments or systems for which SQLite
5747** does not provide a suitable implementation. In this case, the user
5748** creates and populates an instance of this structure to pass
5749** to sqlite3_config() along with the [SQLITE_CONFIG_MUTEX] option.
5750** Additionally, an instance of this structure can be used as an
5751** output variable when querying the system for the current mutex
5752** implementation, using the [SQLITE_CONFIG_GETMUTEX] option.
5753**
5754** ^The xMutexInit method defined by this structure is invoked as
5755** part of system initialization by the sqlite3_initialize() function.
5756** ^The xMutexInit routine is called by SQLite exactly once for each
5757** effective call to [sqlite3_initialize()].
5758**
5759** ^The xMutexEnd method defined by this structure is invoked as
5760** part of system shutdown by the sqlite3_shutdown() function. The
5761** implementation of this method is expected to release all outstanding
5762** resources obtained by the mutex methods implementation, especially
5763** those obtained by the xMutexInit method.  ^The xMutexEnd()
5764** interface is invoked exactly once for each call to [sqlite3_shutdown()].
5765**
5766** ^(The remaining seven methods defined by this structure (xMutexAlloc,
5767** xMutexFree, xMutexEnter, xMutexTry, xMutexLeave, xMutexHeld and
5768** xMutexNotheld) implement the following interfaces (respectively):
5769**
5770** <ul>
5771**   <li>  [sqlite3_mutex_alloc()] </li>
5772**   <li>  [sqlite3_mutex_free()] </li>
5773**   <li>  [sqlite3_mutex_enter()] </li>
5774**   <li>  [sqlite3_mutex_try()] </li>
5775**   <li>  [sqlite3_mutex_leave()] </li>
5776**   <li>  [sqlite3_mutex_held()] </li>
5777**   <li>  [sqlite3_mutex_notheld()] </li>
5778** </ul>)^
5779**
5780** The only difference is that the public sqlite3_XXX functions enumerated
5781** above silently ignore any invocations that pass a NULL pointer instead
5782** of a valid mutex handle. The implementations of the methods defined
5783** by this structure are not required to handle this case, the results
5784** of passing a NULL pointer instead of a valid mutex handle are undefined
5785** (i.e. it is acceptable to provide an implementation that segfaults if
5786** it is passed a NULL pointer).
5787**
5788** The xMutexInit() method must be threadsafe.  ^It must be harmless to
5789** invoke xMutexInit() multiple times within the same process and without
5790** intervening calls to xMutexEnd().  Second and subsequent calls to
5791** xMutexInit() must be no-ops.
5792**
5793** ^xMutexInit() must not use SQLite memory allocation ([sqlite3_malloc()]
5794** and its associates).  ^Similarly, xMutexAlloc() must not use SQLite memory
5795** allocation for a static mutex.  ^However xMutexAlloc() may use SQLite
5796** memory allocation for a fast or recursive mutex.
5797**
5798** ^SQLite will invoke the xMutexEnd() method when [sqlite3_shutdown()] is
5799** called, but only if the prior call to xMutexInit returned SQLITE_OK.
5800** If xMutexInit fails in any way, it is expected to clean up after itself
5801** prior to returning.
5802*/
5803typedef struct sqlite3_mutex_methods sqlite3_mutex_methods;
5804struct sqlite3_mutex_methods {
5805  int (*xMutexInit)(void);
5806  int (*xMutexEnd)(void);
5807  sqlite3_mutex *(*xMutexAlloc)(int);
5808  void (*xMutexFree)(sqlite3_mutex *);
5809  void (*xMutexEnter)(sqlite3_mutex *);
5810  int (*xMutexTry)(sqlite3_mutex *);
5811  void (*xMutexLeave)(sqlite3_mutex *);
5812  int (*xMutexHeld)(sqlite3_mutex *);
5813  int (*xMutexNotheld)(sqlite3_mutex *);
5814};
5815
5816/*
5817** CAPI3REF: Mutex Verification Routines
5818**
5819** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routines
5820** are intended for use inside assert() statements.  ^The SQLite core
5821** never uses these routines except inside an assert() and applications
5822** are advised to follow the lead of the core.  ^The SQLite core only
5823** provides implementations for these routines when it is compiled
5824** with the SQLITE_DEBUG flag.  ^External mutex implementations
5825** are only required to provide these routines if SQLITE_DEBUG is
5826** defined and if NDEBUG is not defined.
5827**
5828** ^These routines should return true if the mutex in their argument
5829** is held or not held, respectively, by the calling thread.
5830**
5831** ^The implementation is not required to provided versions of these
5832** routines that actually work. If the implementation does not provide working
5833** versions of these routines, it should at least provide stubs that always
5834** return true so that one does not get spurious assertion failures.
5835**
5836** ^If the argument to sqlite3_mutex_held() is a NULL pointer then
5837** the routine should return 1.   This seems counter-intuitive since
5838** clearly the mutex cannot be held if it does not exist.  But the
5839** the reason the mutex does not exist is because the build is not
5840** using mutexes.  And we do not want the assert() containing the
5841** call to sqlite3_mutex_held() to fail, so a non-zero return is
5842** the appropriate thing to do.  ^The sqlite3_mutex_notheld()
5843** interface should also return 1 when given a NULL pointer.
5844*/
5845#ifndef NDEBUG
5846SQLITE_API int sqlite3_mutex_held(sqlite3_mutex*);
5847SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex*);
5848#endif
5849
5850/*
5851** CAPI3REF: Mutex Types
5852**
5853** The [sqlite3_mutex_alloc()] interface takes a single argument
5854** which is one of these integer constants.
5855**
5856** The set of static mutexes may change from one SQLite release to the
5857** next.  Applications that override the built-in mutex logic must be
5858** prepared to accommodate additional static mutexes.
5859*/
5860#define SQLITE_MUTEX_FAST             0
5861#define SQLITE_MUTEX_RECURSIVE        1
5862#define SQLITE_MUTEX_STATIC_MASTER    2
5863#define SQLITE_MUTEX_STATIC_MEM       3  /* sqlite3_malloc() */
5864#define SQLITE_MUTEX_STATIC_MEM2      4  /* NOT USED */
5865#define SQLITE_MUTEX_STATIC_OPEN      4  /* sqlite3BtreeOpen() */
5866#define SQLITE_MUTEX_STATIC_PRNG      5  /* sqlite3_random() */
5867#define SQLITE_MUTEX_STATIC_LRU       6  /* lru page list */
5868#define SQLITE_MUTEX_STATIC_LRU2      7  /* NOT USED */
5869#define SQLITE_MUTEX_STATIC_PMEM      7  /* sqlite3PageMalloc() */
5870
5871/*
5872** CAPI3REF: Retrieve the mutex for a database connection
5873**
5874** ^This interface returns a pointer the [sqlite3_mutex] object that
5875** serializes access to the [database connection] given in the argument
5876** when the [threading mode] is Serialized.
5877** ^If the [threading mode] is Single-thread or Multi-thread then this
5878** routine returns a NULL pointer.
5879*/
5880SQLITE_API sqlite3_mutex *sqlite3_db_mutex(sqlite3*);
5881
5882/*
5883** CAPI3REF: Low-Level Control Of Database Files
5884**
5885** ^The [sqlite3_file_control()] interface makes a direct call to the
5886** xFileControl method for the [sqlite3_io_methods] object associated
5887** with a particular database identified by the second argument. ^The
5888** name of the database is "main" for the main database or "temp" for the
5889** TEMP database, or the name that appears after the AS keyword for
5890** databases that are added using the [ATTACH] SQL command.
5891** ^A NULL pointer can be used in place of "main" to refer to the
5892** main database file.
5893** ^The third and fourth parameters to this routine
5894** are passed directly through to the second and third parameters of
5895** the xFileControl method.  ^The return value of the xFileControl
5896** method becomes the return value of this routine.
5897**
5898** ^The SQLITE_FCNTL_FILE_POINTER value for the op parameter causes
5899** a pointer to the underlying [sqlite3_file] object to be written into
5900** the space pointed to by the 4th parameter.  ^The SQLITE_FCNTL_FILE_POINTER
5901** case is a short-circuit path which does not actually invoke the
5902** underlying sqlite3_io_methods.xFileControl method.
5903**
5904** ^If the second parameter (zDbName) does not match the name of any
5905** open database file, then SQLITE_ERROR is returned.  ^This error
5906** code is not remembered and will not be recalled by [sqlite3_errcode()]
5907** or [sqlite3_errmsg()].  The underlying xFileControl method might
5908** also return SQLITE_ERROR.  There is no way to distinguish between
5909** an incorrect zDbName and an SQLITE_ERROR return from the underlying
5910** xFileControl method.
5911**
5912** See also: [SQLITE_FCNTL_LOCKSTATE]
5913*/
5914SQLITE_API int sqlite3_file_control(sqlite3*, const char *zDbName, int op, void*);
5915
5916/*
5917** CAPI3REF: Testing Interface
5918**
5919** ^The sqlite3_test_control() interface is used to read out internal
5920** state of SQLite and to inject faults into SQLite for testing
5921** purposes.  ^The first parameter is an operation code that determines
5922** the number, meaning, and operation of all subsequent parameters.
5923**
5924** This interface is not for use by applications.  It exists solely
5925** for verifying the correct operation of the SQLite library.  Depending
5926** on how the SQLite library is compiled, this interface might not exist.
5927**
5928** The details of the operation codes, their meanings, the parameters
5929** they take, and what they do are all subject to change without notice.
5930** Unlike most of the SQLite API, this function is not guaranteed to
5931** operate consistently from one release to the next.
5932*/
5933SQLITE_API int sqlite3_test_control(int op, ...);
5934
5935/*
5936** CAPI3REF: Testing Interface Operation Codes
5937**
5938** These constants are the valid operation code parameters used
5939** as the first argument to [sqlite3_test_control()].
5940**
5941** These parameters and their meanings are subject to change
5942** without notice.  These values are for testing purposes only.
5943** Applications should not use any of these parameters or the
5944** [sqlite3_test_control()] interface.
5945*/
5946#define SQLITE_TESTCTRL_FIRST                    5
5947#define SQLITE_TESTCTRL_PRNG_SAVE                5
5948#define SQLITE_TESTCTRL_PRNG_RESTORE             6
5949#define SQLITE_TESTCTRL_PRNG_RESET               7
5950#define SQLITE_TESTCTRL_BITVEC_TEST              8
5951#define SQLITE_TESTCTRL_FAULT_INSTALL            9
5952#define SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS     10
5953#define SQLITE_TESTCTRL_PENDING_BYTE            11
5954#define SQLITE_TESTCTRL_ASSERT                  12
5955#define SQLITE_TESTCTRL_ALWAYS                  13
5956#define SQLITE_TESTCTRL_RESERVE                 14
5957#define SQLITE_TESTCTRL_OPTIMIZATIONS           15
5958#define SQLITE_TESTCTRL_ISKEYWORD               16
5959#define SQLITE_TESTCTRL_PGHDRSZ                 17
5960#define SQLITE_TESTCTRL_SCRATCHMALLOC           18
5961#define SQLITE_TESTCTRL_LAST                    18
5962
5963/*
5964** CAPI3REF: SQLite Runtime Status
5965**
5966** ^This interface is used to retrieve runtime status information
5967** about the performance of SQLite, and optionally to reset various
5968** highwater marks.  ^The first argument is an integer code for
5969** the specific parameter to measure.  ^(Recognized integer codes
5970** are of the form [SQLITE_STATUS_MEMORY_USED | SQLITE_STATUS_...].)^
5971** ^The current value of the parameter is returned into *pCurrent.
5972** ^The highest recorded value is returned in *pHighwater.  ^If the
5973** resetFlag is true, then the highest record value is reset after
5974** *pHighwater is written.  ^(Some parameters do not record the highest
5975** value.  For those parameters
5976** nothing is written into *pHighwater and the resetFlag is ignored.)^
5977** ^(Other parameters record only the highwater mark and not the current
5978** value.  For these latter parameters nothing is written into *pCurrent.)^
5979**
5980** ^The sqlite3_status() routine returns SQLITE_OK on success and a
5981** non-zero [error code] on failure.
5982**
5983** This routine is threadsafe but is not atomic.  This routine can be
5984** called while other threads are running the same or different SQLite
5985** interfaces.  However the values returned in *pCurrent and
5986** *pHighwater reflect the status of SQLite at different points in time
5987** and it is possible that another thread might change the parameter
5988** in between the times when *pCurrent and *pHighwater are written.
5989**
5990** See also: [sqlite3_db_status()]
5991*/
5992SQLITE_API int sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag);
5993
5994
5995/*
5996** CAPI3REF: Status Parameters
5997**
5998** These integer constants designate various run-time status parameters
5999** that can be returned by [sqlite3_status()].
6000**
6001** <dl>
6002** ^(<dt>SQLITE_STATUS_MEMORY_USED</dt>
6003** <dd>This parameter is the current amount of memory checked out
6004** using [sqlite3_malloc()], either directly or indirectly.  The
6005** figure includes calls made to [sqlite3_malloc()] by the application
6006** and internal memory usage by the SQLite library.  Scratch memory
6007** controlled by [SQLITE_CONFIG_SCRATCH] and auxiliary page-cache
6008** memory controlled by [SQLITE_CONFIG_PAGECACHE] is not included in
6009** this parameter.  The amount returned is the sum of the allocation
6010** sizes as reported by the xSize method in [sqlite3_mem_methods].</dd>)^
6011**
6012** ^(<dt>SQLITE_STATUS_MALLOC_SIZE</dt>
6013** <dd>This parameter records the largest memory allocation request
6014** handed to [sqlite3_malloc()] or [sqlite3_realloc()] (or their
6015** internal equivalents).  Only the value returned in the
6016** *pHighwater parameter to [sqlite3_status()] is of interest.
6017** The value written into the *pCurrent parameter is undefined.</dd>)^
6018**
6019** ^(<dt>SQLITE_STATUS_MALLOC_COUNT</dt>
6020** <dd>This parameter records the number of separate memory allocations
6021** currently checked out.</dd>)^
6022**
6023** ^(<dt>SQLITE_STATUS_PAGECACHE_USED</dt>
6024** <dd>This parameter returns the number of pages used out of the
6025** [pagecache memory allocator] that was configured using
6026** [SQLITE_CONFIG_PAGECACHE].  The
6027** value returned is in pages, not in bytes.</dd>)^
6028**
6029** ^(<dt>SQLITE_STATUS_PAGECACHE_OVERFLOW</dt>
6030** <dd>This parameter returns the number of bytes of page cache
6031** allocation which could not be satisfied by the [SQLITE_CONFIG_PAGECACHE]
6032** buffer and where forced to overflow to [sqlite3_malloc()].  The
6033** returned value includes allocations that overflowed because they
6034** where too large (they were larger than the "sz" parameter to
6035** [SQLITE_CONFIG_PAGECACHE]) and allocations that overflowed because
6036** no space was left in the page cache.</dd>)^
6037**
6038** ^(<dt>SQLITE_STATUS_PAGECACHE_SIZE</dt>
6039** <dd>This parameter records the largest memory allocation request
6040** handed to [pagecache memory allocator].  Only the value returned in the
6041** *pHighwater parameter to [sqlite3_status()] is of interest.
6042** The value written into the *pCurrent parameter is undefined.</dd>)^
6043**
6044** ^(<dt>SQLITE_STATUS_SCRATCH_USED</dt>
6045** <dd>This parameter returns the number of allocations used out of the
6046** [scratch memory allocator] configured using
6047** [SQLITE_CONFIG_SCRATCH].  The value returned is in allocations, not
6048** in bytes.  Since a single thread may only have one scratch allocation
6049** outstanding at time, this parameter also reports the number of threads
6050** using scratch memory at the same time.</dd>)^
6051**
6052** ^(<dt>SQLITE_STATUS_SCRATCH_OVERFLOW</dt>
6053** <dd>This parameter returns the number of bytes of scratch memory
6054** allocation which could not be satisfied by the [SQLITE_CONFIG_SCRATCH]
6055** buffer and where forced to overflow to [sqlite3_malloc()].  The values
6056** returned include overflows because the requested allocation was too
6057** larger (that is, because the requested allocation was larger than the
6058** "sz" parameter to [SQLITE_CONFIG_SCRATCH]) and because no scratch buffer
6059** slots were available.
6060** </dd>)^
6061**
6062** ^(<dt>SQLITE_STATUS_SCRATCH_SIZE</dt>
6063** <dd>This parameter records the largest memory allocation request
6064** handed to [scratch memory allocator].  Only the value returned in the
6065** *pHighwater parameter to [sqlite3_status()] is of interest.
6066** The value written into the *pCurrent parameter is undefined.</dd>)^
6067**
6068** ^(<dt>SQLITE_STATUS_PARSER_STACK</dt>
6069** <dd>This parameter records the deepest parser stack.  It is only
6070** meaningful if SQLite is compiled with [YYTRACKMAXSTACKDEPTH].</dd>)^
6071** </dl>
6072**
6073** New status parameters may be added from time to time.
6074*/
6075#define SQLITE_STATUS_MEMORY_USED          0
6076#define SQLITE_STATUS_PAGECACHE_USED       1
6077#define SQLITE_STATUS_PAGECACHE_OVERFLOW   2
6078#define SQLITE_STATUS_SCRATCH_USED         3
6079#define SQLITE_STATUS_SCRATCH_OVERFLOW     4
6080#define SQLITE_STATUS_MALLOC_SIZE          5
6081#define SQLITE_STATUS_PARSER_STACK         6
6082#define SQLITE_STATUS_PAGECACHE_SIZE       7
6083#define SQLITE_STATUS_SCRATCH_SIZE         8
6084#define SQLITE_STATUS_MALLOC_COUNT         9
6085
6086/*
6087** CAPI3REF: Database Connection Status
6088**
6089** ^This interface is used to retrieve runtime status information
6090** about a single [database connection].  ^The first argument is the
6091** database connection object to be interrogated.  ^The second argument
6092** is an integer constant, taken from the set of
6093** [SQLITE_DBSTATUS_LOOKASIDE_USED | SQLITE_DBSTATUS_*] macros, that
6094** determines the parameter to interrogate.  The set of
6095** [SQLITE_DBSTATUS_LOOKASIDE_USED | SQLITE_DBSTATUS_*] macros is likely
6096** to grow in future releases of SQLite.
6097**
6098** ^The current value of the requested parameter is written into *pCur
6099** and the highest instantaneous value is written into *pHiwtr.  ^If
6100** the resetFlg is true, then the highest instantaneous value is
6101** reset back down to the current value.
6102**
6103** ^The sqlite3_db_status() routine returns SQLITE_OK on success and a
6104** non-zero [error code] on failure.
6105**
6106** See also: [sqlite3_status()] and [sqlite3_stmt_status()].
6107*/
6108SQLITE_API int sqlite3_db_status(sqlite3*, int op, int *pCur, int *pHiwtr, int resetFlg);
6109
6110/*
6111** CAPI3REF: Status Parameters for database connections
6112**
6113** These constants are the available integer "verbs" that can be passed as
6114** the second argument to the [sqlite3_db_status()] interface.
6115**
6116** New verbs may be added in future releases of SQLite. Existing verbs
6117** might be discontinued. Applications should check the return code from
6118** [sqlite3_db_status()] to make sure that the call worked.
6119** The [sqlite3_db_status()] interface will return a non-zero error code
6120** if a discontinued or unsupported verb is invoked.
6121**
6122** <dl>
6123** ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_USED</dt>
6124** <dd>This parameter returns the number of lookaside memory slots currently
6125** checked out.</dd>)^
6126**
6127** ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_HIT</dt>
6128** <dd>This parameter returns the number malloc attempts that were
6129** satisfied using lookaside memory. Only the high-water value is meaningful;
6130** the current value is always zero.)^
6131**
6132** ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE</dt>
6133** <dd>This parameter returns the number malloc attempts that might have
6134** been satisfied using lookaside memory but failed due to the amount of
6135** memory requested being larger than the lookaside slot size.
6136** Only the high-water value is meaningful;
6137** the current value is always zero.)^
6138**
6139** ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL</dt>
6140** <dd>This parameter returns the number malloc attempts that might have
6141** been satisfied using lookaside memory but failed due to all lookaside
6142** memory already being in use.
6143** Only the high-water value is meaningful;
6144** the current value is always zero.)^
6145**
6146** ^(<dt>SQLITE_DBSTATUS_CACHE_USED</dt>
6147** <dd>This parameter returns the approximate number of of bytes of heap
6148** memory used by all pager caches associated with the database connection.)^
6149** ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_USED is always 0.
6150**
6151** ^(<dt>SQLITE_DBSTATUS_SCHEMA_USED</dt>
6152** <dd>This parameter returns the approximate number of of bytes of heap
6153** memory used to store the schema for all databases associated
6154** with the connection - main, temp, and any [ATTACH]-ed databases.)^
6155** ^The full amount of memory used by the schemas is reported, even if the
6156** schema memory is shared with other database connections due to
6157** [shared cache mode] being enabled.
6158** ^The highwater mark associated with SQLITE_DBSTATUS_SCHEMA_USED is always 0.
6159**
6160** ^(<dt>SQLITE_DBSTATUS_STMT_USED</dt>
6161** <dd>This parameter returns the approximate number of of bytes of heap
6162** and lookaside memory used by all prepared statements associated with
6163** the database connection.)^
6164** ^The highwater mark associated with SQLITE_DBSTATUS_STMT_USED is always 0.
6165** </dd>
6166** </dl>
6167*/
6168#define SQLITE_DBSTATUS_LOOKASIDE_USED       0
6169#define SQLITE_DBSTATUS_CACHE_USED           1
6170#define SQLITE_DBSTATUS_SCHEMA_USED          2
6171#define SQLITE_DBSTATUS_STMT_USED            3
6172#define SQLITE_DBSTATUS_LOOKASIDE_HIT        4
6173#define SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE  5
6174#define SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL  6
6175#define SQLITE_DBSTATUS_MAX                  6   /* Largest defined DBSTATUS */
6176
6177
6178/*
6179** CAPI3REF: Prepared Statement Status
6180**
6181** ^(Each prepared statement maintains various
6182** [SQLITE_STMTSTATUS_SORT | counters] that measure the number
6183** of times it has performed specific operations.)^  These counters can
6184** be used to monitor the performance characteristics of the prepared
6185** statements.  For example, if the number of table steps greatly exceeds
6186** the number of table searches or result rows, that would tend to indicate
6187** that the prepared statement is using a full table scan rather than
6188** an index.
6189**
6190** ^(This interface is used to retrieve and reset counter values from
6191** a [prepared statement].  The first argument is the prepared statement
6192** object to be interrogated.  The second argument
6193** is an integer code for a specific [SQLITE_STMTSTATUS_SORT | counter]
6194** to be interrogated.)^
6195** ^The current value of the requested counter is returned.
6196** ^If the resetFlg is true, then the counter is reset to zero after this
6197** interface call returns.
6198**
6199** See also: [sqlite3_status()] and [sqlite3_db_status()].
6200*/
6201SQLITE_API int sqlite3_stmt_status(sqlite3_stmt*, int op,int resetFlg);
6202
6203/*
6204** CAPI3REF: Status Parameters for prepared statements
6205**
6206** These preprocessor macros define integer codes that name counter
6207** values associated with the [sqlite3_stmt_status()] interface.
6208** The meanings of the various counters are as follows:
6209**
6210** <dl>
6211** <dt>SQLITE_STMTSTATUS_FULLSCAN_STEP</dt>
6212** <dd>^This is the number of times that SQLite has stepped forward in
6213** a table as part of a full table scan.  Large numbers for this counter
6214** may indicate opportunities for performance improvement through
6215** careful use of indices.</dd>
6216**
6217** <dt>SQLITE_STMTSTATUS_SORT</dt>
6218** <dd>^This is the number of sort operations that have occurred.
6219** A non-zero value in this counter may indicate an opportunity to
6220** improvement performance through careful use of indices.</dd>
6221**
6222** <dt>SQLITE_STMTSTATUS_AUTOINDEX</dt>
6223** <dd>^This is the number of rows inserted into transient indices that
6224** were created automatically in order to help joins run faster.
6225** A non-zero value in this counter may indicate an opportunity to
6226** improvement performance by adding permanent indices that do not
6227** need to be reinitialized each time the statement is run.</dd>
6228**
6229** </dl>
6230*/
6231#define SQLITE_STMTSTATUS_FULLSCAN_STEP     1
6232#define SQLITE_STMTSTATUS_SORT              2
6233#define SQLITE_STMTSTATUS_AUTOINDEX         3
6234
6235/*
6236** CAPI3REF: Custom Page Cache Object
6237**
6238** The sqlite3_pcache type is opaque.  It is implemented by
6239** the pluggable module.  The SQLite core has no knowledge of
6240** its size or internal structure and never deals with the
6241** sqlite3_pcache object except by holding and passing pointers
6242** to the object.
6243**
6244** See [sqlite3_pcache_methods] for additional information.
6245*/
6246typedef struct sqlite3_pcache sqlite3_pcache;
6247
6248/*
6249** CAPI3REF: Application Defined Page Cache.
6250** KEYWORDS: {page cache}
6251**
6252** ^(The [sqlite3_config]([SQLITE_CONFIG_PCACHE], ...) interface can
6253** register an alternative page cache implementation by passing in an
6254** instance of the sqlite3_pcache_methods structure.)^
6255** In many applications, most of the heap memory allocated by
6256** SQLite is used for the page cache.
6257** By implementing a
6258** custom page cache using this API, an application can better control
6259** the amount of memory consumed by SQLite, the way in which
6260** that memory is allocated and released, and the policies used to
6261** determine exactly which parts of a database file are cached and for
6262** how long.
6263**
6264** The alternative page cache mechanism is an
6265** extreme measure that is only needed by the most demanding applications.
6266** The built-in page cache is recommended for most uses.
6267**
6268** ^(The contents of the sqlite3_pcache_methods structure are copied to an
6269** internal buffer by SQLite within the call to [sqlite3_config].  Hence
6270** the application may discard the parameter after the call to
6271** [sqlite3_config()] returns.)^
6272**
6273** ^(The xInit() method is called once for each effective
6274** call to [sqlite3_initialize()])^
6275** (usually only once during the lifetime of the process). ^(The xInit()
6276** method is passed a copy of the sqlite3_pcache_methods.pArg value.)^
6277** The intent of the xInit() method is to set up global data structures
6278** required by the custom page cache implementation.
6279** ^(If the xInit() method is NULL, then the
6280** built-in default page cache is used instead of the application defined
6281** page cache.)^
6282**
6283** ^The xShutdown() method is called by [sqlite3_shutdown()].
6284** It can be used to clean up
6285** any outstanding resources before process shutdown, if required.
6286** ^The xShutdown() method may be NULL.
6287**
6288** ^SQLite automatically serializes calls to the xInit method,
6289** so the xInit method need not be threadsafe.  ^The
6290** xShutdown method is only called from [sqlite3_shutdown()] so it does
6291** not need to be threadsafe either.  All other methods must be threadsafe
6292** in multithreaded applications.
6293**
6294** ^SQLite will never invoke xInit() more than once without an intervening
6295** call to xShutdown().
6296**
6297** ^SQLite invokes the xCreate() method to construct a new cache instance.
6298** SQLite will typically create one cache instance for each open database file,
6299** though this is not guaranteed. ^The
6300** first parameter, szPage, is the size in bytes of the pages that must
6301** be allocated by the cache.  ^szPage will not be a power of two.  ^szPage
6302** will the page size of the database file that is to be cached plus an
6303** increment (here called "R") of less than 250.  SQLite will use the
6304** extra R bytes on each page to store metadata about the underlying
6305** database page on disk.  The value of R depends
6306** on the SQLite version, the target platform, and how SQLite was compiled.
6307** ^(R is constant for a particular build of SQLite. Except, there are two
6308** distinct values of R when SQLite is compiled with the proprietary
6309** ZIPVFS extension.)^  ^The second argument to
6310** xCreate(), bPurgeable, is true if the cache being created will
6311** be used to cache database pages of a file stored on disk, or
6312** false if it is used for an in-memory database. The cache implementation
6313** does not have to do anything special based with the value of bPurgeable;
6314** it is purely advisory.  ^On a cache where bPurgeable is false, SQLite will
6315** never invoke xUnpin() except to deliberately delete a page.
6316** ^In other words, calls to xUnpin() on a cache with bPurgeable set to
6317** false will always have the "discard" flag set to true.
6318** ^Hence, a cache created with bPurgeable false will
6319** never contain any unpinned pages.
6320**
6321** ^(The xCachesize() method may be called at any time by SQLite to set the
6322** suggested maximum cache-size (number of pages stored by) the cache
6323** instance passed as the first argument. This is the value configured using
6324** the SQLite "[PRAGMA cache_size]" command.)^  As with the bPurgeable
6325** parameter, the implementation is not required to do anything with this
6326** value; it is advisory only.
6327**
6328** The xPagecount() method must return the number of pages currently
6329** stored in the cache, both pinned and unpinned.
6330**
6331** The xFetch() method locates a page in the cache and returns a pointer to
6332** the page, or a NULL pointer.
6333** A "page", in this context, means a buffer of szPage bytes aligned at an
6334** 8-byte boundary. The page to be fetched is determined by the key. ^The
6335** mimimum key value is 1.  After it has been retrieved using xFetch, the page
6336** is considered to be "pinned".
6337**
6338** If the requested page is already in the page cache, then the page cache
6339** implementation must return a pointer to the page buffer with its content
6340** intact.  If the requested page is not already in the cache, then the
6341** cache implementation should use the value of the createFlag
6342** parameter to help it determined what action to take:
6343**
6344** <table border=1 width=85% align=center>
6345** <tr><th> createFlag <th> Behaviour when page is not already in cache
6346** <tr><td> 0 <td> Do not allocate a new page.  Return NULL.
6347** <tr><td> 1 <td> Allocate a new page if it easy and convenient to do so.
6348**                 Otherwise return NULL.
6349** <tr><td> 2 <td> Make every effort to allocate a new page.  Only return
6350**                 NULL if allocating a new page is effectively impossible.
6351** </table>
6352**
6353** ^(SQLite will normally invoke xFetch() with a createFlag of 0 or 1.  SQLite
6354** will only use a createFlag of 2 after a prior call with a createFlag of 1
6355** failed.)^  In between the to xFetch() calls, SQLite may
6356** attempt to unpin one or more cache pages by spilling the content of
6357** pinned pages to disk and synching the operating system disk cache.
6358**
6359** ^xUnpin() is called by SQLite with a pointer to a currently pinned page
6360** as its second argument.  If the third parameter, discard, is non-zero,
6361** then the page must be evicted from the cache.
6362** ^If the discard parameter is
6363** zero, then the page may be discarded or retained at the discretion of
6364** page cache implementation. ^The page cache implementation
6365** may choose to evict unpinned pages at any time.
6366**
6367** The cache must not perform any reference counting. A single
6368** call to xUnpin() unpins the page regardless of the number of prior calls
6369** to xFetch().
6370**
6371** The xRekey() method is used to change the key value associated with the
6372** page passed as the second argument. If the cache
6373** previously contains an entry associated with newKey, it must be
6374** discarded. ^Any prior cache entry associated with newKey is guaranteed not
6375** to be pinned.
6376**
6377** When SQLite calls the xTruncate() method, the cache must discard all
6378** existing cache entries with page numbers (keys) greater than or equal
6379** to the value of the iLimit parameter passed to xTruncate(). If any
6380** of these pages are pinned, they are implicitly unpinned, meaning that
6381** they can be safely discarded.
6382**
6383** ^The xDestroy() method is used to delete a cache allocated by xCreate().
6384** All resources associated with the specified cache should be freed. ^After
6385** calling the xDestroy() method, SQLite considers the [sqlite3_pcache*]
6386** handle invalid, and will not use it with any other sqlite3_pcache_methods
6387** functions.
6388*/
6389typedef struct sqlite3_pcache_methods sqlite3_pcache_methods;
6390struct sqlite3_pcache_methods {
6391  void *pArg;
6392  int (*xInit)(void*);
6393  void (*xShutdown)(void*);
6394  sqlite3_pcache *(*xCreate)(int szPage, int bPurgeable);
6395  void (*xCachesize)(sqlite3_pcache*, int nCachesize);
6396  int (*xPagecount)(sqlite3_pcache*);
6397  void *(*xFetch)(sqlite3_pcache*, unsigned key, int createFlag);
6398  void (*xUnpin)(sqlite3_pcache*, void*, int discard);
6399  void (*xRekey)(sqlite3_pcache*, void*, unsigned oldKey, unsigned newKey);
6400  void (*xTruncate)(sqlite3_pcache*, unsigned iLimit);
6401  void (*xDestroy)(sqlite3_pcache*);
6402};
6403
6404/*
6405** CAPI3REF: Online Backup Object
6406**
6407** The sqlite3_backup object records state information about an ongoing
6408** online backup operation.  ^The sqlite3_backup object is created by
6409** a call to [sqlite3_backup_init()] and is destroyed by a call to
6410** [sqlite3_backup_finish()].
6411**
6412** See Also: [Using the SQLite Online Backup API]
6413*/
6414typedef struct sqlite3_backup sqlite3_backup;
6415
6416/*
6417** CAPI3REF: Online Backup API.
6418**
6419** The backup API copies the content of one database into another.
6420** It is useful either for creating backups of databases or
6421** for copying in-memory databases to or from persistent files.
6422**
6423** See Also: [Using the SQLite Online Backup API]
6424**
6425** ^SQLite holds a write transaction open on the destination database file
6426** for the duration of the backup operation.
6427** ^The source database is read-locked only while it is being read;
6428** it is not locked continuously for the entire backup operation.
6429** ^Thus, the backup may be performed on a live source database without
6430** preventing other database connections from
6431** reading or writing to the source database while the backup is underway.
6432**
6433** ^(To perform a backup operation:
6434**   <ol>
6435**     <li><b>sqlite3_backup_init()</b> is called once to initialize the
6436**         backup,
6437**     <li><b>sqlite3_backup_step()</b> is called one or more times to transfer
6438**         the data between the two databases, and finally
6439**     <li><b>sqlite3_backup_finish()</b> is called to release all resources
6440**         associated with the backup operation.
6441**   </ol>)^
6442** There should be exactly one call to sqlite3_backup_finish() for each
6443** successful call to sqlite3_backup_init().
6444**
6445** <b>sqlite3_backup_init()</b>
6446**
6447** ^The D and N arguments to sqlite3_backup_init(D,N,S,M) are the
6448** [database connection] associated with the destination database
6449** and the database name, respectively.
6450** ^The database name is "main" for the main database, "temp" for the
6451** temporary database, or the name specified after the AS keyword in
6452** an [ATTACH] statement for an attached database.
6453** ^The S and M arguments passed to
6454** sqlite3_backup_init(D,N,S,M) identify the [database connection]
6455** and database name of the source database, respectively.
6456** ^The source and destination [database connections] (parameters S and D)
6457** must be different or else sqlite3_backup_init(D,N,S,M) will fail with
6458** an error.
6459**
6460** ^If an error occurs within sqlite3_backup_init(D,N,S,M), then NULL is
6461** returned and an error code and error message are stored in the
6462** destination [database connection] D.
6463** ^The error code and message for the failed call to sqlite3_backup_init()
6464** can be retrieved using the [sqlite3_errcode()], [sqlite3_errmsg()], and/or
6465** [sqlite3_errmsg16()] functions.
6466** ^A successful call to sqlite3_backup_init() returns a pointer to an
6467** [sqlite3_backup] object.
6468** ^The [sqlite3_backup] object may be used with the sqlite3_backup_step() and
6469** sqlite3_backup_finish() functions to perform the specified backup
6470** operation.
6471**
6472** <b>sqlite3_backup_step()</b>
6473**
6474** ^Function sqlite3_backup_step(B,N) will copy up to N pages between
6475** the source and destination databases specified by [sqlite3_backup] object B.
6476** ^If N is negative, all remaining source pages are copied.
6477** ^If sqlite3_backup_step(B,N) successfully copies N pages and there
6478** are still more pages to be copied, then the function returns [SQLITE_OK].
6479** ^If sqlite3_backup_step(B,N) successfully finishes copying all pages
6480** from source to destination, then it returns [SQLITE_DONE].
6481** ^If an error occurs while running sqlite3_backup_step(B,N),
6482** then an [error code] is returned. ^As well as [SQLITE_OK] and
6483** [SQLITE_DONE], a call to sqlite3_backup_step() may return [SQLITE_READONLY],
6484** [SQLITE_NOMEM], [SQLITE_BUSY], [SQLITE_LOCKED], or an
6485** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX] extended error code.
6486**
6487** ^(The sqlite3_backup_step() might return [SQLITE_READONLY] if
6488** <ol>
6489** <li> the destination database was opened read-only, or
6490** <li> the destination database is using write-ahead-log journaling
6491** and the destination and source page sizes differ, or
6492** <li> the destination database is an in-memory database and the
6493** destination and source page sizes differ.
6494** </ol>)^
6495**
6496** ^If sqlite3_backup_step() cannot obtain a required file-system lock, then
6497** the [sqlite3_busy_handler | busy-handler function]
6498** is invoked (if one is specified). ^If the
6499** busy-handler returns non-zero before the lock is available, then
6500** [SQLITE_BUSY] is returned to the caller. ^In this case the call to
6501** sqlite3_backup_step() can be retried later. ^If the source
6502** [database connection]
6503** is being used to write to the source database when sqlite3_backup_step()
6504** is called, then [SQLITE_LOCKED] is returned immediately. ^Again, in this
6505** case the call to sqlite3_backup_step() can be retried later on. ^(If
6506** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX], [SQLITE_NOMEM], or
6507** [SQLITE_READONLY] is returned, then
6508** there is no point in retrying the call to sqlite3_backup_step(). These
6509** errors are considered fatal.)^  The application must accept
6510** that the backup operation has failed and pass the backup operation handle
6511** to the sqlite3_backup_finish() to release associated resources.
6512**
6513** ^The first call to sqlite3_backup_step() obtains an exclusive lock
6514** on the destination file. ^The exclusive lock is not released until either
6515** sqlite3_backup_finish() is called or the backup operation is complete
6516** and sqlite3_backup_step() returns [SQLITE_DONE].  ^Every call to
6517** sqlite3_backup_step() obtains a [shared lock] on the source database that
6518** lasts for the duration of the sqlite3_backup_step() call.
6519** ^Because the source database is not locked between calls to
6520** sqlite3_backup_step(), the source database may be modified mid-way
6521** through the backup process.  ^If the source database is modified by an
6522** external process or via a database connection other than the one being
6523** used by the backup operation, then the backup will be automatically
6524** restarted by the next call to sqlite3_backup_step(). ^If the source
6525** database is modified by the using the same database connection as is used
6526** by the backup operation, then the backup database is automatically
6527** updated at the same time.
6528**
6529** <b>sqlite3_backup_finish()</b>
6530**
6531** When sqlite3_backup_step() has returned [SQLITE_DONE], or when the
6532** application wishes to abandon the backup operation, the application
6533** should destroy the [sqlite3_backup] by passing it to sqlite3_backup_finish().
6534** ^The sqlite3_backup_finish() interfaces releases all
6535** resources associated with the [sqlite3_backup] object.
6536** ^If sqlite3_backup_step() has not yet returned [SQLITE_DONE], then any
6537** active write-transaction on the destination database is rolled back.
6538** The [sqlite3_backup] object is invalid
6539** and may not be used following a call to sqlite3_backup_finish().
6540**
6541** ^The value returned by sqlite3_backup_finish is [SQLITE_OK] if no
6542** sqlite3_backup_step() errors occurred, regardless or whether or not
6543** sqlite3_backup_step() completed.
6544** ^If an out-of-memory condition or IO error occurred during any prior
6545** sqlite3_backup_step() call on the same [sqlite3_backup] object, then
6546** sqlite3_backup_finish() returns the corresponding [error code].
6547**
6548** ^A return of [SQLITE_BUSY] or [SQLITE_LOCKED] from sqlite3_backup_step()
6549** is not a permanent error and does not affect the return value of
6550** sqlite3_backup_finish().
6551**
6552** <b>sqlite3_backup_remaining(), sqlite3_backup_pagecount()</b>
6553**
6554** ^Each call to sqlite3_backup_step() sets two values inside
6555** the [sqlite3_backup] object: the number of pages still to be backed
6556** up and the total number of pages in the source database file.
6557** The sqlite3_backup_remaining() and sqlite3_backup_pagecount() interfaces
6558** retrieve these two values, respectively.
6559**
6560** ^The values returned by these functions are only updated by
6561** sqlite3_backup_step(). ^If the source database is modified during a backup
6562** operation, then the values are not updated to account for any extra
6563** pages that need to be updated or the size of the source database file
6564** changing.
6565**
6566** <b>Concurrent Usage of Database Handles</b>
6567**
6568** ^The source [database connection] may be used by the application for other
6569** purposes while a backup operation is underway or being initialized.
6570** ^If SQLite is compiled and configured to support threadsafe database
6571** connections, then the source database connection may be used concurrently
6572** from within other threads.
6573**
6574** However, the application must guarantee that the destination
6575** [database connection] is not passed to any other API (by any thread) after
6576** sqlite3_backup_init() is called and before the corresponding call to
6577** sqlite3_backup_finish().  SQLite does not currently check to see
6578** if the application incorrectly accesses the destination [database connection]
6579** and so no error code is reported, but the operations may malfunction
6580** nevertheless.  Use of the destination database connection while a
6581** backup is in progress might also also cause a mutex deadlock.
6582**
6583** If running in [shared cache mode], the application must
6584** guarantee that the shared cache used by the destination database
6585** is not accessed while the backup is running. In practice this means
6586** that the application must guarantee that the disk file being
6587** backed up to is not accessed by any connection within the process,
6588** not just the specific connection that was passed to sqlite3_backup_init().
6589**
6590** The [sqlite3_backup] object itself is partially threadsafe. Multiple
6591** threads may safely make multiple concurrent calls to sqlite3_backup_step().
6592** However, the sqlite3_backup_remaining() and sqlite3_backup_pagecount()
6593** APIs are not strictly speaking threadsafe. If they are invoked at the
6594** same time as another thread is invoking sqlite3_backup_step() it is
6595** possible that they return invalid values.
6596*/
6597SQLITE_API sqlite3_backup *sqlite3_backup_init(
6598  sqlite3 *pDest,                        /* Destination database handle */
6599  const char *zDestName,                 /* Destination database name */
6600  sqlite3 *pSource,                      /* Source database handle */
6601  const char *zSourceName                /* Source database name */
6602);
6603SQLITE_API int sqlite3_backup_step(sqlite3_backup *p, int nPage);
6604SQLITE_API int sqlite3_backup_finish(sqlite3_backup *p);
6605SQLITE_API int sqlite3_backup_remaining(sqlite3_backup *p);
6606SQLITE_API int sqlite3_backup_pagecount(sqlite3_backup *p);
6607
6608/*
6609** CAPI3REF: Unlock Notification
6610**
6611** ^When running in shared-cache mode, a database operation may fail with
6612** an [SQLITE_LOCKED] error if the required locks on the shared-cache or
6613** individual tables within the shared-cache cannot be obtained. See
6614** [SQLite Shared-Cache Mode] for a description of shared-cache locking.
6615** ^This API may be used to register a callback that SQLite will invoke
6616** when the connection currently holding the required lock relinquishes it.
6617** ^This API is only available if the library was compiled with the
6618** [SQLITE_ENABLE_UNLOCK_NOTIFY] C-preprocessor symbol defined.
6619**
6620** See Also: [Using the SQLite Unlock Notification Feature].
6621**
6622** ^Shared-cache locks are released when a database connection concludes
6623** its current transaction, either by committing it or rolling it back.
6624**
6625** ^When a connection (known as the blocked connection) fails to obtain a
6626** shared-cache lock and SQLITE_LOCKED is returned to the caller, the
6627** identity of the database connection (the blocking connection) that
6628** has locked the required resource is stored internally. ^After an
6629** application receives an SQLITE_LOCKED error, it may call the
6630** sqlite3_unlock_notify() method with the blocked connection handle as
6631** the first argument to register for a callback that will be invoked
6632** when the blocking connections current transaction is concluded. ^The
6633** callback is invoked from within the [sqlite3_step] or [sqlite3_close]
6634** call that concludes the blocking connections transaction.
6635**
6636** ^(If sqlite3_unlock_notify() is called in a multi-threaded application,
6637** there is a chance that the blocking connection will have already
6638** concluded its transaction by the time sqlite3_unlock_notify() is invoked.
6639** If this happens, then the specified callback is invoked immediately,
6640** from within the call to sqlite3_unlock_notify().)^
6641**
6642** ^If the blocked connection is attempting to obtain a write-lock on a
6643** shared-cache table, and more than one other connection currently holds
6644** a read-lock on the same table, then SQLite arbitrarily selects one of
6645** the other connections to use as the blocking connection.
6646**
6647** ^(There may be at most one unlock-notify callback registered by a
6648** blocked connection. If sqlite3_unlock_notify() is called when the
6649** blocked connection already has a registered unlock-notify callback,
6650** then the new callback replaces the old.)^ ^If sqlite3_unlock_notify() is
6651** called with a NULL pointer as its second argument, then any existing
6652** unlock-notify callback is canceled. ^The blocked connections
6653** unlock-notify callback may also be canceled by closing the blocked
6654** connection using [sqlite3_close()].
6655**
6656** The unlock-notify callback is not reentrant. If an application invokes
6657** any sqlite3_xxx API functions from within an unlock-notify callback, a
6658** crash or deadlock may be the result.
6659**
6660** ^Unless deadlock is detected (see below), sqlite3_unlock_notify() always
6661** returns SQLITE_OK.
6662**
6663** <b>Callback Invocation Details</b>
6664**
6665** When an unlock-notify callback is registered, the application provides a
6666** single void* pointer that is passed to the callback when it is invoked.
6667** However, the signature of the callback function allows SQLite to pass
6668** it an array of void* context pointers. The first argument passed to
6669** an unlock-notify callback is a pointer to an array of void* pointers,
6670** and the second is the number of entries in the array.
6671**
6672** When a blocking connections transaction is concluded, there may be
6673** more than one blocked connection that has registered for an unlock-notify
6674** callback. ^If two or more such blocked connections have specified the
6675** same callback function, then instead of invoking the callback function
6676** multiple times, it is invoked once with the set of void* context pointers
6677** specified by the blocked connections bundled together into an array.
6678** This gives the application an opportunity to prioritize any actions
6679** related to the set of unblocked database connections.
6680**
6681** <b>Deadlock Detection</b>
6682**
6683** Assuming that after registering for an unlock-notify callback a
6684** database waits for the callback to be issued before taking any further
6685** action (a reasonable assumption), then using this API may cause the
6686** application to deadlock. For example, if connection X is waiting for
6687** connection Y's transaction to be concluded, and similarly connection
6688** Y is waiting on connection X's transaction, then neither connection
6689** will proceed and the system may remain deadlocked indefinitely.
6690**
6691** To avoid this scenario, the sqlite3_unlock_notify() performs deadlock
6692** detection. ^If a given call to sqlite3_unlock_notify() would put the
6693** system in a deadlocked state, then SQLITE_LOCKED is returned and no
6694** unlock-notify callback is registered. The system is said to be in
6695** a deadlocked state if connection A has registered for an unlock-notify
6696** callback on the conclusion of connection B's transaction, and connection
6697** B has itself registered for an unlock-notify callback when connection
6698** A's transaction is concluded. ^Indirect deadlock is also detected, so
6699** the system is also considered to be deadlocked if connection B has
6700** registered for an unlock-notify callback on the conclusion of connection
6701** C's transaction, where connection C is waiting on connection A. ^Any
6702** number of levels of indirection are allowed.
6703**
6704** <b>The "DROP TABLE" Exception</b>
6705**
6706** When a call to [sqlite3_step()] returns SQLITE_LOCKED, it is almost
6707** always appropriate to call sqlite3_unlock_notify(). There is however,
6708** one exception. When executing a "DROP TABLE" or "DROP INDEX" statement,
6709** SQLite checks if there are any currently executing SELECT statements
6710** that belong to the same connection. If there are, SQLITE_LOCKED is
6711** returned. In this case there is no "blocking connection", so invoking
6712** sqlite3_unlock_notify() results in the unlock-notify callback being
6713** invoked immediately. If the application then re-attempts the "DROP TABLE"
6714** or "DROP INDEX" query, an infinite loop might be the result.
6715**
6716** One way around this problem is to check the extended error code returned
6717** by an sqlite3_step() call. ^(If there is a blocking connection, then the
6718** extended error code is set to SQLITE_LOCKED_SHAREDCACHE. Otherwise, in
6719** the special "DROP TABLE/INDEX" case, the extended error code is just
6720** SQLITE_LOCKED.)^
6721*/
6722SQLITE_API int sqlite3_unlock_notify(
6723  sqlite3 *pBlocked,                          /* Waiting connection */
6724  void (*xNotify)(void **apArg, int nArg),    /* Callback function to invoke */
6725  void *pNotifyArg                            /* Argument to pass to xNotify */
6726);
6727
6728
6729/*
6730** CAPI3REF: String Comparison
6731**
6732** ^The [sqlite3_strnicmp()] API allows applications and extensions to
6733** compare the contents of two buffers containing UTF-8 strings in a
6734** case-independent fashion, using the same definition of case independence
6735** that SQLite uses internally when comparing identifiers.
6736*/
6737SQLITE_API int sqlite3_strnicmp(const char *, const char *, int);
6738
6739/*
6740** CAPI3REF: Error Logging Interface
6741**
6742** ^The [sqlite3_log()] interface writes a message into the error log
6743** established by the [SQLITE_CONFIG_LOG] option to [sqlite3_config()].
6744** ^If logging is enabled, the zFormat string and subsequent arguments are
6745** used with [sqlite3_snprintf()] to generate the final output string.
6746**
6747** The sqlite3_log() interface is intended for use by extensions such as
6748** virtual tables, collating functions, and SQL functions.  While there is
6749** nothing to prevent an application from calling sqlite3_log(), doing so
6750** is considered bad form.
6751**
6752** The zFormat string must not be NULL.
6753**
6754** To avoid deadlocks and other threading problems, the sqlite3_log() routine
6755** will not use dynamically allocated memory.  The log message is stored in
6756** a fixed-length buffer on the stack.  If the log message is longer than
6757** a few hundred characters, it will be truncated to the length of the
6758** buffer.
6759*/
6760SQLITE_API void sqlite3_log(int iErrCode, const char *zFormat, ...);
6761
6762/*
6763** CAPI3REF: Write-Ahead Log Commit Hook
6764**
6765** ^The [sqlite3_wal_hook()] function is used to register a callback that
6766** will be invoked each time a database connection commits data to a
6767** [write-ahead log] (i.e. whenever a transaction is committed in
6768** [journal_mode | journal_mode=WAL mode]).
6769**
6770** ^The callback is invoked by SQLite after the commit has taken place and
6771** the associated write-lock on the database released, so the implementation
6772** may read, write or [checkpoint] the database as required.
6773**
6774** ^The first parameter passed to the callback function when it is invoked
6775** is a copy of the third parameter passed to sqlite3_wal_hook() when
6776** registering the callback. ^The second is a copy of the database handle.
6777** ^The third parameter is the name of the database that was written to -
6778** either "main" or the name of an [ATTACH]-ed database. ^The fourth parameter
6779** is the number of pages currently in the write-ahead log file,
6780** including those that were just committed.
6781**
6782** The callback function should normally return [SQLITE_OK].  ^If an error
6783** code is returned, that error will propagate back up through the
6784** SQLite code base to cause the statement that provoked the callback
6785** to report an error, though the commit will have still occurred. If the
6786** callback returns [SQLITE_ROW] or [SQLITE_DONE], or if it returns a value
6787** that does not correspond to any valid SQLite error code, the results
6788** are undefined.
6789**
6790** A single database handle may have at most a single write-ahead log callback
6791** registered at one time. ^Calling [sqlite3_wal_hook()] replaces any
6792** previously registered write-ahead log callback. ^Note that the
6793** [sqlite3_wal_autocheckpoint()] interface and the
6794** [wal_autocheckpoint pragma] both invoke [sqlite3_wal_hook()] and will
6795** those overwrite any prior [sqlite3_wal_hook()] settings.
6796*/
6797SQLITE_API void *sqlite3_wal_hook(
6798  sqlite3*,
6799  int(*)(void *,sqlite3*,const char*,int),
6800  void*
6801);
6802
6803/*
6804** CAPI3REF: Configure an auto-checkpoint
6805**
6806** ^The [sqlite3_wal_autocheckpoint(D,N)] is a wrapper around
6807** [sqlite3_wal_hook()] that causes any database on [database connection] D
6808** to automatically [checkpoint]
6809** after committing a transaction if there are N or
6810** more frames in the [write-ahead log] file.  ^Passing zero or
6811** a negative value as the nFrame parameter disables automatic
6812** checkpoints entirely.
6813**
6814** ^The callback registered by this function replaces any existing callback
6815** registered using [sqlite3_wal_hook()].  ^Likewise, registering a callback
6816** using [sqlite3_wal_hook()] disables the automatic checkpoint mechanism
6817** configured by this function.
6818**
6819** ^The [wal_autocheckpoint pragma] can be used to invoke this interface
6820** from SQL.
6821**
6822** ^Every new [database connection] defaults to having the auto-checkpoint
6823** enabled with a threshold of 1000 or [SQLITE_DEFAULT_WAL_AUTOCHECKPOINT]
6824** pages.  The use of this interface
6825** is only necessary if the default setting is found to be suboptimal
6826** for a particular application.
6827*/
6828SQLITE_API int sqlite3_wal_autocheckpoint(sqlite3 *db, int N);
6829
6830/*
6831** CAPI3REF: Checkpoint a database
6832**
6833** ^The [sqlite3_wal_checkpoint(D,X)] interface causes database named X
6834** on [database connection] D to be [checkpointed].  ^If X is NULL or an
6835** empty string, then a checkpoint is run on all databases of
6836** connection D.  ^If the database connection D is not in
6837** [WAL | write-ahead log mode] then this interface is a harmless no-op.
6838**
6839** ^The [wal_checkpoint pragma] can be used to invoke this interface
6840** from SQL.  ^The [sqlite3_wal_autocheckpoint()] interface and the
6841** [wal_autocheckpoint pragma] can be used to cause this interface to be
6842** run whenever the WAL reaches a certain size threshold.
6843**
6844** See also: [sqlite3_wal_checkpoint_v2()]
6845*/
6846SQLITE_API int sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb);
6847
6848/*
6849** CAPI3REF: Checkpoint a database
6850**
6851** Run a checkpoint operation on WAL database zDb attached to database
6852** handle db. The specific operation is determined by the value of the
6853** eMode parameter:
6854**
6855** <dl>
6856** <dt>SQLITE_CHECKPOINT_PASSIVE<dd>
6857**   Checkpoint as many frames as possible without waiting for any database
6858**   readers or writers to finish. Sync the db file if all frames in the log
6859**   are checkpointed. This mode is the same as calling
6860**   sqlite3_wal_checkpoint(). The busy-handler callback is never invoked.
6861**
6862** <dt>SQLITE_CHECKPOINT_FULL<dd>
6863**   This mode blocks (calls the busy-handler callback) until there is no
6864**   database writer and all readers are reading from the most recent database
6865**   snapshot. It then checkpoints all frames in the log file and syncs the
6866**   database file. This call blocks database writers while it is running,
6867**   but not database readers.
6868**
6869** <dt>SQLITE_CHECKPOINT_RESTART<dd>
6870**   This mode works the same way as SQLITE_CHECKPOINT_FULL, except after
6871**   checkpointing the log file it blocks (calls the busy-handler callback)
6872**   until all readers are reading from the database file only. This ensures
6873**   that the next client to write to the database file restarts the log file
6874**   from the beginning. This call blocks database writers while it is running,
6875**   but not database readers.
6876** </dl>
6877**
6878** If pnLog is not NULL, then *pnLog is set to the total number of frames in
6879** the log file before returning. If pnCkpt is not NULL, then *pnCkpt is set to
6880** the total number of checkpointed frames (including any that were already
6881** checkpointed when this function is called). *pnLog and *pnCkpt may be
6882** populated even if sqlite3_wal_checkpoint_v2() returns other than SQLITE_OK.
6883** If no values are available because of an error, they are both set to -1
6884** before returning to communicate this to the caller.
6885**
6886** All calls obtain an exclusive "checkpoint" lock on the database file. If
6887** any other process is running a checkpoint operation at the same time, the
6888** lock cannot be obtained and SQLITE_BUSY is returned. Even if there is a
6889** busy-handler configured, it will not be invoked in this case.
6890**
6891** The SQLITE_CHECKPOINT_FULL and RESTART modes also obtain the exclusive
6892** "writer" lock on the database file. If the writer lock cannot be obtained
6893** immediately, and a busy-handler is configured, it is invoked and the writer
6894** lock retried until either the busy-handler returns 0 or the lock is
6895** successfully obtained. The busy-handler is also invoked while waiting for
6896** database readers as described above. If the busy-handler returns 0 before
6897** the writer lock is obtained or while waiting for database readers, the
6898** checkpoint operation proceeds from that point in the same way as
6899** SQLITE_CHECKPOINT_PASSIVE - checkpointing as many frames as possible
6900** without blocking any further. SQLITE_BUSY is returned in this case.
6901**
6902** If parameter zDb is NULL or points to a zero length string, then the
6903** specified operation is attempted on all WAL databases. In this case the
6904** values written to output parameters *pnLog and *pnCkpt are undefined. If
6905** an SQLITE_BUSY error is encountered when processing one or more of the
6906** attached WAL databases, the operation is still attempted on any remaining
6907** attached databases and SQLITE_BUSY is returned to the caller. If any other
6908** error occurs while processing an attached database, processing is abandoned
6909** and the error code returned to the caller immediately. If no error
6910** (SQLITE_BUSY or otherwise) is encountered while processing the attached
6911** databases, SQLITE_OK is returned.
6912**
6913** If database zDb is the name of an attached database that is not in WAL
6914** mode, SQLITE_OK is returned and both *pnLog and *pnCkpt set to -1. If
6915** zDb is not NULL (or a zero length string) and is not the name of any
6916** attached database, SQLITE_ERROR is returned to the caller.
6917*/
6918SQLITE_API int sqlite3_wal_checkpoint_v2(
6919  sqlite3 *db,                    /* Database handle */
6920  const char *zDb,                /* Name of attached database (or NULL) */
6921  int eMode,                      /* SQLITE_CHECKPOINT_* value */
6922  int *pnLog,                     /* OUT: Size of WAL log in frames */
6923  int *pnCkpt                     /* OUT: Total number of frames checkpointed */
6924);
6925
6926/*
6927** CAPI3REF: Checkpoint operation parameters
6928**
6929** These constants can be used as the 3rd parameter to
6930** [sqlite3_wal_checkpoint_v2()].  See the [sqlite3_wal_checkpoint_v2()]
6931** documentation for additional information about the meaning and use of
6932** each of these values.
6933*/
6934#define SQLITE_CHECKPOINT_PASSIVE 0
6935#define SQLITE_CHECKPOINT_FULL    1
6936#define SQLITE_CHECKPOINT_RESTART 2
6937
6938
6939/* Begin recover.patch for Chromium */
6940/*
6941** Call to initialize the recover virtual-table modules (see recover.c).
6942**
6943** This could be loaded by default in main.c, but that would make the
6944** virtual table available to Web SQL.  Breaking it out allows only
6945** selected users to enable it (currently sql/recovery.cc).
6946*/
6947int recoverVtableInit(sqlite3 *db);
6948/* End recover.patch for Chromium */
6949
6950/*
6951** Undo the hack that converts floating point types to integer for
6952** builds on processors without floating point support.
6953*/
6954#ifdef SQLITE_OMIT_FLOATING_POINT
6955# undef double
6956#endif
6957
6958#if 0
6959}  /* End of the 'extern "C"' block */
6960#endif
6961#endif
6962
6963/*
6964** 2010 August 30
6965**
6966** The author disclaims copyright to this source code.  In place of
6967** a legal notice, here is a blessing:
6968**
6969**    May you do good and not evil.
6970**    May you find forgiveness for yourself and forgive others.
6971**    May you share freely, never taking more than you give.
6972**
6973*************************************************************************
6974*/
6975
6976#ifndef _SQLITE3RTREE_H_
6977#define _SQLITE3RTREE_H_
6978
6979
6980#if 0
6981extern "C" {
6982#endif
6983
6984typedef struct sqlite3_rtree_geometry sqlite3_rtree_geometry;
6985
6986/*
6987** Register a geometry callback named zGeom that can be used as part of an
6988** R-Tree geometry query as follows:
6989**
6990**   SELECT ... FROM <rtree> WHERE <rtree col> MATCH $zGeom(... params ...)
6991*/
6992SQLITE_API int sqlite3_rtree_geometry_callback(
6993  sqlite3 *db,
6994  const char *zGeom,
6995  int (*xGeom)(sqlite3_rtree_geometry *, int nCoord, double *aCoord, int *pRes),
6996  void *pContext
6997);
6998
6999
7000/*
7001** A pointer to a structure of the following type is passed as the first
7002** argument to callbacks registered using rtree_geometry_callback().
7003*/
7004struct sqlite3_rtree_geometry {
7005  void *pContext;                 /* Copy of pContext passed to s_r_g_c() */
7006  int nParam;                     /* Size of array aParam[] */
7007  double *aParam;                 /* Parameters passed to SQL geom function */
7008  void *pUser;                    /* Callback implementation user data */
7009  void (*xDelUser)(void *);       /* Called by SQLite to clean up pUser */
7010};
7011
7012
7013#if 0
7014}  /* end of the 'extern "C"' block */
7015#endif
7016
7017#endif  /* ifndef _SQLITE3RTREE_H_ */
7018
7019
7020/************** End of sqlite3.h *********************************************/
7021/************** Continuing where we left off in sqliteInt.h ******************/
7022/************** Include hash.h in the middle of sqliteInt.h ******************/
7023/************** Begin file hash.h ********************************************/
7024/*
7025** 2001 September 22
7026**
7027** The author disclaims copyright to this source code.  In place of
7028** a legal notice, here is a blessing:
7029**
7030**    May you do good and not evil.
7031**    May you find forgiveness for yourself and forgive others.
7032**    May you share freely, never taking more than you give.
7033**
7034*************************************************************************
7035** This is the header file for the generic hash-table implemenation
7036** used in SQLite.
7037*/
7038#ifndef _SQLITE_HASH_H_
7039#define _SQLITE_HASH_H_
7040
7041/* Forward declarations of structures. */
7042typedef struct Hash Hash;
7043typedef struct HashElem HashElem;
7044
7045/* A complete hash table is an instance of the following structure.
7046** The internals of this structure are intended to be opaque -- client
7047** code should not attempt to access or modify the fields of this structure
7048** directly.  Change this structure only by using the routines below.
7049** However, some of the "procedures" and "functions" for modifying and
7050** accessing this structure are really macros, so we can't really make
7051** this structure opaque.
7052**
7053** All elements of the hash table are on a single doubly-linked list.
7054** Hash.first points to the head of this list.
7055**
7056** There are Hash.htsize buckets.  Each bucket points to a spot in
7057** the global doubly-linked list.  The contents of the bucket are the
7058** element pointed to plus the next _ht.count-1 elements in the list.
7059**
7060** Hash.htsize and Hash.ht may be zero.  In that case lookup is done
7061** by a linear search of the global list.  For small tables, the
7062** Hash.ht table is never allocated because if there are few elements
7063** in the table, it is faster to do a linear search than to manage
7064** the hash table.
7065*/
7066struct Hash {
7067  unsigned int htsize;      /* Number of buckets in the hash table */
7068  unsigned int count;       /* Number of entries in this table */
7069  HashElem *first;          /* The first element of the array */
7070  struct _ht {              /* the hash table */
7071    int count;                 /* Number of entries with this hash */
7072    HashElem *chain;           /* Pointer to first entry with this hash */
7073  } *ht;
7074};
7075
7076/* Each element in the hash table is an instance of the following
7077** structure.  All elements are stored on a single doubly-linked list.
7078**
7079** Again, this structure is intended to be opaque, but it can't really
7080** be opaque because it is used by macros.
7081*/
7082struct HashElem {
7083  HashElem *next, *prev;       /* Next and previous elements in the table */
7084  void *data;                  /* Data associated with this element */
7085  const char *pKey; int nKey;  /* Key associated with this element */
7086};
7087
7088/*
7089** Access routines.  To delete, insert a NULL pointer.
7090*/
7091SQLITE_PRIVATE void sqlite3HashInit(Hash*);
7092SQLITE_PRIVATE void *sqlite3HashInsert(Hash*, const char *pKey, int nKey, void *pData);
7093SQLITE_PRIVATE void *sqlite3HashFind(const Hash*, const char *pKey, int nKey);
7094SQLITE_PRIVATE void sqlite3HashClear(Hash*);
7095
7096/*
7097** Macros for looping over all elements of a hash table.  The idiom is
7098** like this:
7099**
7100**   Hash h;
7101**   HashElem *p;
7102**   ...
7103**   for(p=sqliteHashFirst(&h); p; p=sqliteHashNext(p)){
7104**     SomeStructure *pData = sqliteHashData(p);
7105**     // do something with pData
7106**   }
7107*/
7108#define sqliteHashFirst(H)  ((H)->first)
7109#define sqliteHashNext(E)   ((E)->next)
7110#define sqliteHashData(E)   ((E)->data)
7111/* #define sqliteHashKey(E)    ((E)->pKey) // NOT USED */
7112/* #define sqliteHashKeysize(E) ((E)->nKey)  // NOT USED */
7113
7114/*
7115** Number of entries in a hash table
7116*/
7117/* #define sqliteHashCount(H)  ((H)->count) // NOT USED */
7118
7119#endif /* _SQLITE_HASH_H_ */
7120
7121/************** End of hash.h ************************************************/
7122/************** Continuing where we left off in sqliteInt.h ******************/
7123/************** Include parse.h in the middle of sqliteInt.h *****************/
7124/************** Begin file parse.h *******************************************/
7125#define TK_SEMI                            1
7126#define TK_EXPLAIN                         2
7127#define TK_QUERY                           3
7128#define TK_PLAN                            4
7129#define TK_BEGIN                           5
7130#define TK_TRANSACTION                     6
7131#define TK_DEFERRED                        7
7132#define TK_IMMEDIATE                       8
7133#define TK_EXCLUSIVE                       9
7134#define TK_COMMIT                         10
7135#define TK_END                            11
7136#define TK_ROLLBACK                       12
7137#define TK_SAVEPOINT                      13
7138#define TK_RELEASE                        14
7139#define TK_TO                             15
7140#define TK_TABLE                          16
7141#define TK_CREATE                         17
7142#define TK_IF                             18
7143#define TK_NOT                            19
7144#define TK_EXISTS                         20
7145#define TK_TEMP                           21
7146#define TK_LP                             22
7147#define TK_RP                             23
7148#define TK_AS                             24
7149#define TK_COMMA                          25
7150#define TK_ID                             26
7151#define TK_INDEXED                        27
7152#define TK_ABORT                          28
7153#define TK_ACTION                         29
7154#define TK_AFTER                          30
7155#define TK_ANALYZE                        31
7156#define TK_ASC                            32
7157#define TK_ATTACH                         33
7158#define TK_BEFORE                         34
7159#define TK_BY                             35
7160#define TK_CASCADE                        36
7161#define TK_CAST                           37
7162#define TK_COLUMNKW                       38
7163#define TK_CONFLICT                       39
7164#define TK_DATABASE                       40
7165#define TK_DESC                           41
7166#define TK_DETACH                         42
7167#define TK_EACH                           43
7168#define TK_FAIL                           44
7169#define TK_FOR                            45
7170#define TK_IGNORE                         46
7171#define TK_INITIALLY                      47
7172#define TK_INSTEAD                        48
7173#define TK_LIKE_KW                        49
7174#define TK_MATCH                          50
7175#define TK_NO                             51
7176#define TK_KEY                            52
7177#define TK_OF                             53
7178#define TK_OFFSET                         54
7179#define TK_PRAGMA                         55
7180#define TK_RAISE                          56
7181#define TK_REPLACE                        57
7182#define TK_RESTRICT                       58
7183#define TK_ROW                            59
7184#define TK_TRIGGER                        60
7185#define TK_VACUUM                         61
7186#define TK_VIEW                           62
7187#define TK_VIRTUAL                        63
7188#define TK_REINDEX                        64
7189#define TK_RENAME                         65
7190#define TK_CTIME_KW                       66
7191#define TK_ANY                            67
7192#define TK_OR                             68
7193#define TK_AND                            69
7194#define TK_IS                             70
7195#define TK_BETWEEN                        71
7196#define TK_IN                             72
7197#define TK_ISNULL                         73
7198#define TK_NOTNULL                        74
7199#define TK_NE                             75
7200#define TK_EQ                             76
7201#define TK_GT                             77
7202#define TK_LE                             78
7203#define TK_LT                             79
7204#define TK_GE                             80
7205#define TK_ESCAPE                         81
7206#define TK_BITAND                         82
7207#define TK_BITOR                          83
7208#define TK_LSHIFT                         84
7209#define TK_RSHIFT                         85
7210#define TK_PLUS                           86
7211#define TK_MINUS                          87
7212#define TK_STAR                           88
7213#define TK_SLASH                          89
7214#define TK_REM                            90
7215#define TK_CONCAT                         91
7216#define TK_COLLATE                        92
7217#define TK_BITNOT                         93
7218#define TK_STRING                         94
7219#define TK_JOIN_KW                        95
7220#define TK_CONSTRAINT                     96
7221#define TK_DEFAULT                        97
7222#define TK_NULL                           98
7223#define TK_PRIMARY                        99
7224#define TK_UNIQUE                         100
7225#define TK_CHECK                          101
7226#define TK_REFERENCES                     102
7227#define TK_AUTOINCR                       103
7228#define TK_ON                             104
7229#define TK_INSERT                         105
7230#define TK_DELETE                         106
7231#define TK_UPDATE                         107
7232#define TK_SET                            108
7233#define TK_DEFERRABLE                     109
7234#define TK_FOREIGN                        110
7235#define TK_DROP                           111
7236#define TK_UNION                          112
7237#define TK_ALL                            113
7238#define TK_EXCEPT                         114
7239#define TK_INTERSECT                      115
7240#define TK_SELECT                         116
7241#define TK_DISTINCT                       117
7242#define TK_DOT                            118
7243#define TK_FROM                           119
7244#define TK_JOIN                           120
7245#define TK_USING                          121
7246#define TK_ORDER                          122
7247#define TK_GROUP                          123
7248#define TK_HAVING                         124
7249#define TK_LIMIT                          125
7250#define TK_WHERE                          126
7251#define TK_INTO                           127
7252#define TK_VALUES                         128
7253#define TK_INTEGER                        129
7254#define TK_FLOAT                          130
7255#define TK_BLOB                           131
7256#define TK_REGISTER                       132
7257#define TK_VARIABLE                       133
7258#define TK_CASE                           134
7259#define TK_WHEN                           135
7260#define TK_THEN                           136
7261#define TK_ELSE                           137
7262#define TK_INDEX                          138
7263#define TK_ALTER                          139
7264#define TK_ADD                            140
7265#define TK_TO_TEXT                        141
7266#define TK_TO_BLOB                        142
7267#define TK_TO_NUMERIC                     143
7268#define TK_TO_INT                         144
7269#define TK_TO_REAL                        145
7270#define TK_ISNOT                          146
7271#define TK_END_OF_FILE                    147
7272#define TK_ILLEGAL                        148
7273#define TK_SPACE                          149
7274#define TK_UNCLOSED_STRING                150
7275#define TK_FUNCTION                       151
7276#define TK_COLUMN                         152
7277#define TK_AGG_FUNCTION                   153
7278#define TK_AGG_COLUMN                     154
7279#define TK_CONST_FUNC                     155
7280#define TK_UMINUS                         156
7281#define TK_UPLUS                          157
7282
7283/************** End of parse.h ***********************************************/
7284/************** Continuing where we left off in sqliteInt.h ******************/
7285#include <stdio.h>
7286#include <stdlib.h>
7287#include <string.h>
7288#include <assert.h>
7289#include <stddef.h>
7290
7291/*
7292** If compiling for a processor that lacks floating point support,
7293** substitute integer for floating-point
7294*/
7295#ifdef SQLITE_OMIT_FLOATING_POINT
7296# define double sqlite_int64
7297# define float sqlite_int64
7298# define LONGDOUBLE_TYPE sqlite_int64
7299# ifndef SQLITE_BIG_DBL
7300#   define SQLITE_BIG_DBL (((sqlite3_int64)1)<<50)
7301# endif
7302# define SQLITE_OMIT_DATETIME_FUNCS 1
7303# define SQLITE_OMIT_TRACE 1
7304# undef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
7305# undef SQLITE_HAVE_ISNAN
7306#endif
7307#ifndef SQLITE_BIG_DBL
7308# define SQLITE_BIG_DBL (1e99)
7309#endif
7310
7311/*
7312** OMIT_TEMPDB is set to 1 if SQLITE_OMIT_TEMPDB is defined, or 0
7313** afterward. Having this macro allows us to cause the C compiler
7314** to omit code used by TEMP tables without messy #ifndef statements.
7315*/
7316#ifdef SQLITE_OMIT_TEMPDB
7317#define OMIT_TEMPDB 1
7318#else
7319#define OMIT_TEMPDB 0
7320#endif
7321
7322/*
7323** The "file format" number is an integer that is incremented whenever
7324** the VDBE-level file format changes.  The following macros define the
7325** the default file format for new databases and the maximum file format
7326** that the library can read.
7327*/
7328#define SQLITE_MAX_FILE_FORMAT 4
7329#ifndef SQLITE_DEFAULT_FILE_FORMAT
7330# define SQLITE_DEFAULT_FILE_FORMAT 1
7331#endif
7332
7333/*
7334** Determine whether triggers are recursive by default.  This can be
7335** changed at run-time using a pragma.
7336*/
7337#ifndef SQLITE_DEFAULT_RECURSIVE_TRIGGERS
7338# define SQLITE_DEFAULT_RECURSIVE_TRIGGERS 0
7339#endif
7340
7341/*
7342** Provide a default value for SQLITE_TEMP_STORE in case it is not specified
7343** on the command-line
7344*/
7345#ifndef SQLITE_TEMP_STORE
7346# define SQLITE_TEMP_STORE 1
7347#endif
7348
7349/*
7350** GCC does not define the offsetof() macro so we'll have to do it
7351** ourselves.
7352*/
7353#ifndef offsetof
7354#define offsetof(STRUCTURE,FIELD) ((int)((char*)&((STRUCTURE*)0)->FIELD))
7355#endif
7356
7357/*
7358** Check to see if this machine uses EBCDIC.  (Yes, believe it or
7359** not, there are still machines out there that use EBCDIC.)
7360*/
7361#if 'A' == '\301'
7362# define SQLITE_EBCDIC 1
7363#else
7364# define SQLITE_ASCII 1
7365#endif
7366
7367/*
7368** Integers of known sizes.  These typedefs might change for architectures
7369** where the sizes very.  Preprocessor macros are available so that the
7370** types can be conveniently redefined at compile-type.  Like this:
7371**
7372**         cc '-DUINTPTR_TYPE=long long int' ...
7373*/
7374#ifndef UINT32_TYPE
7375# ifdef HAVE_UINT32_T
7376#  define UINT32_TYPE uint32_t
7377# else
7378#  define UINT32_TYPE unsigned int
7379# endif
7380#endif
7381#ifndef UINT16_TYPE
7382# ifdef HAVE_UINT16_T
7383#  define UINT16_TYPE uint16_t
7384# else
7385#  define UINT16_TYPE unsigned short int
7386# endif
7387#endif
7388#ifndef INT16_TYPE
7389# ifdef HAVE_INT16_T
7390#  define INT16_TYPE int16_t
7391# else
7392#  define INT16_TYPE short int
7393# endif
7394#endif
7395#ifndef UINT8_TYPE
7396# ifdef HAVE_UINT8_T
7397#  define UINT8_TYPE uint8_t
7398# else
7399#  define UINT8_TYPE unsigned char
7400# endif
7401#endif
7402#ifndef INT8_TYPE
7403# ifdef HAVE_INT8_T
7404#  define INT8_TYPE int8_t
7405# else
7406#  define INT8_TYPE signed char
7407# endif
7408#endif
7409#ifndef LONGDOUBLE_TYPE
7410# define LONGDOUBLE_TYPE long double
7411#endif
7412typedef sqlite_int64 i64;          /* 8-byte signed integer */
7413typedef sqlite_uint64 u64;         /* 8-byte unsigned integer */
7414typedef UINT32_TYPE u32;           /* 4-byte unsigned integer */
7415typedef UINT16_TYPE u16;           /* 2-byte unsigned integer */
7416typedef INT16_TYPE i16;            /* 2-byte signed integer */
7417typedef UINT8_TYPE u8;             /* 1-byte unsigned integer */
7418typedef INT8_TYPE i8;              /* 1-byte signed integer */
7419
7420/*
7421** SQLITE_MAX_U32 is a u64 constant that is the maximum u64 value
7422** that can be stored in a u32 without loss of data.  The value
7423** is 0x00000000ffffffff.  But because of quirks of some compilers, we
7424** have to specify the value in the less intuitive manner shown:
7425*/
7426#define SQLITE_MAX_U32  ((((u64)1)<<32)-1)
7427
7428/*
7429** Macros to determine whether the machine is big or little endian,
7430** evaluated at runtime.
7431*/
7432#ifdef SQLITE_AMALGAMATION
7433SQLITE_PRIVATE const int sqlite3one = 1;
7434#else
7435SQLITE_PRIVATE const int sqlite3one;
7436#endif
7437#if defined(i386) || defined(__i386__) || defined(_M_IX86)\
7438                             || defined(__x86_64) || defined(__x86_64__)
7439# define SQLITE_BIGENDIAN    0
7440# define SQLITE_LITTLEENDIAN 1
7441# define SQLITE_UTF16NATIVE  SQLITE_UTF16LE
7442#else
7443# define SQLITE_BIGENDIAN    (*(char *)(&sqlite3one)==0)
7444# define SQLITE_LITTLEENDIAN (*(char *)(&sqlite3one)==1)
7445# define SQLITE_UTF16NATIVE (SQLITE_BIGENDIAN?SQLITE_UTF16BE:SQLITE_UTF16LE)
7446#endif
7447
7448/*
7449** Constants for the largest and smallest possible 64-bit signed integers.
7450** These macros are designed to work correctly on both 32-bit and 64-bit
7451** compilers.
7452*/
7453#define LARGEST_INT64  (0xffffffff|(((i64)0x7fffffff)<<32))
7454#define SMALLEST_INT64 (((i64)-1) - LARGEST_INT64)
7455
7456/*
7457** Round up a number to the next larger multiple of 8.  This is used
7458** to force 8-byte alignment on 64-bit architectures.
7459*/
7460#define ROUND8(x)     (((x)+7)&~7)
7461
7462/*
7463** Round down to the nearest multiple of 8
7464*/
7465#define ROUNDDOWN8(x) ((x)&~7)
7466
7467/*
7468** Assert that the pointer X is aligned to an 8-byte boundary.  This
7469** macro is used only within assert() to verify that the code gets
7470** all alignment restrictions correct.
7471**
7472** Except, if SQLITE_4_BYTE_ALIGNED_MALLOC is defined, then the
7473** underlying malloc() implemention might return us 4-byte aligned
7474** pointers.  In that case, only verify 4-byte alignment.
7475*/
7476#ifdef SQLITE_4_BYTE_ALIGNED_MALLOC
7477# define EIGHT_BYTE_ALIGNMENT(X)   ((((char*)(X) - (char*)0)&3)==0)
7478#else
7479# define EIGHT_BYTE_ALIGNMENT(X)   ((((char*)(X) - (char*)0)&7)==0)
7480#endif
7481
7482
7483/*
7484** An instance of the following structure is used to store the busy-handler
7485** callback for a given sqlite handle.
7486**
7487** The sqlite.busyHandler member of the sqlite struct contains the busy
7488** callback for the database handle. Each pager opened via the sqlite
7489** handle is passed a pointer to sqlite.busyHandler. The busy-handler
7490** callback is currently invoked only from within pager.c.
7491*/
7492typedef struct BusyHandler BusyHandler;
7493struct BusyHandler {
7494  int (*xFunc)(void *,int);  /* The busy callback */
7495  void *pArg;                /* First arg to busy callback */
7496  int nBusy;                 /* Incremented with each busy call */
7497};
7498
7499/*
7500** Name of the master database table.  The master database table
7501** is a special table that holds the names and attributes of all
7502** user tables and indices.
7503*/
7504#define MASTER_NAME       "sqlite_master"
7505#define TEMP_MASTER_NAME  "sqlite_temp_master"
7506
7507/*
7508** The root-page of the master database table.
7509*/
7510#define MASTER_ROOT       1
7511
7512/*
7513** The name of the schema table.
7514*/
7515#define SCHEMA_TABLE(x)  ((!OMIT_TEMPDB)&&(x==1)?TEMP_MASTER_NAME:MASTER_NAME)
7516
7517/*
7518** A convenience macro that returns the number of elements in
7519** an array.
7520*/
7521#define ArraySize(X)    ((int)(sizeof(X)/sizeof(X[0])))
7522
7523/*
7524** The following value as a destructor means to use sqlite3DbFree().
7525** This is an internal extension to SQLITE_STATIC and SQLITE_TRANSIENT.
7526*/
7527#define SQLITE_DYNAMIC   ((sqlite3_destructor_type)sqlite3DbFree)
7528
7529/*
7530** When SQLITE_OMIT_WSD is defined, it means that the target platform does
7531** not support Writable Static Data (WSD) such as global and static variables.
7532** All variables must either be on the stack or dynamically allocated from
7533** the heap.  When WSD is unsupported, the variable declarations scattered
7534** throughout the SQLite code must become constants instead.  The SQLITE_WSD
7535** macro is used for this purpose.  And instead of referencing the variable
7536** directly, we use its constant as a key to lookup the run-time allocated
7537** buffer that holds real variable.  The constant is also the initializer
7538** for the run-time allocated buffer.
7539**
7540** In the usual case where WSD is supported, the SQLITE_WSD and GLOBAL
7541** macros become no-ops and have zero performance impact.
7542*/
7543#ifdef SQLITE_OMIT_WSD
7544  #define SQLITE_WSD const
7545  #define GLOBAL(t,v) (*(t*)sqlite3_wsd_find((void*)&(v), sizeof(v)))
7546  #define sqlite3GlobalConfig GLOBAL(struct Sqlite3Config, sqlite3Config)
7547SQLITE_API   int sqlite3_wsd_init(int N, int J);
7548SQLITE_API   void *sqlite3_wsd_find(void *K, int L);
7549#else
7550  #define SQLITE_WSD
7551  #define GLOBAL(t,v) v
7552  #define sqlite3GlobalConfig sqlite3Config
7553#endif
7554
7555/*
7556** The following macros are used to suppress compiler warnings and to
7557** make it clear to human readers when a function parameter is deliberately
7558** left unused within the body of a function. This usually happens when
7559** a function is called via a function pointer. For example the
7560** implementation of an SQL aggregate step callback may not use the
7561** parameter indicating the number of arguments passed to the aggregate,
7562** if it knows that this is enforced elsewhere.
7563**
7564** When a function parameter is not used at all within the body of a function,
7565** it is generally named "NotUsed" or "NotUsed2" to make things even clearer.
7566** However, these macros may also be used to suppress warnings related to
7567** parameters that may or may not be used depending on compilation options.
7568** For example those parameters only used in assert() statements. In these
7569** cases the parameters are named as per the usual conventions.
7570*/
7571#define UNUSED_PARAMETER(x) (void)(x)
7572#define UNUSED_PARAMETER2(x,y) UNUSED_PARAMETER(x),UNUSED_PARAMETER(y)
7573
7574/*
7575** Forward references to structures
7576*/
7577typedef struct AggInfo AggInfo;
7578typedef struct AuthContext AuthContext;
7579typedef struct AutoincInfo AutoincInfo;
7580typedef struct Bitvec Bitvec;
7581typedef struct CollSeq CollSeq;
7582typedef struct Column Column;
7583typedef struct Db Db;
7584typedef struct Schema Schema;
7585typedef struct Expr Expr;
7586typedef struct ExprList ExprList;
7587typedef struct ExprSpan ExprSpan;
7588typedef struct FKey FKey;
7589typedef struct FuncDestructor FuncDestructor;
7590typedef struct FuncDef FuncDef;
7591typedef struct FuncDefHash FuncDefHash;
7592typedef struct IdList IdList;
7593typedef struct Index Index;
7594typedef struct IndexSample IndexSample;
7595typedef struct KeyClass KeyClass;
7596typedef struct KeyInfo KeyInfo;
7597typedef struct Lookaside Lookaside;
7598typedef struct LookasideSlot LookasideSlot;
7599typedef struct Module Module;
7600typedef struct NameContext NameContext;
7601typedef struct Parse Parse;
7602typedef struct RowSet RowSet;
7603typedef struct Savepoint Savepoint;
7604typedef struct Select Select;
7605typedef struct SrcList SrcList;
7606typedef struct StrAccum StrAccum;
7607typedef struct Table Table;
7608typedef struct TableLock TableLock;
7609typedef struct Token Token;
7610typedef struct Trigger Trigger;
7611typedef struct TriggerPrg TriggerPrg;
7612typedef struct TriggerStep TriggerStep;
7613typedef struct UnpackedRecord UnpackedRecord;
7614typedef struct VTable VTable;
7615typedef struct Walker Walker;
7616typedef struct WherePlan WherePlan;
7617typedef struct WhereInfo WhereInfo;
7618typedef struct WhereLevel WhereLevel;
7619
7620/*
7621** Defer sourcing vdbe.h and btree.h until after the "u8" and
7622** "BusyHandler" typedefs. vdbe.h also requires a few of the opaque
7623** pointer types (i.e. FuncDef) defined above.
7624*/
7625/************** Include btree.h in the middle of sqliteInt.h *****************/
7626/************** Begin file btree.h *******************************************/
7627/*
7628** 2001 September 15
7629**
7630** The author disclaims copyright to this source code.  In place of
7631** a legal notice, here is a blessing:
7632**
7633**    May you do good and not evil.
7634**    May you find forgiveness for yourself and forgive others.
7635**    May you share freely, never taking more than you give.
7636**
7637*************************************************************************
7638** This header file defines the interface that the sqlite B-Tree file
7639** subsystem.  See comments in the source code for a detailed description
7640** of what each interface routine does.
7641*/
7642#ifndef _BTREE_H_
7643#define _BTREE_H_
7644
7645/* TODO: This definition is just included so other modules compile. It
7646** needs to be revisited.
7647*/
7648#define SQLITE_N_BTREE_META 10
7649
7650/*
7651** If defined as non-zero, auto-vacuum is enabled by default. Otherwise
7652** it must be turned on for each database using "PRAGMA auto_vacuum = 1".
7653*/
7654#ifndef SQLITE_DEFAULT_AUTOVACUUM
7655  #define SQLITE_DEFAULT_AUTOVACUUM 0
7656#endif
7657
7658#define BTREE_AUTOVACUUM_NONE 0        /* Do not do auto-vacuum */
7659#define BTREE_AUTOVACUUM_FULL 1        /* Do full auto-vacuum */
7660#define BTREE_AUTOVACUUM_INCR 2        /* Incremental vacuum */
7661
7662/*
7663** Forward declarations of structure
7664*/
7665typedef struct Btree Btree;
7666typedef struct BtCursor BtCursor;
7667typedef struct BtShared BtShared;
7668
7669
7670SQLITE_PRIVATE int sqlite3BtreeOpen(
7671  const char *zFilename,   /* Name of database file to open */
7672  sqlite3 *db,             /* Associated database connection */
7673  Btree **ppBtree,         /* Return open Btree* here */
7674  int flags,               /* Flags */
7675  int vfsFlags             /* Flags passed through to VFS open */
7676);
7677
7678/* The flags parameter to sqlite3BtreeOpen can be the bitwise or of the
7679** following values.
7680**
7681** NOTE:  These values must match the corresponding PAGER_ values in
7682** pager.h.
7683*/
7684#define BTREE_OMIT_JOURNAL  1  /* Do not create or use a rollback journal */
7685#define BTREE_NO_READLOCK   2  /* Omit readlocks on readonly files */
7686#define BTREE_MEMORY        4  /* This is an in-memory DB */
7687#define BTREE_SINGLE        8  /* The file contains at most 1 b-tree */
7688#define BTREE_UNORDERED    16  /* Use of a hash implementation is OK */
7689
7690SQLITE_PRIVATE int sqlite3BtreeClose(Btree*);
7691SQLITE_PRIVATE int sqlite3BtreeSetCacheSize(Btree*,int);
7692SQLITE_PRIVATE int sqlite3BtreeSetSafetyLevel(Btree*,int,int,int);
7693SQLITE_PRIVATE int sqlite3BtreeSyncDisabled(Btree*);
7694SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree *p, int nPagesize, int nReserve, int eFix);
7695SQLITE_PRIVATE int sqlite3BtreeGetPageSize(Btree*);
7696SQLITE_PRIVATE int sqlite3BtreeMaxPageCount(Btree*,int);
7697SQLITE_PRIVATE u32 sqlite3BtreeLastPage(Btree*);
7698SQLITE_PRIVATE int sqlite3BtreeSecureDelete(Btree*,int);
7699SQLITE_PRIVATE int sqlite3BtreeGetReserve(Btree*);
7700SQLITE_PRIVATE int sqlite3BtreeSetAutoVacuum(Btree *, int);
7701SQLITE_PRIVATE int sqlite3BtreeGetAutoVacuum(Btree *);
7702SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree*,int);
7703SQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree*, const char *zMaster);
7704SQLITE_PRIVATE int sqlite3BtreeCommitPhaseTwo(Btree*, int);
7705SQLITE_PRIVATE int sqlite3BtreeCommit(Btree*);
7706SQLITE_PRIVATE int sqlite3BtreeRollback(Btree*);
7707SQLITE_PRIVATE int sqlite3BtreeBeginStmt(Btree*,int);
7708SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree*, int*, int flags);
7709SQLITE_PRIVATE int sqlite3BtreeIsInTrans(Btree*);
7710SQLITE_PRIVATE int sqlite3BtreeIsInReadTrans(Btree*);
7711SQLITE_PRIVATE int sqlite3BtreeIsInBackup(Btree*);
7712SQLITE_PRIVATE void *sqlite3BtreeSchema(Btree *, int, void(*)(void *));
7713SQLITE_PRIVATE int sqlite3BtreeSchemaLocked(Btree *pBtree);
7714SQLITE_PRIVATE int sqlite3BtreeLockTable(Btree *pBtree, int iTab, u8 isWriteLock);
7715SQLITE_PRIVATE int sqlite3BtreeSavepoint(Btree *, int, int);
7716
7717SQLITE_PRIVATE const char *sqlite3BtreeGetFilename(Btree *);
7718SQLITE_PRIVATE const char *sqlite3BtreeGetJournalname(Btree *);
7719SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *, Btree *);
7720
7721SQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *);
7722
7723/* The flags parameter to sqlite3BtreeCreateTable can be the bitwise OR
7724** of the flags shown below.
7725**
7726** Every SQLite table must have either BTREE_INTKEY or BTREE_BLOBKEY set.
7727** With BTREE_INTKEY, the table key is a 64-bit integer and arbitrary data
7728** is stored in the leaves.  (BTREE_INTKEY is used for SQL tables.)  With
7729** BTREE_BLOBKEY, the key is an arbitrary BLOB and no content is stored
7730** anywhere - the key is the content.  (BTREE_BLOBKEY is used for SQL
7731** indices.)
7732*/
7733#define BTREE_INTKEY     1    /* Table has only 64-bit signed integer keys */
7734#define BTREE_BLOBKEY    2    /* Table has keys only - no data */
7735
7736SQLITE_PRIVATE int sqlite3BtreeDropTable(Btree*, int, int*);
7737SQLITE_PRIVATE int sqlite3BtreeClearTable(Btree*, int, int*);
7738SQLITE_PRIVATE void sqlite3BtreeTripAllCursors(Btree*, int);
7739
7740SQLITE_PRIVATE void sqlite3BtreeGetMeta(Btree *pBtree, int idx, u32 *pValue);
7741SQLITE_PRIVATE int sqlite3BtreeUpdateMeta(Btree*, int idx, u32 value);
7742
7743/*
7744** The second parameter to sqlite3BtreeGetMeta or sqlite3BtreeUpdateMeta
7745** should be one of the following values. The integer values are assigned
7746** to constants so that the offset of the corresponding field in an
7747** SQLite database header may be found using the following formula:
7748**
7749**   offset = 36 + (idx * 4)
7750**
7751** For example, the free-page-count field is located at byte offset 36 of
7752** the database file header. The incr-vacuum-flag field is located at
7753** byte offset 64 (== 36+4*7).
7754*/
7755#define BTREE_FREE_PAGE_COUNT     0
7756#define BTREE_SCHEMA_VERSION      1
7757#define BTREE_FILE_FORMAT         2
7758#define BTREE_DEFAULT_CACHE_SIZE  3
7759#define BTREE_LARGEST_ROOT_PAGE   4
7760#define BTREE_TEXT_ENCODING       5
7761#define BTREE_USER_VERSION        6
7762#define BTREE_INCR_VACUUM         7
7763
7764SQLITE_PRIVATE int sqlite3BtreeCursor(
7765  Btree*,                              /* BTree containing table to open */
7766  int iTable,                          /* Index of root page */
7767  int wrFlag,                          /* 1 for writing.  0 for read-only */
7768  struct KeyInfo*,                     /* First argument to compare function */
7769  BtCursor *pCursor                    /* Space to write cursor structure */
7770);
7771SQLITE_PRIVATE int sqlite3BtreeCursorSize(void);
7772SQLITE_PRIVATE void sqlite3BtreeCursorZero(BtCursor*);
7773
7774SQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor*);
7775SQLITE_PRIVATE int sqlite3BtreeMovetoUnpacked(
7776  BtCursor*,
7777  UnpackedRecord *pUnKey,
7778  i64 intKey,
7779  int bias,
7780  int *pRes
7781);
7782SQLITE_PRIVATE int sqlite3BtreeCursorHasMoved(BtCursor*, int*);
7783SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor*);
7784SQLITE_PRIVATE int sqlite3BtreeInsert(BtCursor*, const void *pKey, i64 nKey,
7785                                  const void *pData, int nData,
7786                                  int nZero, int bias, int seekResult);
7787SQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor*, int *pRes);
7788SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor*, int *pRes);
7789SQLITE_PRIVATE int sqlite3BtreeNext(BtCursor*, int *pRes);
7790SQLITE_PRIVATE int sqlite3BtreeEof(BtCursor*);
7791SQLITE_PRIVATE int sqlite3BtreePrevious(BtCursor*, int *pRes);
7792SQLITE_PRIVATE int sqlite3BtreeKeySize(BtCursor*, i64 *pSize);
7793SQLITE_PRIVATE int sqlite3BtreeKey(BtCursor*, u32 offset, u32 amt, void*);
7794SQLITE_PRIVATE const void *sqlite3BtreeKeyFetch(BtCursor*, int *pAmt);
7795SQLITE_PRIVATE const void *sqlite3BtreeDataFetch(BtCursor*, int *pAmt);
7796SQLITE_PRIVATE int sqlite3BtreeDataSize(BtCursor*, u32 *pSize);
7797SQLITE_PRIVATE int sqlite3BtreeData(BtCursor*, u32 offset, u32 amt, void*);
7798SQLITE_PRIVATE void sqlite3BtreeSetCachedRowid(BtCursor*, sqlite3_int64);
7799SQLITE_PRIVATE sqlite3_int64 sqlite3BtreeGetCachedRowid(BtCursor*);
7800
7801SQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck(Btree*, int *aRoot, int nRoot, int, int*);
7802SQLITE_PRIVATE struct Pager *sqlite3BtreePager(Btree*);
7803
7804SQLITE_PRIVATE int sqlite3BtreePutData(BtCursor*, u32 offset, u32 amt, void*);
7805SQLITE_PRIVATE void sqlite3BtreeCacheOverflow(BtCursor *);
7806SQLITE_PRIVATE void sqlite3BtreeClearCursor(BtCursor *);
7807
7808SQLITE_PRIVATE int sqlite3BtreeSetVersion(Btree *pBt, int iVersion);
7809
7810#ifndef NDEBUG
7811SQLITE_PRIVATE int sqlite3BtreeCursorIsValid(BtCursor*);
7812#endif
7813
7814#ifndef SQLITE_OMIT_BTREECOUNT
7815SQLITE_PRIVATE int sqlite3BtreeCount(BtCursor *, i64 *);
7816#endif
7817
7818#ifdef SQLITE_TEST
7819SQLITE_PRIVATE int sqlite3BtreeCursorInfo(BtCursor*, int*, int);
7820SQLITE_PRIVATE void sqlite3BtreeCursorList(Btree*);
7821#endif
7822
7823#ifndef SQLITE_OMIT_WAL
7824SQLITE_PRIVATE   int sqlite3BtreeCheckpoint(Btree*, int, int *, int *);
7825#endif
7826
7827/*
7828** If we are not using shared cache, then there is no need to
7829** use mutexes to access the BtShared structures.  So make the
7830** Enter and Leave procedures no-ops.
7831*/
7832#ifndef SQLITE_OMIT_SHARED_CACHE
7833SQLITE_PRIVATE   void sqlite3BtreeEnter(Btree*);
7834SQLITE_PRIVATE   void sqlite3BtreeEnterAll(sqlite3*);
7835#else
7836# define sqlite3BtreeEnter(X)
7837# define sqlite3BtreeEnterAll(X)
7838#endif
7839
7840#if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE
7841SQLITE_PRIVATE   int sqlite3BtreeSharable(Btree*);
7842SQLITE_PRIVATE   void sqlite3BtreeLeave(Btree*);
7843SQLITE_PRIVATE   void sqlite3BtreeEnterCursor(BtCursor*);
7844SQLITE_PRIVATE   void sqlite3BtreeLeaveCursor(BtCursor*);
7845SQLITE_PRIVATE   void sqlite3BtreeLeaveAll(sqlite3*);
7846#ifndef NDEBUG
7847  /* These routines are used inside assert() statements only. */
7848SQLITE_PRIVATE   int sqlite3BtreeHoldsMutex(Btree*);
7849SQLITE_PRIVATE   int sqlite3BtreeHoldsAllMutexes(sqlite3*);
7850SQLITE_PRIVATE   int sqlite3SchemaMutexHeld(sqlite3*,int,Schema*);
7851#endif
7852#else
7853
7854# define sqlite3BtreeSharable(X) 0
7855# define sqlite3BtreeLeave(X)
7856# define sqlite3BtreeEnterCursor(X)
7857# define sqlite3BtreeLeaveCursor(X)
7858# define sqlite3BtreeLeaveAll(X)
7859
7860# define sqlite3BtreeHoldsMutex(X) 1
7861# define sqlite3BtreeHoldsAllMutexes(X) 1
7862# define sqlite3SchemaMutexHeld(X,Y,Z) 1
7863#endif
7864
7865
7866#endif /* _BTREE_H_ */
7867
7868/************** End of btree.h ***********************************************/
7869/************** Continuing where we left off in sqliteInt.h ******************/
7870/************** Include vdbe.h in the middle of sqliteInt.h ******************/
7871/************** Begin file vdbe.h ********************************************/
7872/*
7873** 2001 September 15
7874**
7875** The author disclaims copyright to this source code.  In place of
7876** a legal notice, here is a blessing:
7877**
7878**    May you do good and not evil.
7879**    May you find forgiveness for yourself and forgive others.
7880**    May you share freely, never taking more than you give.
7881**
7882*************************************************************************
7883** Header file for the Virtual DataBase Engine (VDBE)
7884**
7885** This header defines the interface to the virtual database engine
7886** or VDBE.  The VDBE implements an abstract machine that runs a
7887** simple program to access and modify the underlying database.
7888*/
7889#ifndef _SQLITE_VDBE_H_
7890#define _SQLITE_VDBE_H_
7891
7892/*
7893** A single VDBE is an opaque structure named "Vdbe".  Only routines
7894** in the source file sqliteVdbe.c are allowed to see the insides
7895** of this structure.
7896*/
7897typedef struct Vdbe Vdbe;
7898
7899/*
7900** The names of the following types declared in vdbeInt.h are required
7901** for the VdbeOp definition.
7902*/
7903typedef struct VdbeFunc VdbeFunc;
7904typedef struct Mem Mem;
7905typedef struct SubProgram SubProgram;
7906
7907/*
7908** A single instruction of the virtual machine has an opcode
7909** and as many as three operands.  The instruction is recorded
7910** as an instance of the following structure:
7911*/
7912struct VdbeOp {
7913  u8 opcode;          /* What operation to perform */
7914  signed char p4type; /* One of the P4_xxx constants for p4 */
7915  u8 opflags;         /* Mask of the OPFLG_* flags in opcodes.h */
7916  u8 p5;              /* Fifth parameter is an unsigned character */
7917  int p1;             /* First operand */
7918  int p2;             /* Second parameter (often the jump destination) */
7919  int p3;             /* The third parameter */
7920  union {             /* fourth parameter */
7921    int i;                 /* Integer value if p4type==P4_INT32 */
7922    void *p;               /* Generic pointer */
7923    char *z;               /* Pointer to data for string (char array) types */
7924    i64 *pI64;             /* Used when p4type is P4_INT64 */
7925    double *pReal;         /* Used when p4type is P4_REAL */
7926    FuncDef *pFunc;        /* Used when p4type is P4_FUNCDEF */
7927    VdbeFunc *pVdbeFunc;   /* Used when p4type is P4_VDBEFUNC */
7928    CollSeq *pColl;        /* Used when p4type is P4_COLLSEQ */
7929    Mem *pMem;             /* Used when p4type is P4_MEM */
7930    VTable *pVtab;         /* Used when p4type is P4_VTAB */
7931    KeyInfo *pKeyInfo;     /* Used when p4type is P4_KEYINFO */
7932    int *ai;               /* Used when p4type is P4_INTARRAY */
7933    SubProgram *pProgram;  /* Used when p4type is P4_SUBPROGRAM */
7934  } p4;
7935#ifdef SQLITE_DEBUG
7936  char *zComment;          /* Comment to improve readability */
7937#endif
7938#ifdef VDBE_PROFILE
7939  int cnt;                 /* Number of times this instruction was executed */
7940  u64 cycles;              /* Total time spent executing this instruction */
7941#endif
7942};
7943typedef struct VdbeOp VdbeOp;
7944
7945
7946/*
7947** A sub-routine used to implement a trigger program.
7948*/
7949struct SubProgram {
7950  VdbeOp *aOp;                  /* Array of opcodes for sub-program */
7951  int nOp;                      /* Elements in aOp[] */
7952  int nMem;                     /* Number of memory cells required */
7953  int nCsr;                     /* Number of cursors required */
7954  void *token;                  /* id that may be used to recursive triggers */
7955  SubProgram *pNext;            /* Next sub-program already visited */
7956};
7957
7958/*
7959** A smaller version of VdbeOp used for the VdbeAddOpList() function because
7960** it takes up less space.
7961*/
7962struct VdbeOpList {
7963  u8 opcode;          /* What operation to perform */
7964  signed char p1;     /* First operand */
7965  signed char p2;     /* Second parameter (often the jump destination) */
7966  signed char p3;     /* Third parameter */
7967};
7968typedef struct VdbeOpList VdbeOpList;
7969
7970/*
7971** Allowed values of VdbeOp.p4type
7972*/
7973#define P4_NOTUSED    0   /* The P4 parameter is not used */
7974#define P4_DYNAMIC  (-1)  /* Pointer to a string obtained from sqliteMalloc() */
7975#define P4_STATIC   (-2)  /* Pointer to a static string */
7976#define P4_COLLSEQ  (-4)  /* P4 is a pointer to a CollSeq structure */
7977#define P4_FUNCDEF  (-5)  /* P4 is a pointer to a FuncDef structure */
7978#define P4_KEYINFO  (-6)  /* P4 is a pointer to a KeyInfo structure */
7979#define P4_VDBEFUNC (-7)  /* P4 is a pointer to a VdbeFunc structure */
7980#define P4_MEM      (-8)  /* P4 is a pointer to a Mem*    structure */
7981#define P4_TRANSIENT  0   /* P4 is a pointer to a transient string */
7982#define P4_VTAB     (-10) /* P4 is a pointer to an sqlite3_vtab structure */
7983#define P4_MPRINTF  (-11) /* P4 is a string obtained from sqlite3_mprintf() */
7984#define P4_REAL     (-12) /* P4 is a 64-bit floating point value */
7985#define P4_INT64    (-13) /* P4 is a 64-bit signed integer */
7986#define P4_INT32    (-14) /* P4 is a 32-bit signed integer */
7987#define P4_INTARRAY (-15) /* P4 is a vector of 32-bit integers */
7988#define P4_SUBPROGRAM  (-18) /* P4 is a pointer to a SubProgram structure */
7989
7990/* When adding a P4 argument using P4_KEYINFO, a copy of the KeyInfo structure
7991** is made.  That copy is freed when the Vdbe is finalized.  But if the
7992** argument is P4_KEYINFO_HANDOFF, the passed in pointer is used.  It still
7993** gets freed when the Vdbe is finalized so it still should be obtained
7994** from a single sqliteMalloc().  But no copy is made and the calling
7995** function should *not* try to free the KeyInfo.
7996*/
7997#define P4_KEYINFO_HANDOFF (-16)
7998#define P4_KEYINFO_STATIC  (-17)
7999
8000/*
8001** The Vdbe.aColName array contains 5n Mem structures, where n is the
8002** number of columns of data returned by the statement.
8003*/
8004#define COLNAME_NAME     0
8005#define COLNAME_DECLTYPE 1
8006#define COLNAME_DATABASE 2
8007#define COLNAME_TABLE    3
8008#define COLNAME_COLUMN   4
8009#ifdef SQLITE_ENABLE_COLUMN_METADATA
8010# define COLNAME_N        5      /* Number of COLNAME_xxx symbols */
8011#else
8012# ifdef SQLITE_OMIT_DECLTYPE
8013#   define COLNAME_N      1      /* Store only the name */
8014# else
8015#   define COLNAME_N      2      /* Store the name and decltype */
8016# endif
8017#endif
8018
8019/*
8020** The following macro converts a relative address in the p2 field
8021** of a VdbeOp structure into a negative number so that
8022** sqlite3VdbeAddOpList() knows that the address is relative.  Calling
8023** the macro again restores the address.
8024*/
8025#define ADDR(X)  (-1-(X))
8026
8027/*
8028** The makefile scans the vdbe.c source file and creates the "opcodes.h"
8029** header file that defines a number for each opcode used by the VDBE.
8030*/
8031/************** Include opcodes.h in the middle of vdbe.h ********************/
8032/************** Begin file opcodes.h *****************************************/
8033/* Automatically generated.  Do not edit */
8034/* See the mkopcodeh.awk script for details */
8035#define OP_Goto                                 1
8036#define OP_Gosub                                2
8037#define OP_Return                               3
8038#define OP_Yield                                4
8039#define OP_HaltIfNull                           5
8040#define OP_Halt                                 6
8041#define OP_Integer                              7
8042#define OP_Int64                                8
8043#define OP_Real                               130   /* same as TK_FLOAT    */
8044#define OP_String8                             94   /* same as TK_STRING   */
8045#define OP_String                               9
8046#define OP_Null                                10
8047#define OP_Blob                                11
8048#define OP_Variable                            12
8049#define OP_Move                                13
8050#define OP_Copy                                14
8051#define OP_SCopy                               15
8052#define OP_ResultRow                           16
8053#define OP_Concat                              91   /* same as TK_CONCAT   */
8054#define OP_Add                                 86   /* same as TK_PLUS     */
8055#define OP_Subtract                            87   /* same as TK_MINUS    */
8056#define OP_Multiply                            88   /* same as TK_STAR     */
8057#define OP_Divide                              89   /* same as TK_SLASH    */
8058#define OP_Remainder                           90   /* same as TK_REM      */
8059#define OP_CollSeq                             17
8060#define OP_Function                            18
8061#define OP_BitAnd                              82   /* same as TK_BITAND   */
8062#define OP_BitOr                               83   /* same as TK_BITOR    */
8063#define OP_ShiftLeft                           84   /* same as TK_LSHIFT   */
8064#define OP_ShiftRight                          85   /* same as TK_RSHIFT   */
8065#define OP_AddImm                              20
8066#define OP_MustBeInt                           21
8067#define OP_RealAffinity                        22
8068#define OP_ToText                             141   /* same as TK_TO_TEXT  */
8069#define OP_ToBlob                             142   /* same as TK_TO_BLOB  */
8070#define OP_ToNumeric                          143   /* same as TK_TO_NUMERIC*/
8071#define OP_ToInt                              144   /* same as TK_TO_INT   */
8072#define OP_ToReal                             145   /* same as TK_TO_REAL  */
8073#define OP_Eq                                  76   /* same as TK_EQ       */
8074#define OP_Ne                                  75   /* same as TK_NE       */
8075#define OP_Lt                                  79   /* same as TK_LT       */
8076#define OP_Le                                  78   /* same as TK_LE       */
8077#define OP_Gt                                  77   /* same as TK_GT       */
8078#define OP_Ge                                  80   /* same as TK_GE       */
8079#define OP_Permutation                         23
8080#define OP_Compare                             24
8081#define OP_Jump                                25
8082#define OP_And                                 69   /* same as TK_AND      */
8083#define OP_Or                                  68   /* same as TK_OR       */
8084#define OP_Not                                 19   /* same as TK_NOT      */
8085#define OP_BitNot                              93   /* same as TK_BITNOT   */
8086#define OP_If                                  26
8087#define OP_IfNot                               27
8088#define OP_IsNull                              73   /* same as TK_ISNULL   */
8089#define OP_NotNull                             74   /* same as TK_NOTNULL  */
8090#define OP_Column                              28
8091#define OP_Affinity                            29
8092#define OP_MakeRecord                          30
8093#define OP_Count                               31
8094#define OP_Savepoint                           32
8095#define OP_AutoCommit                          33
8096#define OP_Transaction                         34
8097#define OP_ReadCookie                          35
8098#define OP_SetCookie                           36
8099#define OP_VerifyCookie                        37
8100#define OP_OpenRead                            38
8101#define OP_OpenWrite                           39
8102#define OP_OpenAutoindex                       40
8103#define OP_OpenEphemeral                       41
8104#define OP_OpenPseudo                          42
8105#define OP_Close                               43
8106#define OP_SeekLt                              44
8107#define OP_SeekLe                              45
8108#define OP_SeekGe                              46
8109#define OP_SeekGt                              47
8110#define OP_Seek                                48
8111#define OP_NotFound                            49
8112#define OP_Found                               50
8113#define OP_IsUnique                            51
8114#define OP_NotExists                           52
8115#define OP_Sequence                            53
8116#define OP_NewRowid                            54
8117#define OP_Insert                              55
8118#define OP_InsertInt                           56
8119#define OP_Delete                              57
8120#define OP_ResetCount                          58
8121#define OP_RowKey                              59
8122#define OP_RowData                             60
8123#define OP_Rowid                               61
8124#define OP_NullRow                             62
8125#define OP_Last                                63
8126#define OP_Sort                                64
8127#define OP_Rewind                              65
8128#define OP_Prev                                66
8129#define OP_Next                                67
8130#define OP_IdxInsert                           70
8131#define OP_IdxDelete                           71
8132#define OP_IdxRowid                            72
8133#define OP_IdxLT                               81
8134#define OP_IdxGE                               92
8135#define OP_Destroy                             95
8136#define OP_Clear                               96
8137#define OP_CreateIndex                         97
8138#define OP_CreateTable                         98
8139#define OP_ParseSchema                         99
8140#define OP_LoadAnalysis                       100
8141#define OP_DropTable                          101
8142#define OP_DropIndex                          102
8143#define OP_DropTrigger                        103
8144#define OP_IntegrityCk                        104
8145#define OP_RowSetAdd                          105
8146#define OP_RowSetRead                         106
8147#define OP_RowSetTest                         107
8148#define OP_Program                            108
8149#define OP_Param                              109
8150#define OP_FkCounter                          110
8151#define OP_FkIfZero                           111
8152#define OP_MemMax                             112
8153#define OP_IfPos                              113
8154#define OP_IfNeg                              114
8155#define OP_IfZero                             115
8156#define OP_AggStep                            116
8157#define OP_AggFinal                           117
8158#define OP_Checkpoint                         118
8159#define OP_JournalMode                        119
8160#define OP_Vacuum                             120
8161#define OP_IncrVacuum                         121
8162#define OP_Expire                             122
8163#define OP_TableLock                          123
8164#define OP_VBegin                             124
8165#define OP_VCreate                            125
8166#define OP_VDestroy                           126
8167#define OP_VOpen                              127
8168#define OP_VFilter                            128
8169#define OP_VColumn                            129
8170#define OP_VNext                              131
8171#define OP_VRename                            132
8172#define OP_VUpdate                            133
8173#define OP_Pagecount                          134
8174#define OP_MaxPgcnt                           135
8175#define OP_Trace                              136
8176#define OP_Noop                               137
8177#define OP_Explain                            138
8178
8179/* The following opcode values are never used */
8180#define OP_NotUsed_139                        139
8181#define OP_NotUsed_140                        140
8182
8183
8184/* Properties such as "out2" or "jump" that are specified in
8185** comments following the "case" for each opcode in the vdbe.c
8186** are encoded into bitvectors as follows:
8187*/
8188#define OPFLG_JUMP            0x0001  /* jump:  P2 holds jmp target */
8189#define OPFLG_OUT2_PRERELEASE 0x0002  /* out2-prerelease: */
8190#define OPFLG_IN1             0x0004  /* in1:   P1 is an input */
8191#define OPFLG_IN2             0x0008  /* in2:   P2 is an input */
8192#define OPFLG_IN3             0x0010  /* in3:   P3 is an input */
8193#define OPFLG_OUT2            0x0020  /* out2:  P2 is an output */
8194#define OPFLG_OUT3            0x0040  /* out3:  P3 is an output */
8195#define OPFLG_INITIALIZER {\
8196/*   0 */ 0x00, 0x01, 0x05, 0x04, 0x04, 0x10, 0x00, 0x02,\
8197/*   8 */ 0x02, 0x02, 0x02, 0x02, 0x02, 0x00, 0x24, 0x24,\
8198/*  16 */ 0x00, 0x00, 0x00, 0x24, 0x04, 0x05, 0x04, 0x00,\
8199/*  24 */ 0x00, 0x01, 0x05, 0x05, 0x00, 0x00, 0x00, 0x02,\
8200/*  32 */ 0x00, 0x00, 0x00, 0x02, 0x10, 0x00, 0x00, 0x00,\
8201/*  40 */ 0x00, 0x00, 0x00, 0x00, 0x11, 0x11, 0x11, 0x11,\
8202/*  48 */ 0x08, 0x11, 0x11, 0x11, 0x11, 0x02, 0x02, 0x00,\
8203/*  56 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x01,\
8204/*  64 */ 0x01, 0x01, 0x01, 0x01, 0x4c, 0x4c, 0x08, 0x00,\
8205/*  72 */ 0x02, 0x05, 0x05, 0x15, 0x15, 0x15, 0x15, 0x15,\
8206/*  80 */ 0x15, 0x01, 0x4c, 0x4c, 0x4c, 0x4c, 0x4c, 0x4c,\
8207/*  88 */ 0x4c, 0x4c, 0x4c, 0x4c, 0x01, 0x24, 0x02, 0x02,\
8208/*  96 */ 0x00, 0x02, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00,\
8209/* 104 */ 0x00, 0x0c, 0x45, 0x15, 0x01, 0x02, 0x00, 0x01,\
8210/* 112 */ 0x08, 0x05, 0x05, 0x05, 0x00, 0x00, 0x00, 0x02,\
8211/* 120 */ 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\
8212/* 128 */ 0x01, 0x00, 0x02, 0x01, 0x00, 0x00, 0x02, 0x02,\
8213/* 136 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x04, 0x04,\
8214/* 144 */ 0x04, 0x04,}
8215
8216/************** End of opcodes.h *********************************************/
8217/************** Continuing where we left off in vdbe.h ***********************/
8218
8219/*
8220** Prototypes for the VDBE interface.  See comments on the implementation
8221** for a description of what each of these routines does.
8222*/
8223SQLITE_PRIVATE Vdbe *sqlite3VdbeCreate(sqlite3*);
8224SQLITE_PRIVATE int sqlite3VdbeAddOp0(Vdbe*,int);
8225SQLITE_PRIVATE int sqlite3VdbeAddOp1(Vdbe*,int,int);
8226SQLITE_PRIVATE int sqlite3VdbeAddOp2(Vdbe*,int,int,int);
8227SQLITE_PRIVATE int sqlite3VdbeAddOp3(Vdbe*,int,int,int,int);
8228SQLITE_PRIVATE int sqlite3VdbeAddOp4(Vdbe*,int,int,int,int,const char *zP4,int);
8229SQLITE_PRIVATE int sqlite3VdbeAddOp4Int(Vdbe*,int,int,int,int,int);
8230SQLITE_PRIVATE int sqlite3VdbeAddOpList(Vdbe*, int nOp, VdbeOpList const *aOp);
8231SQLITE_PRIVATE void sqlite3VdbeChangeP1(Vdbe*, int addr, int P1);
8232SQLITE_PRIVATE void sqlite3VdbeChangeP2(Vdbe*, int addr, int P2);
8233SQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe*, int addr, int P3);
8234SQLITE_PRIVATE void sqlite3VdbeChangeP5(Vdbe*, u8 P5);
8235SQLITE_PRIVATE void sqlite3VdbeJumpHere(Vdbe*, int addr);
8236SQLITE_PRIVATE void sqlite3VdbeChangeToNoop(Vdbe*, int addr, int N);
8237SQLITE_PRIVATE void sqlite3VdbeChangeP4(Vdbe*, int addr, const char *zP4, int N);
8238SQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe*, int);
8239SQLITE_PRIVATE VdbeOp *sqlite3VdbeGetOp(Vdbe*, int);
8240SQLITE_PRIVATE int sqlite3VdbeMakeLabel(Vdbe*);
8241SQLITE_PRIVATE void sqlite3VdbeRunOnlyOnce(Vdbe*);
8242SQLITE_PRIVATE void sqlite3VdbeDelete(Vdbe*);
8243SQLITE_PRIVATE void sqlite3VdbeDeleteObject(sqlite3*,Vdbe*);
8244SQLITE_PRIVATE void sqlite3VdbeMakeReady(Vdbe*,int,int,int,int,int,int);
8245SQLITE_PRIVATE int sqlite3VdbeFinalize(Vdbe*);
8246SQLITE_PRIVATE void sqlite3VdbeResolveLabel(Vdbe*, int);
8247SQLITE_PRIVATE int sqlite3VdbeCurrentAddr(Vdbe*);
8248#ifdef SQLITE_DEBUG
8249SQLITE_PRIVATE   int sqlite3VdbeAssertMayAbort(Vdbe *, int);
8250SQLITE_PRIVATE   void sqlite3VdbeTrace(Vdbe*,FILE*);
8251#endif
8252SQLITE_PRIVATE void sqlite3VdbeResetStepResult(Vdbe*);
8253SQLITE_PRIVATE int sqlite3VdbeReset(Vdbe*);
8254SQLITE_PRIVATE void sqlite3VdbeSetNumCols(Vdbe*,int);
8255SQLITE_PRIVATE int sqlite3VdbeSetColName(Vdbe*, int, int, const char *, void(*)(void*));
8256SQLITE_PRIVATE void sqlite3VdbeCountChanges(Vdbe*);
8257SQLITE_PRIVATE sqlite3 *sqlite3VdbeDb(Vdbe*);
8258SQLITE_PRIVATE void sqlite3VdbeSetSql(Vdbe*, const char *z, int n, int);
8259SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe*,Vdbe*);
8260SQLITE_PRIVATE VdbeOp *sqlite3VdbeTakeOpArray(Vdbe*, int*, int*);
8261SQLITE_PRIVATE sqlite3_value *sqlite3VdbeGetValue(Vdbe*, int, u8);
8262SQLITE_PRIVATE void sqlite3VdbeSetVarmask(Vdbe*, int);
8263#ifndef SQLITE_OMIT_TRACE
8264SQLITE_PRIVATE   char *sqlite3VdbeExpandSql(Vdbe*, const char*);
8265#endif
8266
8267SQLITE_PRIVATE UnpackedRecord *sqlite3VdbeRecordUnpack(KeyInfo*,int,const void*,char*,int);
8268SQLITE_PRIVATE void sqlite3VdbeDeleteUnpackedRecord(UnpackedRecord*);
8269SQLITE_PRIVATE int sqlite3VdbeRecordCompare(int,const void*,UnpackedRecord*);
8270
8271#ifndef SQLITE_OMIT_TRIGGER
8272SQLITE_PRIVATE void sqlite3VdbeLinkSubProgram(Vdbe *, SubProgram *);
8273#endif
8274
8275
8276#ifndef NDEBUG
8277SQLITE_PRIVATE   void sqlite3VdbeComment(Vdbe*, const char*, ...);
8278# define VdbeComment(X)  sqlite3VdbeComment X
8279SQLITE_PRIVATE   void sqlite3VdbeNoopComment(Vdbe*, const char*, ...);
8280# define VdbeNoopComment(X)  sqlite3VdbeNoopComment X
8281#else
8282# define VdbeComment(X)
8283# define VdbeNoopComment(X)
8284#endif
8285
8286#endif
8287
8288/************** End of vdbe.h ************************************************/
8289/************** Continuing where we left off in sqliteInt.h ******************/
8290/************** Include pager.h in the middle of sqliteInt.h *****************/
8291/************** Begin file pager.h *******************************************/
8292/*
8293** 2001 September 15
8294**
8295** The author disclaims copyright to this source code.  In place of
8296** a legal notice, here is a blessing:
8297**
8298**    May you do good and not evil.
8299**    May you find forgiveness for yourself and forgive others.
8300**    May you share freely, never taking more than you give.
8301**
8302*************************************************************************
8303** This header file defines the interface that the sqlite page cache
8304** subsystem.  The page cache subsystem reads and writes a file a page
8305** at a time and provides a journal for rollback.
8306*/
8307
8308#ifndef _PAGER_H_
8309#define _PAGER_H_
8310
8311/*
8312** Default maximum size for persistent journal files. A negative
8313** value means no limit. This value may be overridden using the
8314** sqlite3PagerJournalSizeLimit() API. See also "PRAGMA journal_size_limit".
8315*/
8316#ifndef SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT
8317  #define SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT -1
8318#endif
8319
8320/*
8321** The type used to represent a page number.  The first page in a file
8322** is called page 1.  0 is used to represent "not a page".
8323*/
8324typedef u32 Pgno;
8325
8326/*
8327** Each open file is managed by a separate instance of the "Pager" structure.
8328*/
8329typedef struct Pager Pager;
8330
8331/*
8332** Handle type for pages.
8333*/
8334typedef struct PgHdr DbPage;
8335
8336/*
8337** Page number PAGER_MJ_PGNO is never used in an SQLite database (it is
8338** reserved for working around a windows/posix incompatibility). It is
8339** used in the journal to signify that the remainder of the journal file
8340** is devoted to storing a master journal name - there are no more pages to
8341** roll back. See comments for function writeMasterJournal() in pager.c
8342** for details.
8343*/
8344#define PAGER_MJ_PGNO(x) ((Pgno)((PENDING_BYTE/((x)->pageSize))+1))
8345
8346/*
8347** Allowed values for the flags parameter to sqlite3PagerOpen().
8348**
8349** NOTE: These values must match the corresponding BTREE_ values in btree.h.
8350*/
8351#define PAGER_OMIT_JOURNAL  0x0001    /* Do not use a rollback journal */
8352#define PAGER_NO_READLOCK   0x0002    /* Omit readlocks on readonly files */
8353#define PAGER_MEMORY        0x0004    /* In-memory database */
8354
8355/*
8356** Valid values for the second argument to sqlite3PagerLockingMode().
8357*/
8358#define PAGER_LOCKINGMODE_QUERY      -1
8359#define PAGER_LOCKINGMODE_NORMAL      0
8360#define PAGER_LOCKINGMODE_EXCLUSIVE   1
8361
8362/*
8363** Numeric constants that encode the journalmode.
8364*/
8365#define PAGER_JOURNALMODE_QUERY     (-1)  /* Query the value of journalmode */
8366#define PAGER_JOURNALMODE_DELETE      0   /* Commit by deleting journal file */
8367#define PAGER_JOURNALMODE_PERSIST     1   /* Commit by zeroing journal header */
8368#define PAGER_JOURNALMODE_OFF         2   /* Journal omitted.  */
8369#define PAGER_JOURNALMODE_TRUNCATE    3   /* Commit by truncating journal */
8370#define PAGER_JOURNALMODE_MEMORY      4   /* In-memory journal file */
8371#define PAGER_JOURNALMODE_WAL         5   /* Use write-ahead logging */
8372
8373/*
8374** The remainder of this file contains the declarations of the functions
8375** that make up the Pager sub-system API. See source code comments for
8376** a detailed description of each routine.
8377*/
8378
8379/* Open and close a Pager connection. */
8380SQLITE_PRIVATE int sqlite3PagerOpen(
8381  sqlite3_vfs*,
8382  Pager **ppPager,
8383  const char*,
8384  int,
8385  int,
8386  int,
8387  void(*)(DbPage*)
8388);
8389SQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager);
8390SQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager*, int, unsigned char*);
8391
8392/* Functions used to configure a Pager object. */
8393SQLITE_PRIVATE void sqlite3PagerSetBusyhandler(Pager*, int(*)(void *), void *);
8394SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager*, u32*, int);
8395SQLITE_PRIVATE int sqlite3PagerMaxPageCount(Pager*, int);
8396SQLITE_PRIVATE void sqlite3PagerSetCachesize(Pager*, int);
8397SQLITE_PRIVATE void sqlite3PagerSetSafetyLevel(Pager*,int,int,int);
8398SQLITE_PRIVATE int sqlite3PagerLockingMode(Pager *, int);
8399SQLITE_PRIVATE int sqlite3PagerSetJournalMode(Pager *, int);
8400SQLITE_PRIVATE int sqlite3PagerGetJournalMode(Pager*);
8401SQLITE_PRIVATE int sqlite3PagerOkToChangeJournalMode(Pager*);
8402SQLITE_PRIVATE i64 sqlite3PagerJournalSizeLimit(Pager *, i64);
8403SQLITE_PRIVATE sqlite3_backup **sqlite3PagerBackupPtr(Pager*);
8404
8405/* Functions used to obtain and release page references. */
8406SQLITE_PRIVATE int sqlite3PagerAcquire(Pager *pPager, Pgno pgno, DbPage **ppPage, int clrFlag);
8407#define sqlite3PagerGet(A,B,C) sqlite3PagerAcquire(A,B,C,0)
8408SQLITE_PRIVATE DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno);
8409SQLITE_PRIVATE void sqlite3PagerRef(DbPage*);
8410SQLITE_PRIVATE void sqlite3PagerUnref(DbPage*);
8411
8412/* Operations on page references. */
8413SQLITE_PRIVATE int sqlite3PagerWrite(DbPage*);
8414SQLITE_PRIVATE void sqlite3PagerDontWrite(DbPage*);
8415SQLITE_PRIVATE int sqlite3PagerMovepage(Pager*,DbPage*,Pgno,int);
8416SQLITE_PRIVATE int sqlite3PagerPageRefcount(DbPage*);
8417SQLITE_PRIVATE void *sqlite3PagerGetData(DbPage *);
8418SQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *);
8419
8420/* Functions used to manage pager transactions and savepoints. */
8421SQLITE_PRIVATE void sqlite3PagerPagecount(Pager*, int*);
8422SQLITE_PRIVATE int sqlite3PagerBegin(Pager*, int exFlag, int);
8423SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(Pager*,const char *zMaster, int);
8424SQLITE_PRIVATE int sqlite3PagerExclusiveLock(Pager*);
8425SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager);
8426SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager*);
8427SQLITE_PRIVATE int sqlite3PagerRollback(Pager*);
8428SQLITE_PRIVATE int sqlite3PagerOpenSavepoint(Pager *pPager, int n);
8429SQLITE_PRIVATE int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint);
8430SQLITE_PRIVATE int sqlite3PagerSharedLock(Pager *pPager);
8431
8432SQLITE_PRIVATE int sqlite3PagerCheckpoint(Pager *pPager, int, int*, int*);
8433SQLITE_PRIVATE int sqlite3PagerWalSupported(Pager *pPager);
8434SQLITE_PRIVATE int sqlite3PagerWalCallback(Pager *pPager);
8435SQLITE_PRIVATE int sqlite3PagerOpenWal(Pager *pPager, int *pisOpen);
8436SQLITE_PRIVATE int sqlite3PagerCloseWal(Pager *pPager);
8437
8438/* Functions used to query pager state and configuration. */
8439SQLITE_PRIVATE u8 sqlite3PagerIsreadonly(Pager*);
8440SQLITE_PRIVATE int sqlite3PagerRefcount(Pager*);
8441SQLITE_PRIVATE int sqlite3PagerMemUsed(Pager*);
8442SQLITE_PRIVATE const char *sqlite3PagerFilename(Pager*);
8443SQLITE_PRIVATE const sqlite3_vfs *sqlite3PagerVfs(Pager*);
8444SQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager*);
8445SQLITE_PRIVATE const char *sqlite3PagerJournalname(Pager*);
8446SQLITE_PRIVATE int sqlite3PagerNosync(Pager*);
8447SQLITE_PRIVATE void *sqlite3PagerTempSpace(Pager*);
8448SQLITE_PRIVATE int sqlite3PagerIsMemdb(Pager*);
8449
8450/* Functions used to truncate the database file. */
8451SQLITE_PRIVATE void sqlite3PagerTruncateImage(Pager*,Pgno);
8452
8453#if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_WAL)
8454SQLITE_PRIVATE void *sqlite3PagerCodec(DbPage *);
8455#endif
8456
8457/* Functions to support testing and debugging. */
8458#if !defined(NDEBUG) || defined(SQLITE_TEST)
8459SQLITE_PRIVATE   Pgno sqlite3PagerPagenumber(DbPage*);
8460SQLITE_PRIVATE   int sqlite3PagerIswriteable(DbPage*);
8461#endif
8462#ifdef SQLITE_TEST
8463SQLITE_PRIVATE   int *sqlite3PagerStats(Pager*);
8464SQLITE_PRIVATE   void sqlite3PagerRefdump(Pager*);
8465  void disable_simulated_io_errors(void);
8466  void enable_simulated_io_errors(void);
8467#else
8468# define disable_simulated_io_errors()
8469# define enable_simulated_io_errors()
8470#endif
8471
8472#endif /* _PAGER_H_ */
8473
8474/************** End of pager.h ***********************************************/
8475/************** Continuing where we left off in sqliteInt.h ******************/
8476/************** Include pcache.h in the middle of sqliteInt.h ****************/
8477/************** Begin file pcache.h ******************************************/
8478/*
8479** 2008 August 05
8480**
8481** The author disclaims copyright to this source code.  In place of
8482** a legal notice, here is a blessing:
8483**
8484**    May you do good and not evil.
8485**    May you find forgiveness for yourself and forgive others.
8486**    May you share freely, never taking more than you give.
8487**
8488*************************************************************************
8489** This header file defines the interface that the sqlite page cache
8490** subsystem.
8491*/
8492
8493#ifndef _PCACHE_H_
8494
8495typedef struct PgHdr PgHdr;
8496typedef struct PCache PCache;
8497
8498/*
8499** Every page in the cache is controlled by an instance of the following
8500** structure.
8501*/
8502struct PgHdr {
8503  void *pData;                   /* Content of this page */
8504  void *pExtra;                  /* Extra content */
8505  PgHdr *pDirty;                 /* Transient list of dirty pages */
8506  Pgno pgno;                     /* Page number for this page */
8507  Pager *pPager;                 /* The pager this page is part of */
8508#ifdef SQLITE_CHECK_PAGES
8509  u32 pageHash;                  /* Hash of page content */
8510#endif
8511  u16 flags;                     /* PGHDR flags defined below */
8512
8513  /**********************************************************************
8514  ** Elements above are public.  All that follows is private to pcache.c
8515  ** and should not be accessed by other modules.
8516  */
8517  i16 nRef;                      /* Number of users of this page */
8518  PCache *pCache;                /* Cache that owns this page */
8519
8520  PgHdr *pDirtyNext;             /* Next element in list of dirty pages */
8521  PgHdr *pDirtyPrev;             /* Previous element in list of dirty pages */
8522};
8523
8524/* Bit values for PgHdr.flags */
8525#define PGHDR_DIRTY             0x002  /* Page has changed */
8526#define PGHDR_NEED_SYNC         0x004  /* Fsync the rollback journal before
8527                                       ** writing this page to the database */
8528#define PGHDR_NEED_READ         0x008  /* Content is unread */
8529#define PGHDR_REUSE_UNLIKELY    0x010  /* A hint that reuse is unlikely */
8530#define PGHDR_DONT_WRITE        0x020  /* Do not write content to disk */
8531
8532/* Initialize and shutdown the page cache subsystem */
8533SQLITE_PRIVATE int sqlite3PcacheInitialize(void);
8534SQLITE_PRIVATE void sqlite3PcacheShutdown(void);
8535
8536/* Page cache buffer management:
8537** These routines implement SQLITE_CONFIG_PAGECACHE.
8538*/
8539SQLITE_PRIVATE void sqlite3PCacheBufferSetup(void *, int sz, int n);
8540
8541/* Create a new pager cache.
8542** Under memory stress, invoke xStress to try to make pages clean.
8543** Only clean and unpinned pages can be reclaimed.
8544*/
8545SQLITE_PRIVATE void sqlite3PcacheOpen(
8546  int szPage,                    /* Size of every page */
8547  int szExtra,                   /* Extra space associated with each page */
8548  int bPurgeable,                /* True if pages are on backing store */
8549  int (*xStress)(void*, PgHdr*), /* Call to try to make pages clean */
8550  void *pStress,                 /* Argument to xStress */
8551  PCache *pToInit                /* Preallocated space for the PCache */
8552);
8553
8554/* Modify the page-size after the cache has been created. */
8555SQLITE_PRIVATE void sqlite3PcacheSetPageSize(PCache *, int);
8556
8557/* Return the size in bytes of a PCache object.  Used to preallocate
8558** storage space.
8559*/
8560SQLITE_PRIVATE int sqlite3PcacheSize(void);
8561
8562/* One release per successful fetch.  Page is pinned until released.
8563** Reference counted.
8564*/
8565SQLITE_PRIVATE int sqlite3PcacheFetch(PCache*, Pgno, int createFlag, PgHdr**);
8566SQLITE_PRIVATE void sqlite3PcacheRelease(PgHdr*);
8567
8568SQLITE_PRIVATE void sqlite3PcacheDrop(PgHdr*);         /* Remove page from cache */
8569SQLITE_PRIVATE void sqlite3PcacheMakeDirty(PgHdr*);    /* Make sure page is marked dirty */
8570SQLITE_PRIVATE void sqlite3PcacheMakeClean(PgHdr*);    /* Mark a single page as clean */
8571SQLITE_PRIVATE void sqlite3PcacheCleanAll(PCache*);    /* Mark all dirty list pages as clean */
8572
8573/* Change a page number.  Used by incr-vacuum. */
8574SQLITE_PRIVATE void sqlite3PcacheMove(PgHdr*, Pgno);
8575
8576/* Remove all pages with pgno>x.  Reset the cache if x==0 */
8577SQLITE_PRIVATE void sqlite3PcacheTruncate(PCache*, Pgno x);
8578
8579/* Get a list of all dirty pages in the cache, sorted by page number */
8580SQLITE_PRIVATE PgHdr *sqlite3PcacheDirtyList(PCache*);
8581
8582/* Reset and close the cache object */
8583SQLITE_PRIVATE void sqlite3PcacheClose(PCache*);
8584
8585/* Clear flags from pages of the page cache */
8586SQLITE_PRIVATE void sqlite3PcacheClearSyncFlags(PCache *);
8587
8588/* Discard the contents of the cache */
8589SQLITE_PRIVATE void sqlite3PcacheClear(PCache*);
8590
8591/* Return the total number of outstanding page references */
8592SQLITE_PRIVATE int sqlite3PcacheRefCount(PCache*);
8593
8594/* Increment the reference count of an existing page */
8595SQLITE_PRIVATE void sqlite3PcacheRef(PgHdr*);
8596
8597SQLITE_PRIVATE int sqlite3PcachePageRefcount(PgHdr*);
8598
8599/* Return the total number of pages stored in the cache */
8600SQLITE_PRIVATE int sqlite3PcachePagecount(PCache*);
8601
8602#if defined(SQLITE_CHECK_PAGES) || defined(SQLITE_DEBUG)
8603/* Iterate through all dirty pages currently stored in the cache. This
8604** interface is only available if SQLITE_CHECK_PAGES is defined when the
8605** library is built.
8606*/
8607SQLITE_PRIVATE void sqlite3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHdr *));
8608#endif
8609
8610/* Set and get the suggested cache-size for the specified pager-cache.
8611**
8612** If no global maximum is configured, then the system attempts to limit
8613** the total number of pages cached by purgeable pager-caches to the sum
8614** of the suggested cache-sizes.
8615*/
8616SQLITE_PRIVATE void sqlite3PcacheSetCachesize(PCache *, int);
8617#ifdef SQLITE_TEST
8618SQLITE_PRIVATE int sqlite3PcacheGetCachesize(PCache *);
8619#endif
8620
8621#ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
8622/* Try to return memory used by the pcache module to the main memory heap */
8623SQLITE_PRIVATE int sqlite3PcacheReleaseMemory(int);
8624#endif
8625
8626#ifdef SQLITE_TEST
8627SQLITE_PRIVATE void sqlite3PcacheStats(int*,int*,int*,int*);
8628#endif
8629
8630SQLITE_PRIVATE void sqlite3PCacheSetDefault(void);
8631
8632#endif /* _PCACHE_H_ */
8633
8634/************** End of pcache.h **********************************************/
8635/************** Continuing where we left off in sqliteInt.h ******************/
8636
8637/************** Include os.h in the middle of sqliteInt.h ********************/
8638/************** Begin file os.h **********************************************/
8639/*
8640** 2001 September 16
8641**
8642** The author disclaims copyright to this source code.  In place of
8643** a legal notice, here is a blessing:
8644**
8645**    May you do good and not evil.
8646**    May you find forgiveness for yourself and forgive others.
8647**    May you share freely, never taking more than you give.
8648**
8649******************************************************************************
8650**
8651** This header file (together with is companion C source-code file
8652** "os.c") attempt to abstract the underlying operating system so that
8653** the SQLite library will work on both POSIX and windows systems.
8654**
8655** This header file is #include-ed by sqliteInt.h and thus ends up
8656** being included by every source file.
8657*/
8658#ifndef _SQLITE_OS_H_
8659#define _SQLITE_OS_H_
8660
8661/*
8662** Figure out if we are dealing with Unix, Windows, or some other
8663** operating system.  After the following block of preprocess macros,
8664** all of SQLITE_OS_UNIX, SQLITE_OS_WIN, SQLITE_OS_OS2, and SQLITE_OS_OTHER
8665** will defined to either 1 or 0.  One of the four will be 1.  The other
8666** three will be 0.
8667*/
8668#if defined(SQLITE_OS_OTHER)
8669# if SQLITE_OS_OTHER==1
8670#   undef SQLITE_OS_UNIX
8671#   define SQLITE_OS_UNIX 0
8672#   undef SQLITE_OS_WIN
8673#   define SQLITE_OS_WIN 0
8674#   undef SQLITE_OS_OS2
8675#   define SQLITE_OS_OS2 0
8676# else
8677#   undef SQLITE_OS_OTHER
8678# endif
8679#endif
8680#if !defined(SQLITE_OS_UNIX) && !defined(SQLITE_OS_OTHER)
8681# define SQLITE_OS_OTHER 0
8682# ifndef SQLITE_OS_WIN
8683#   if defined(_WIN32) || defined(WIN32) || defined(__CYGWIN__) || defined(__MINGW32__) || defined(__BORLANDC__)
8684#     define SQLITE_OS_WIN 1
8685#     define SQLITE_OS_UNIX 0
8686#     define SQLITE_OS_OS2 0
8687#   elif defined(__EMX__) || defined(_OS2) || defined(OS2) || defined(_OS2_) || defined(__OS2__)
8688#     define SQLITE_OS_WIN 0
8689#     define SQLITE_OS_UNIX 0
8690#     define SQLITE_OS_OS2 1
8691#   else
8692#     define SQLITE_OS_WIN 0
8693#     define SQLITE_OS_UNIX 1
8694#     define SQLITE_OS_OS2 0
8695#  endif
8696# else
8697#  define SQLITE_OS_UNIX 0
8698#  define SQLITE_OS_OS2 0
8699# endif
8700#else
8701# ifndef SQLITE_OS_WIN
8702#  define SQLITE_OS_WIN 0
8703# endif
8704#endif
8705
8706/*
8707** Determine if we are dealing with WindowsCE - which has a much
8708** reduced API.
8709*/
8710#if defined(_WIN32_WCE)
8711# define SQLITE_OS_WINCE 1
8712#else
8713# define SQLITE_OS_WINCE 0
8714#endif
8715
8716
8717/*
8718** Define the maximum size of a temporary filename
8719*/
8720#if SQLITE_OS_WIN
8721# include <windows.h>
8722# define SQLITE_TEMPNAME_SIZE (MAX_PATH+50)
8723#elif SQLITE_OS_OS2
8724# if (__GNUC__ > 3 || __GNUC__ == 3 && __GNUC_MINOR__ >= 3) && defined(OS2_HIGH_MEMORY)
8725#  include <os2safe.h> /* has to be included before os2.h for linking to work */
8726# endif
8727# define INCL_DOSDATETIME
8728# define INCL_DOSFILEMGR
8729# define INCL_DOSERRORS
8730# define INCL_DOSMISC
8731# define INCL_DOSPROCESS
8732# define INCL_DOSMODULEMGR
8733# define INCL_DOSSEMAPHORES
8734# include <os2.h>
8735# include <uconv.h>
8736# define SQLITE_TEMPNAME_SIZE (CCHMAXPATHCOMP)
8737#else
8738# define SQLITE_TEMPNAME_SIZE 200
8739#endif
8740
8741/* If the SET_FULLSYNC macro is not defined above, then make it
8742** a no-op
8743*/
8744#ifndef SET_FULLSYNC
8745# define SET_FULLSYNC(x,y)
8746#endif
8747
8748/*
8749** The default size of a disk sector
8750*/
8751#ifndef SQLITE_DEFAULT_SECTOR_SIZE
8752# define SQLITE_DEFAULT_SECTOR_SIZE 512
8753#endif
8754
8755/*
8756** Temporary files are named starting with this prefix followed by 16 random
8757** alphanumeric characters, and no file extension. They are stored in the
8758** OS's standard temporary file directory, and are deleted prior to exit.
8759** If sqlite is being embedded in another program, you may wish to change the
8760** prefix to reflect your program's name, so that if your program exits
8761** prematurely, old temporary files can be easily identified. This can be done
8762** using -DSQLITE_TEMP_FILE_PREFIX=myprefix_ on the compiler command line.
8763**
8764** 2006-10-31:  The default prefix used to be "sqlite_".  But then
8765** Mcafee started using SQLite in their anti-virus product and it
8766** started putting files with the "sqlite" name in the c:/temp folder.
8767** This annoyed many windows users.  Those users would then do a
8768** Google search for "sqlite", find the telephone numbers of the
8769** developers and call to wake them up at night and complain.
8770** For this reason, the default name prefix is changed to be "sqlite"
8771** spelled backwards.  So the temp files are still identified, but
8772** anybody smart enough to figure out the code is also likely smart
8773** enough to know that calling the developer will not help get rid
8774** of the file.
8775*/
8776#ifndef SQLITE_TEMP_FILE_PREFIX
8777# define SQLITE_TEMP_FILE_PREFIX "etilqs_"
8778#endif
8779
8780/*
8781** The following values may be passed as the second argument to
8782** sqlite3OsLock(). The various locks exhibit the following semantics:
8783**
8784** SHARED:    Any number of processes may hold a SHARED lock simultaneously.
8785** RESERVED:  A single process may hold a RESERVED lock on a file at
8786**            any time. Other processes may hold and obtain new SHARED locks.
8787** PENDING:   A single process may hold a PENDING lock on a file at
8788**            any one time. Existing SHARED locks may persist, but no new
8789**            SHARED locks may be obtained by other processes.
8790** EXCLUSIVE: An EXCLUSIVE lock precludes all other locks.
8791**
8792** PENDING_LOCK may not be passed directly to sqlite3OsLock(). Instead, a
8793** process that requests an EXCLUSIVE lock may actually obtain a PENDING
8794** lock. This can be upgraded to an EXCLUSIVE lock by a subsequent call to
8795** sqlite3OsLock().
8796*/
8797#define NO_LOCK         0
8798#define SHARED_LOCK     1
8799#define RESERVED_LOCK   2
8800#define PENDING_LOCK    3
8801#define EXCLUSIVE_LOCK  4
8802
8803/*
8804** File Locking Notes:  (Mostly about windows but also some info for Unix)
8805**
8806** We cannot use LockFileEx() or UnlockFileEx() on Win95/98/ME because
8807** those functions are not available.  So we use only LockFile() and
8808** UnlockFile().
8809**
8810** LockFile() prevents not just writing but also reading by other processes.
8811** A SHARED_LOCK is obtained by locking a single randomly-chosen
8812** byte out of a specific range of bytes. The lock byte is obtained at
8813** random so two separate readers can probably access the file at the
8814** same time, unless they are unlucky and choose the same lock byte.
8815** An EXCLUSIVE_LOCK is obtained by locking all bytes in the range.
8816** There can only be one writer.  A RESERVED_LOCK is obtained by locking
8817** a single byte of the file that is designated as the reserved lock byte.
8818** A PENDING_LOCK is obtained by locking a designated byte different from
8819** the RESERVED_LOCK byte.
8820**
8821** On WinNT/2K/XP systems, LockFileEx() and UnlockFileEx() are available,
8822** which means we can use reader/writer locks.  When reader/writer locks
8823** are used, the lock is placed on the same range of bytes that is used
8824** for probabilistic locking in Win95/98/ME.  Hence, the locking scheme
8825** will support two or more Win95 readers or two or more WinNT readers.
8826** But a single Win95 reader will lock out all WinNT readers and a single
8827** WinNT reader will lock out all other Win95 readers.
8828**
8829** The following #defines specify the range of bytes used for locking.
8830** SHARED_SIZE is the number of bytes available in the pool from which
8831** a random byte is selected for a shared lock.  The pool of bytes for
8832** shared locks begins at SHARED_FIRST.
8833**
8834** The same locking strategy and
8835** byte ranges are used for Unix.  This leaves open the possiblity of having
8836** clients on win95, winNT, and unix all talking to the same shared file
8837** and all locking correctly.  To do so would require that samba (or whatever
8838** tool is being used for file sharing) implements locks correctly between
8839** windows and unix.  I'm guessing that isn't likely to happen, but by
8840** using the same locking range we are at least open to the possibility.
8841**
8842** Locking in windows is manditory.  For this reason, we cannot store
8843** actual data in the bytes used for locking.  The pager never allocates
8844** the pages involved in locking therefore.  SHARED_SIZE is selected so
8845** that all locks will fit on a single page even at the minimum page size.
8846** PENDING_BYTE defines the beginning of the locks.  By default PENDING_BYTE
8847** is set high so that we don't have to allocate an unused page except
8848** for very large databases.  But one should test the page skipping logic
8849** by setting PENDING_BYTE low and running the entire regression suite.
8850**
8851** Changing the value of PENDING_BYTE results in a subtly incompatible
8852** file format.  Depending on how it is changed, you might not notice
8853** the incompatibility right away, even running a full regression test.
8854** The default location of PENDING_BYTE is the first byte past the
8855** 1GB boundary.
8856**
8857*/
8858#ifdef SQLITE_OMIT_WSD
8859# define PENDING_BYTE     (0x40000000)
8860#else
8861# define PENDING_BYTE      sqlite3PendingByte
8862#endif
8863#define RESERVED_BYTE     (PENDING_BYTE+1)
8864#define SHARED_FIRST      (PENDING_BYTE+2)
8865#define SHARED_SIZE       510
8866
8867/*
8868** Wrapper around OS specific sqlite3_os_init() function.
8869*/
8870SQLITE_PRIVATE int sqlite3OsInit(void);
8871
8872/*
8873** Functions for accessing sqlite3_file methods
8874*/
8875SQLITE_PRIVATE int sqlite3OsClose(sqlite3_file*);
8876SQLITE_PRIVATE int sqlite3OsRead(sqlite3_file*, void*, int amt, i64 offset);
8877SQLITE_PRIVATE int sqlite3OsWrite(sqlite3_file*, const void*, int amt, i64 offset);
8878SQLITE_PRIVATE int sqlite3OsTruncate(sqlite3_file*, i64 size);
8879SQLITE_PRIVATE int sqlite3OsSync(sqlite3_file*, int);
8880SQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file*, i64 *pSize);
8881SQLITE_PRIVATE int sqlite3OsLock(sqlite3_file*, int);
8882SQLITE_PRIVATE int sqlite3OsUnlock(sqlite3_file*, int);
8883SQLITE_PRIVATE int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut);
8884SQLITE_PRIVATE int sqlite3OsFileControl(sqlite3_file*,int,void*);
8885#define SQLITE_FCNTL_DB_UNCHANGED 0xca093fa0
8886SQLITE_PRIVATE int sqlite3OsSectorSize(sqlite3_file *id);
8887SQLITE_PRIVATE int sqlite3OsDeviceCharacteristics(sqlite3_file *id);
8888SQLITE_PRIVATE int sqlite3OsShmMap(sqlite3_file *,int,int,int,void volatile **);
8889SQLITE_PRIVATE int sqlite3OsShmLock(sqlite3_file *id, int, int, int);
8890SQLITE_PRIVATE void sqlite3OsShmBarrier(sqlite3_file *id);
8891SQLITE_PRIVATE int sqlite3OsShmUnmap(sqlite3_file *id, int);
8892
8893/*
8894** Functions for accessing sqlite3_vfs methods
8895*/
8896SQLITE_PRIVATE int sqlite3OsOpen(sqlite3_vfs *, const char *, sqlite3_file*, int, int *);
8897SQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *, const char *, int);
8898SQLITE_PRIVATE int sqlite3OsAccess(sqlite3_vfs *, const char *, int, int *pResOut);
8899SQLITE_PRIVATE int sqlite3OsFullPathname(sqlite3_vfs *, const char *, int, char *);
8900#ifndef SQLITE_OMIT_LOAD_EXTENSION
8901SQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *, const char *);
8902SQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *, int, char *);
8903SQLITE_PRIVATE void (*sqlite3OsDlSym(sqlite3_vfs *, void *, const char *))(void);
8904SQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *, void *);
8905#endif /* SQLITE_OMIT_LOAD_EXTENSION */
8906SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *, int, char *);
8907SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *, int);
8908SQLITE_PRIVATE int sqlite3OsCurrentTimeInt64(sqlite3_vfs *, sqlite3_int64*);
8909
8910/*
8911** Convenience functions for opening and closing files using
8912** sqlite3_malloc() to obtain space for the file-handle structure.
8913*/
8914SQLITE_PRIVATE int sqlite3OsOpenMalloc(sqlite3_vfs *, const char *, sqlite3_file **, int,int*);
8915SQLITE_PRIVATE int sqlite3OsCloseFree(sqlite3_file *);
8916
8917#endif /* _SQLITE_OS_H_ */
8918
8919/************** End of os.h **************************************************/
8920/************** Continuing where we left off in sqliteInt.h ******************/
8921/************** Include mutex.h in the middle of sqliteInt.h *****************/
8922/************** Begin file mutex.h *******************************************/
8923/*
8924** 2007 August 28
8925**
8926** The author disclaims copyright to this source code.  In place of
8927** a legal notice, here is a blessing:
8928**
8929**    May you do good and not evil.
8930**    May you find forgiveness for yourself and forgive others.
8931**    May you share freely, never taking more than you give.
8932**
8933*************************************************************************
8934**
8935** This file contains the common header for all mutex implementations.
8936** The sqliteInt.h header #includes this file so that it is available
8937** to all source files.  We break it out in an effort to keep the code
8938** better organized.
8939**
8940** NOTE:  source files should *not* #include this header file directly.
8941** Source files should #include the sqliteInt.h file and let that file
8942** include this one indirectly.
8943*/
8944
8945
8946/*
8947** Figure out what version of the code to use.  The choices are
8948**
8949**   SQLITE_MUTEX_OMIT         No mutex logic.  Not even stubs.  The
8950**                             mutexes implemention cannot be overridden
8951**                             at start-time.
8952**
8953**   SQLITE_MUTEX_NOOP         For single-threaded applications.  No
8954**                             mutual exclusion is provided.  But this
8955**                             implementation can be overridden at
8956**                             start-time.
8957**
8958**   SQLITE_MUTEX_PTHREADS     For multi-threaded applications on Unix.
8959**
8960**   SQLITE_MUTEX_W32          For multi-threaded applications on Win32.
8961**
8962**   SQLITE_MUTEX_OS2          For multi-threaded applications on OS/2.
8963*/
8964#if !SQLITE_THREADSAFE
8965# define SQLITE_MUTEX_OMIT
8966#endif
8967#if SQLITE_THREADSAFE && !defined(SQLITE_MUTEX_NOOP)
8968#  if SQLITE_OS_UNIX
8969#    define SQLITE_MUTEX_PTHREADS
8970#  elif SQLITE_OS_WIN
8971#    define SQLITE_MUTEX_W32
8972#  elif SQLITE_OS_OS2
8973#    define SQLITE_MUTEX_OS2
8974#  else
8975#    define SQLITE_MUTEX_NOOP
8976#  endif
8977#endif
8978
8979#ifdef SQLITE_MUTEX_OMIT
8980/*
8981** If this is a no-op implementation, implement everything as macros.
8982*/
8983#define sqlite3_mutex_alloc(X)    ((sqlite3_mutex*)8)
8984#define sqlite3_mutex_free(X)
8985#define sqlite3_mutex_enter(X)
8986#define sqlite3_mutex_try(X)      SQLITE_OK
8987#define sqlite3_mutex_leave(X)
8988#define sqlite3_mutex_held(X)     ((void)(X),1)
8989#define sqlite3_mutex_notheld(X)  ((void)(X),1)
8990#define sqlite3MutexAlloc(X)      ((sqlite3_mutex*)8)
8991#define sqlite3MutexInit()        SQLITE_OK
8992#define sqlite3MutexEnd()
8993#endif /* defined(SQLITE_MUTEX_OMIT) */
8994
8995/************** End of mutex.h ***********************************************/
8996/************** Continuing where we left off in sqliteInt.h ******************/
8997
8998
8999/*
9000** Each database file to be accessed by the system is an instance
9001** of the following structure.  There are normally two of these structures
9002** in the sqlite.aDb[] array.  aDb[0] is the main database file and
9003** aDb[1] is the database file used to hold temporary tables.  Additional
9004** databases may be attached.
9005*/
9006struct Db {
9007  char *zName;         /* Name of this database */
9008  Btree *pBt;          /* The B*Tree structure for this database file */
9009  u8 inTrans;          /* 0: not writable.  1: Transaction.  2: Checkpoint */
9010  u8 safety_level;     /* How aggressive at syncing data to disk */
9011  Schema *pSchema;     /* Pointer to database schema (possibly shared) */
9012};
9013
9014/*
9015** An instance of the following structure stores a database schema.
9016**
9017** Most Schema objects are associated with a Btree.  The exception is
9018** the Schema for the TEMP databaes (sqlite3.aDb[1]) which is free-standing.
9019** In shared cache mode, a single Schema object can be shared by multiple
9020** Btrees that refer to the same underlying BtShared object.
9021**
9022** Schema objects are automatically deallocated when the last Btree that
9023** references them is destroyed.   The TEMP Schema is manually freed by
9024** sqlite3_close().
9025*
9026** A thread must be holding a mutex on the corresponding Btree in order
9027** to access Schema content.  This implies that the thread must also be
9028** holding a mutex on the sqlite3 connection pointer that owns the Btree.
9029** For a TEMP Schema, on the connection mutex is required.
9030*/
9031struct Schema {
9032  int schema_cookie;   /* Database schema version number for this file */
9033  int iGeneration;     /* Generation counter.  Incremented with each change */
9034  Hash tblHash;        /* All tables indexed by name */
9035  Hash idxHash;        /* All (named) indices indexed by name */
9036  Hash trigHash;       /* All triggers indexed by name */
9037  Hash fkeyHash;       /* All foreign keys by referenced table name */
9038  Table *pSeqTab;      /* The sqlite_sequence table used by AUTOINCREMENT */
9039  u8 file_format;      /* Schema format version for this file */
9040  u8 enc;              /* Text encoding used by this database */
9041  u16 flags;           /* Flags associated with this schema */
9042  int cache_size;      /* Number of pages to use in the cache */
9043};
9044
9045/*
9046** These macros can be used to test, set, or clear bits in the
9047** Db.pSchema->flags field.
9048*/
9049#define DbHasProperty(D,I,P)     (((D)->aDb[I].pSchema->flags&(P))==(P))
9050#define DbHasAnyProperty(D,I,P)  (((D)->aDb[I].pSchema->flags&(P))!=0)
9051#define DbSetProperty(D,I,P)     (D)->aDb[I].pSchema->flags|=(P)
9052#define DbClearProperty(D,I,P)   (D)->aDb[I].pSchema->flags&=~(P)
9053
9054/*
9055** Allowed values for the DB.pSchema->flags field.
9056**
9057** The DB_SchemaLoaded flag is set after the database schema has been
9058** read into internal hash tables.
9059**
9060** DB_UnresetViews means that one or more views have column names that
9061** have been filled out.  If the schema changes, these column names might
9062** changes and so the view will need to be reset.
9063*/
9064#define DB_SchemaLoaded    0x0001  /* The schema has been loaded */
9065#define DB_UnresetViews    0x0002  /* Some views have defined column names */
9066#define DB_Empty           0x0004  /* The file is empty (length 0 bytes) */
9067
9068/*
9069** The number of different kinds of things that can be limited
9070** using the sqlite3_limit() interface.
9071*/
9072#define SQLITE_N_LIMIT (SQLITE_LIMIT_TRIGGER_DEPTH+1)
9073
9074/*
9075** Lookaside malloc is a set of fixed-size buffers that can be used
9076** to satisfy small transient memory allocation requests for objects
9077** associated with a particular database connection.  The use of
9078** lookaside malloc provides a significant performance enhancement
9079** (approx 10%) by avoiding numerous malloc/free requests while parsing
9080** SQL statements.
9081**
9082** The Lookaside structure holds configuration information about the
9083** lookaside malloc subsystem.  Each available memory allocation in
9084** the lookaside subsystem is stored on a linked list of LookasideSlot
9085** objects.
9086**
9087** Lookaside allocations are only allowed for objects that are associated
9088** with a particular database connection.  Hence, schema information cannot
9089** be stored in lookaside because in shared cache mode the schema information
9090** is shared by multiple database connections.  Therefore, while parsing
9091** schema information, the Lookaside.bEnabled flag is cleared so that
9092** lookaside allocations are not used to construct the schema objects.
9093*/
9094struct Lookaside {
9095  u16 sz;                 /* Size of each buffer in bytes */
9096  u8 bEnabled;            /* False to disable new lookaside allocations */
9097  u8 bMalloced;           /* True if pStart obtained from sqlite3_malloc() */
9098  int nOut;               /* Number of buffers currently checked out */
9099  int mxOut;              /* Highwater mark for nOut */
9100  int anStat[3];          /* 0: hits.  1: size misses.  2: full misses */
9101  LookasideSlot *pFree;   /* List of available buffers */
9102  void *pStart;           /* First byte of available memory space */
9103  void *pEnd;             /* First byte past end of available space */
9104};
9105struct LookasideSlot {
9106  LookasideSlot *pNext;    /* Next buffer in the list of free buffers */
9107};
9108
9109/*
9110** A hash table for function definitions.
9111**
9112** Hash each FuncDef structure into one of the FuncDefHash.a[] slots.
9113** Collisions are on the FuncDef.pHash chain.
9114*/
9115struct FuncDefHash {
9116  FuncDef *a[23];       /* Hash table for functions */
9117};
9118
9119/*
9120** Each database connection is an instance of the following structure.
9121**
9122** The sqlite.lastRowid records the last insert rowid generated by an
9123** insert statement.  Inserts on views do not affect its value.  Each
9124** trigger has its own context, so that lastRowid can be updated inside
9125** triggers as usual.  The previous value will be restored once the trigger
9126** exits.  Upon entering a before or instead of trigger, lastRowid is no
9127** longer (since after version 2.8.12) reset to -1.
9128**
9129** The sqlite.nChange does not count changes within triggers and keeps no
9130** context.  It is reset at start of sqlite3_exec.
9131** The sqlite.lsChange represents the number of changes made by the last
9132** insert, update, or delete statement.  It remains constant throughout the
9133** length of a statement and is then updated by OP_SetCounts.  It keeps a
9134** context stack just like lastRowid so that the count of changes
9135** within a trigger is not seen outside the trigger.  Changes to views do not
9136** affect the value of lsChange.
9137** The sqlite.csChange keeps track of the number of current changes (since
9138** the last statement) and is used to update sqlite_lsChange.
9139**
9140** The member variables sqlite.errCode, sqlite.zErrMsg and sqlite.zErrMsg16
9141** store the most recent error code and, if applicable, string. The
9142** internal function sqlite3Error() is used to set these variables
9143** consistently.
9144*/
9145struct sqlite3 {
9146  sqlite3_vfs *pVfs;            /* OS Interface */
9147  int nDb;                      /* Number of backends currently in use */
9148  Db *aDb;                      /* All backends */
9149  int flags;                    /* Miscellaneous flags. See below */
9150  int openFlags;                /* Flags passed to sqlite3_vfs.xOpen() */
9151  int errCode;                  /* Most recent error code (SQLITE_*) */
9152  int errMask;                  /* & result codes with this before returning */
9153  u8 autoCommit;                /* The auto-commit flag. */
9154  u8 temp_store;                /* 1: file 2: memory 0: default */
9155  u8 mallocFailed;              /* True if we have seen a malloc failure */
9156  u8 dfltLockMode;              /* Default locking-mode for attached dbs */
9157  signed char nextAutovac;      /* Autovac setting after VACUUM if >=0 */
9158  u8 suppressErr;               /* Do not issue error messages if true */
9159  int nextPagesize;             /* Pagesize after VACUUM if >0 */
9160  int nTable;                   /* Number of tables in the database */
9161  CollSeq *pDfltColl;           /* The default collating sequence (BINARY) */
9162  i64 lastRowid;                /* ROWID of most recent insert (see above) */
9163  u32 magic;                    /* Magic number for detect library misuse */
9164  int nChange;                  /* Value returned by sqlite3_changes() */
9165  int nTotalChange;             /* Value returned by sqlite3_total_changes() */
9166  sqlite3_mutex *mutex;         /* Connection mutex */
9167  int aLimit[SQLITE_N_LIMIT];   /* Limits */
9168  struct sqlite3InitInfo {      /* Information used during initialization */
9169    int iDb;                    /* When back is being initialized */
9170    int newTnum;                /* Rootpage of table being initialized */
9171    u8 busy;                    /* TRUE if currently initializing */
9172    u8 orphanTrigger;           /* Last statement is orphaned TEMP trigger */
9173  } init;
9174  int nExtension;               /* Number of loaded extensions */
9175  void **aExtension;            /* Array of shared library handles */
9176  struct Vdbe *pVdbe;           /* List of active virtual machines */
9177  int activeVdbeCnt;            /* Number of VDBEs currently executing */
9178  int writeVdbeCnt;             /* Number of active VDBEs that are writing */
9179  int vdbeExecCnt;              /* Number of nested calls to VdbeExec() */
9180  void (*xTrace)(void*,const char*);        /* Trace function */
9181  void *pTraceArg;                          /* Argument to the trace function */
9182  void (*xProfile)(void*,const char*,u64);  /* Profiling function */
9183  void *pProfileArg;                        /* Argument to profile function */
9184  void *pCommitArg;                 /* Argument to xCommitCallback() */
9185  int (*xCommitCallback)(void*);    /* Invoked at every commit. */
9186  void *pRollbackArg;               /* Argument to xRollbackCallback() */
9187  void (*xRollbackCallback)(void*); /* Invoked at every commit. */
9188  void *pUpdateArg;
9189  void (*xUpdateCallback)(void*,int, const char*,const char*,sqlite_int64);
9190#ifndef SQLITE_OMIT_WAL
9191  int (*xWalCallback)(void *, sqlite3 *, const char *, int);
9192  void *pWalArg;
9193#endif
9194  void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*);
9195  void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*);
9196  void *pCollNeededArg;
9197  sqlite3_value *pErr;          /* Most recent error message */
9198  char *zErrMsg;                /* Most recent error message (UTF-8 encoded) */
9199  char *zErrMsg16;              /* Most recent error message (UTF-16 encoded) */
9200  union {
9201    volatile int isInterrupted; /* True if sqlite3_interrupt has been called */
9202    double notUsed1;            /* Spacer */
9203  } u1;
9204  Lookaside lookaside;          /* Lookaside malloc configuration */
9205#ifndef SQLITE_OMIT_AUTHORIZATION
9206  int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
9207                                /* Access authorization function */
9208  void *pAuthArg;               /* 1st argument to the access auth function */
9209#endif
9210#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
9211  int (*xProgress)(void *);     /* The progress callback */
9212  void *pProgressArg;           /* Argument to the progress callback */
9213  int nProgressOps;             /* Number of opcodes for progress callback */
9214#endif
9215#ifndef SQLITE_OMIT_VIRTUALTABLE
9216  Hash aModule;                 /* populated by sqlite3_create_module() */
9217  Table *pVTab;                 /* vtab with active Connect/Create method */
9218  VTable **aVTrans;             /* Virtual tables with open transactions */
9219  int nVTrans;                  /* Allocated size of aVTrans */
9220  VTable *pDisconnect;    /* Disconnect these in next sqlite3_prepare() */
9221#endif
9222  FuncDefHash aFunc;            /* Hash table of connection functions */
9223  Hash aCollSeq;                /* All collating sequences */
9224  BusyHandler busyHandler;      /* Busy callback */
9225  int busyTimeout;              /* Busy handler timeout, in msec */
9226  Db aDbStatic[2];              /* Static space for the 2 default backends */
9227  Savepoint *pSavepoint;        /* List of active savepoints */
9228  int nSavepoint;               /* Number of non-transaction savepoints */
9229  int nStatement;               /* Number of nested statement-transactions  */
9230  u8 isTransactionSavepoint;    /* True if the outermost savepoint is a TS */
9231  i64 nDeferredCons;            /* Net deferred constraints this transaction. */
9232  int *pnBytesFreed;            /* If not NULL, increment this in DbFree() */
9233
9234#ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
9235  /* The following variables are all protected by the STATIC_MASTER
9236  ** mutex, not by sqlite3.mutex. They are used by code in notify.c.
9237  **
9238  ** When X.pUnlockConnection==Y, that means that X is waiting for Y to
9239  ** unlock so that it can proceed.
9240  **
9241  ** When X.pBlockingConnection==Y, that means that something that X tried
9242  ** tried to do recently failed with an SQLITE_LOCKED error due to locks
9243  ** held by Y.
9244  */
9245  sqlite3 *pBlockingConnection; /* Connection that caused SQLITE_LOCKED */
9246  sqlite3 *pUnlockConnection;           /* Connection to watch for unlock */
9247  void *pUnlockArg;                     /* Argument to xUnlockNotify */
9248  void (*xUnlockNotify)(void **, int);  /* Unlock notify callback */
9249  sqlite3 *pNextBlocked;        /* Next in list of all blocked connections */
9250#endif
9251};
9252
9253/*
9254** A macro to discover the encoding of a database.
9255*/
9256#define ENC(db) ((db)->aDb[0].pSchema->enc)
9257
9258/*
9259** Possible values for the sqlite3.flags.
9260*/
9261#define SQLITE_VdbeTrace      0x00000100  /* True to trace VDBE execution */
9262#define SQLITE_InternChanges  0x00000200  /* Uncommitted Hash table changes */
9263#define SQLITE_FullColNames   0x00000400  /* Show full column names on SELECT */
9264#define SQLITE_ShortColNames  0x00000800  /* Show short columns names */
9265#define SQLITE_CountRows      0x00001000  /* Count rows changed by INSERT, */
9266                                          /*   DELETE, or UPDATE and return */
9267                                          /*   the count using a callback. */
9268#define SQLITE_NullCallback   0x00002000  /* Invoke the callback once if the */
9269                                          /*   result set is empty */
9270#define SQLITE_SqlTrace       0x00004000  /* Debug print SQL as it executes */
9271#define SQLITE_VdbeListing    0x00008000  /* Debug listings of VDBE programs */
9272#define SQLITE_WriteSchema    0x00010000  /* OK to update SQLITE_MASTER */
9273#define SQLITE_NoReadlock     0x00020000  /* Readlocks are omitted when
9274                                          ** accessing read-only databases */
9275#define SQLITE_IgnoreChecks   0x00040000  /* Do not enforce check constraints */
9276#define SQLITE_ReadUncommitted 0x0080000  /* For shared-cache mode */
9277#define SQLITE_LegacyFileFmt  0x00100000  /* Create new databases in format 1 */
9278#define SQLITE_FullFSync      0x00200000  /* Use full fsync on the backend */
9279#define SQLITE_CkptFullFSync  0x00400000  /* Use full fsync for checkpoint */
9280#define SQLITE_RecoveryMode   0x00800000  /* Ignore schema errors */
9281#define SQLITE_ReverseOrder   0x01000000  /* Reverse unordered SELECTs */
9282#define SQLITE_RecTriggers    0x02000000  /* Enable recursive triggers */
9283#define SQLITE_ForeignKeys    0x04000000  /* Enforce foreign key constraints  */
9284#define SQLITE_AutoIndex      0x08000000  /* Enable automatic indexes */
9285#define SQLITE_PreferBuiltin  0x10000000  /* Preference to built-in funcs */
9286#define SQLITE_LoadExtension  0x20000000  /* Enable load_extension */
9287#define SQLITE_EnableTrigger  0x40000000  /* True to enable triggers */
9288
9289/*
9290** Bits of the sqlite3.flags field that are used by the
9291** sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS,...) interface.
9292** These must be the low-order bits of the flags field.
9293*/
9294#define SQLITE_QueryFlattener 0x01        /* Disable query flattening */
9295#define SQLITE_ColumnCache    0x02        /* Disable the column cache */
9296#define SQLITE_IndexSort      0x04        /* Disable indexes for sorting */
9297#define SQLITE_IndexSearch    0x08        /* Disable indexes for searching */
9298#define SQLITE_IndexCover     0x10        /* Disable index covering table */
9299#define SQLITE_GroupByOrder   0x20        /* Disable GROUPBY cover of ORDERBY */
9300#define SQLITE_FactorOutConst 0x40        /* Disable factoring out constants */
9301#define SQLITE_OptMask        0xff        /* Mask of all disablable opts */
9302
9303/*
9304** Possible values for the sqlite.magic field.
9305** The numbers are obtained at random and have no special meaning, other
9306** than being distinct from one another.
9307*/
9308#define SQLITE_MAGIC_OPEN     0xa029a697  /* Database is open */
9309#define SQLITE_MAGIC_CLOSED   0x9f3c2d33  /* Database is closed */
9310#define SQLITE_MAGIC_SICK     0x4b771290  /* Error and awaiting close */
9311#define SQLITE_MAGIC_BUSY     0xf03b7906  /* Database currently in use */
9312#define SQLITE_MAGIC_ERROR    0xb5357930  /* An SQLITE_MISUSE error occurred */
9313
9314/*
9315** Each SQL function is defined by an instance of the following
9316** structure.  A pointer to this structure is stored in the sqlite.aFunc
9317** hash table.  When multiple functions have the same name, the hash table
9318** points to a linked list of these structures.
9319*/
9320struct FuncDef {
9321  i16 nArg;            /* Number of arguments.  -1 means unlimited */
9322  u8 iPrefEnc;         /* Preferred text encoding (SQLITE_UTF8, 16LE, 16BE) */
9323  u8 flags;            /* Some combination of SQLITE_FUNC_* */
9324  void *pUserData;     /* User data parameter */
9325  FuncDef *pNext;      /* Next function with same name */
9326  void (*xFunc)(sqlite3_context*,int,sqlite3_value**); /* Regular function */
9327  void (*xStep)(sqlite3_context*,int,sqlite3_value**); /* Aggregate step */
9328  void (*xFinalize)(sqlite3_context*);                /* Aggregate finalizer */
9329  char *zName;         /* SQL name of the function. */
9330  FuncDef *pHash;      /* Next with a different name but the same hash */
9331  FuncDestructor *pDestructor;   /* Reference counted destructor function */
9332};
9333
9334/*
9335** This structure encapsulates a user-function destructor callback (as
9336** configured using create_function_v2()) and a reference counter. When
9337** create_function_v2() is called to create a function with a destructor,
9338** a single object of this type is allocated. FuncDestructor.nRef is set to
9339** the number of FuncDef objects created (either 1 or 3, depending on whether
9340** or not the specified encoding is SQLITE_ANY). The FuncDef.pDestructor
9341** member of each of the new FuncDef objects is set to point to the allocated
9342** FuncDestructor.
9343**
9344** Thereafter, when one of the FuncDef objects is deleted, the reference
9345** count on this object is decremented. When it reaches 0, the destructor
9346** is invoked and the FuncDestructor structure freed.
9347*/
9348struct FuncDestructor {
9349  int nRef;
9350  void (*xDestroy)(void *);
9351  void *pUserData;
9352};
9353
9354/*
9355** Possible values for FuncDef.flags
9356*/
9357#define SQLITE_FUNC_LIKE     0x01 /* Candidate for the LIKE optimization */
9358#define SQLITE_FUNC_CASE     0x02 /* Case-sensitive LIKE-type function */
9359#define SQLITE_FUNC_EPHEM    0x04 /* Ephemeral.  Delete with VDBE */
9360#define SQLITE_FUNC_NEEDCOLL 0x08 /* sqlite3GetFuncCollSeq() might be called */
9361#define SQLITE_FUNC_PRIVATE  0x10 /* Allowed for internal use only */
9362#define SQLITE_FUNC_COUNT    0x20 /* Built-in count(*) aggregate */
9363#define SQLITE_FUNC_COALESCE 0x40 /* Built-in coalesce() or ifnull() function */
9364
9365/*
9366** The following three macros, FUNCTION(), LIKEFUNC() and AGGREGATE() are
9367** used to create the initializers for the FuncDef structures.
9368**
9369**   FUNCTION(zName, nArg, iArg, bNC, xFunc)
9370**     Used to create a scalar function definition of a function zName
9371**     implemented by C function xFunc that accepts nArg arguments. The
9372**     value passed as iArg is cast to a (void*) and made available
9373**     as the user-data (sqlite3_user_data()) for the function. If
9374**     argument bNC is true, then the SQLITE_FUNC_NEEDCOLL flag is set.
9375**
9376**   AGGREGATE(zName, nArg, iArg, bNC, xStep, xFinal)
9377**     Used to create an aggregate function definition implemented by
9378**     the C functions xStep and xFinal. The first four parameters
9379**     are interpreted in the same way as the first 4 parameters to
9380**     FUNCTION().
9381**
9382**   LIKEFUNC(zName, nArg, pArg, flags)
9383**     Used to create a scalar function definition of a function zName
9384**     that accepts nArg arguments and is implemented by a call to C
9385**     function likeFunc. Argument pArg is cast to a (void *) and made
9386**     available as the function user-data (sqlite3_user_data()). The
9387**     FuncDef.flags variable is set to the value passed as the flags
9388**     parameter.
9389*/
9390#define FUNCTION(zName, nArg, iArg, bNC, xFunc) \
9391  {nArg, SQLITE_UTF8, bNC*SQLITE_FUNC_NEEDCOLL, \
9392   SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, 0, #zName, 0, 0}
9393#define STR_FUNCTION(zName, nArg, pArg, bNC, xFunc) \
9394  {nArg, SQLITE_UTF8, bNC*SQLITE_FUNC_NEEDCOLL, \
9395   pArg, 0, xFunc, 0, 0, #zName, 0, 0}
9396#define LIKEFUNC(zName, nArg, arg, flags) \
9397  {nArg, SQLITE_UTF8, flags, (void *)arg, 0, likeFunc, 0, 0, #zName, 0, 0}
9398#define AGGREGATE(zName, nArg, arg, nc, xStep, xFinal) \
9399  {nArg, SQLITE_UTF8, nc*SQLITE_FUNC_NEEDCOLL, \
9400   SQLITE_INT_TO_PTR(arg), 0, 0, xStep,xFinal,#zName,0,0}
9401
9402/*
9403** All current savepoints are stored in a linked list starting at
9404** sqlite3.pSavepoint. The first element in the list is the most recently
9405** opened savepoint. Savepoints are added to the list by the vdbe
9406** OP_Savepoint instruction.
9407*/
9408struct Savepoint {
9409  char *zName;                        /* Savepoint name (nul-terminated) */
9410  i64 nDeferredCons;                  /* Number of deferred fk violations */
9411  Savepoint *pNext;                   /* Parent savepoint (if any) */
9412};
9413
9414/*
9415** The following are used as the second parameter to sqlite3Savepoint(),
9416** and as the P1 argument to the OP_Savepoint instruction.
9417*/
9418#define SAVEPOINT_BEGIN      0
9419#define SAVEPOINT_RELEASE    1
9420#define SAVEPOINT_ROLLBACK   2
9421
9422
9423/*
9424** Each SQLite module (virtual table definition) is defined by an
9425** instance of the following structure, stored in the sqlite3.aModule
9426** hash table.
9427*/
9428struct Module {
9429  const sqlite3_module *pModule;       /* Callback pointers */
9430  const char *zName;                   /* Name passed to create_module() */
9431  void *pAux;                          /* pAux passed to create_module() */
9432  void (*xDestroy)(void *);            /* Module destructor function */
9433};
9434
9435/*
9436** information about each column of an SQL table is held in an instance
9437** of this structure.
9438*/
9439struct Column {
9440  char *zName;     /* Name of this column */
9441  Expr *pDflt;     /* Default value of this column */
9442  char *zDflt;     /* Original text of the default value */
9443  char *zType;     /* Data type for this column */
9444  char *zColl;     /* Collating sequence.  If NULL, use the default */
9445  u8 notNull;      /* True if there is a NOT NULL constraint */
9446  u8 isPrimKey;    /* True if this column is part of the PRIMARY KEY */
9447  char affinity;   /* One of the SQLITE_AFF_... values */
9448#ifndef SQLITE_OMIT_VIRTUALTABLE
9449  u8 isHidden;     /* True if this column is 'hidden' */
9450#endif
9451};
9452
9453/*
9454** A "Collating Sequence" is defined by an instance of the following
9455** structure. Conceptually, a collating sequence consists of a name and
9456** a comparison routine that defines the order of that sequence.
9457**
9458** There may two separate implementations of the collation function, one
9459** that processes text in UTF-8 encoding (CollSeq.xCmp) and another that
9460** processes text encoded in UTF-16 (CollSeq.xCmp16), using the machine
9461** native byte order. When a collation sequence is invoked, SQLite selects
9462** the version that will require the least expensive encoding
9463** translations, if any.
9464**
9465** The CollSeq.pUser member variable is an extra parameter that passed in
9466** as the first argument to the UTF-8 comparison function, xCmp.
9467** CollSeq.pUser16 is the equivalent for the UTF-16 comparison function,
9468** xCmp16.
9469**
9470** If both CollSeq.xCmp and CollSeq.xCmp16 are NULL, it means that the
9471** collating sequence is undefined.  Indices built on an undefined
9472** collating sequence may not be read or written.
9473*/
9474struct CollSeq {
9475  char *zName;          /* Name of the collating sequence, UTF-8 encoded */
9476  u8 enc;               /* Text encoding handled by xCmp() */
9477  u8 type;              /* One of the SQLITE_COLL_... values below */
9478  void *pUser;          /* First argument to xCmp() */
9479  int (*xCmp)(void*,int, const void*, int, const void*);
9480  void (*xDel)(void*);  /* Destructor for pUser */
9481};
9482
9483/*
9484** Allowed values of CollSeq.type:
9485*/
9486#define SQLITE_COLL_BINARY  1  /* The default memcmp() collating sequence */
9487#define SQLITE_COLL_NOCASE  2  /* The built-in NOCASE collating sequence */
9488#define SQLITE_COLL_REVERSE 3  /* The built-in REVERSE collating sequence */
9489#define SQLITE_COLL_USER    0  /* Any other user-defined collating sequence */
9490
9491/*
9492** A sort order can be either ASC or DESC.
9493*/
9494#define SQLITE_SO_ASC       0  /* Sort in ascending order */
9495#define SQLITE_SO_DESC      1  /* Sort in ascending order */
9496
9497/*
9498** Column affinity types.
9499**
9500** These used to have mnemonic name like 'i' for SQLITE_AFF_INTEGER and
9501** 't' for SQLITE_AFF_TEXT.  But we can save a little space and improve
9502** the speed a little by numbering the values consecutively.
9503**
9504** But rather than start with 0 or 1, we begin with 'a'.  That way,
9505** when multiple affinity types are concatenated into a string and
9506** used as the P4 operand, they will be more readable.
9507**
9508** Note also that the numeric types are grouped together so that testing
9509** for a numeric type is a single comparison.
9510*/
9511#define SQLITE_AFF_TEXT     'a'
9512#define SQLITE_AFF_NONE     'b'
9513#define SQLITE_AFF_NUMERIC  'c'
9514#define SQLITE_AFF_INTEGER  'd'
9515#define SQLITE_AFF_REAL     'e'
9516
9517#define sqlite3IsNumericAffinity(X)  ((X)>=SQLITE_AFF_NUMERIC)
9518
9519/*
9520** The SQLITE_AFF_MASK values masks off the significant bits of an
9521** affinity value.
9522*/
9523#define SQLITE_AFF_MASK     0x67
9524
9525/*
9526** Additional bit values that can be ORed with an affinity without
9527** changing the affinity.
9528*/
9529#define SQLITE_JUMPIFNULL   0x08  /* jumps if either operand is NULL */
9530#define SQLITE_STOREP2      0x10  /* Store result in reg[P2] rather than jump */
9531#define SQLITE_NULLEQ       0x80  /* NULL=NULL */
9532
9533/*
9534** An object of this type is created for each virtual table present in
9535** the database schema.
9536**
9537** If the database schema is shared, then there is one instance of this
9538** structure for each database connection (sqlite3*) that uses the shared
9539** schema. This is because each database connection requires its own unique
9540** instance of the sqlite3_vtab* handle used to access the virtual table
9541** implementation. sqlite3_vtab* handles can not be shared between
9542** database connections, even when the rest of the in-memory database
9543** schema is shared, as the implementation often stores the database
9544** connection handle passed to it via the xConnect() or xCreate() method
9545** during initialization internally. This database connection handle may
9546** then be used by the virtual table implementation to access real tables
9547** within the database. So that they appear as part of the callers
9548** transaction, these accesses need to be made via the same database
9549** connection as that used to execute SQL operations on the virtual table.
9550**
9551** All VTable objects that correspond to a single table in a shared
9552** database schema are initially stored in a linked-list pointed to by
9553** the Table.pVTable member variable of the corresponding Table object.
9554** When an sqlite3_prepare() operation is required to access the virtual
9555** table, it searches the list for the VTable that corresponds to the
9556** database connection doing the preparing so as to use the correct
9557** sqlite3_vtab* handle in the compiled query.
9558**
9559** When an in-memory Table object is deleted (for example when the
9560** schema is being reloaded for some reason), the VTable objects are not
9561** deleted and the sqlite3_vtab* handles are not xDisconnect()ed
9562** immediately. Instead, they are moved from the Table.pVTable list to
9563** another linked list headed by the sqlite3.pDisconnect member of the
9564** corresponding sqlite3 structure. They are then deleted/xDisconnected
9565** next time a statement is prepared using said sqlite3*. This is done
9566** to avoid deadlock issues involving multiple sqlite3.mutex mutexes.
9567** Refer to comments above function sqlite3VtabUnlockList() for an
9568** explanation as to why it is safe to add an entry to an sqlite3.pDisconnect
9569** list without holding the corresponding sqlite3.mutex mutex.
9570**
9571** The memory for objects of this type is always allocated by
9572** sqlite3DbMalloc(), using the connection handle stored in VTable.db as
9573** the first argument.
9574*/
9575struct VTable {
9576  sqlite3 *db;              /* Database connection associated with this table */
9577  Module *pMod;             /* Pointer to module implementation */
9578  sqlite3_vtab *pVtab;      /* Pointer to vtab instance */
9579  int nRef;                 /* Number of pointers to this structure */
9580  VTable *pNext;            /* Next in linked list (see above) */
9581};
9582
9583/*
9584** Each SQL table is represented in memory by an instance of the
9585** following structure.
9586**
9587** Table.zName is the name of the table.  The case of the original
9588** CREATE TABLE statement is stored, but case is not significant for
9589** comparisons.
9590**
9591** Table.nCol is the number of columns in this table.  Table.aCol is a
9592** pointer to an array of Column structures, one for each column.
9593**
9594** If the table has an INTEGER PRIMARY KEY, then Table.iPKey is the index of
9595** the column that is that key.   Otherwise Table.iPKey is negative.  Note
9596** that the datatype of the PRIMARY KEY must be INTEGER for this field to
9597** be set.  An INTEGER PRIMARY KEY is used as the rowid for each row of
9598** the table.  If a table has no INTEGER PRIMARY KEY, then a random rowid
9599** is generated for each row of the table.  TF_HasPrimaryKey is set if
9600** the table has any PRIMARY KEY, INTEGER or otherwise.
9601**
9602** Table.tnum is the page number for the root BTree page of the table in the
9603** database file.  If Table.iDb is the index of the database table backend
9604** in sqlite.aDb[].  0 is for the main database and 1 is for the file that
9605** holds temporary tables and indices.  If TF_Ephemeral is set
9606** then the table is stored in a file that is automatically deleted
9607** when the VDBE cursor to the table is closed.  In this case Table.tnum
9608** refers VDBE cursor number that holds the table open, not to the root
9609** page number.  Transient tables are used to hold the results of a
9610** sub-query that appears instead of a real table name in the FROM clause
9611** of a SELECT statement.
9612*/
9613struct Table {
9614  char *zName;         /* Name of the table or view */
9615  int iPKey;           /* If not negative, use aCol[iPKey] as the primary key */
9616  int nCol;            /* Number of columns in this table */
9617  Column *aCol;        /* Information about each column */
9618  Index *pIndex;       /* List of SQL indexes on this table. */
9619  int tnum;            /* Root BTree node for this table (see note above) */
9620  unsigned nRowEst;    /* Estimated rows in table - from sqlite_stat1 table */
9621  Select *pSelect;     /* NULL for tables.  Points to definition if a view. */
9622  u16 nRef;            /* Number of pointers to this Table */
9623  u8 tabFlags;         /* Mask of TF_* values */
9624  u8 keyConf;          /* What to do in case of uniqueness conflict on iPKey */
9625  FKey *pFKey;         /* Linked list of all foreign keys in this table */
9626  char *zColAff;       /* String defining the affinity of each column */
9627#ifndef SQLITE_OMIT_CHECK
9628  Expr *pCheck;        /* The AND of all CHECK constraints */
9629#endif
9630#ifndef SQLITE_OMIT_ALTERTABLE
9631  int addColOffset;    /* Offset in CREATE TABLE stmt to add a new column */
9632#endif
9633#ifndef SQLITE_OMIT_VIRTUALTABLE
9634  VTable *pVTable;     /* List of VTable objects. */
9635  int nModuleArg;      /* Number of arguments to the module */
9636  char **azModuleArg;  /* Text of all module args. [0] is module name */
9637#endif
9638  Trigger *pTrigger;   /* List of triggers stored in pSchema */
9639  Schema *pSchema;     /* Schema that contains this table */
9640  Table *pNextZombie;  /* Next on the Parse.pZombieTab list */
9641};
9642
9643/*
9644** Allowed values for Tabe.tabFlags.
9645*/
9646#define TF_Readonly        0x01    /* Read-only system table */
9647#define TF_Ephemeral       0x02    /* An ephemeral table */
9648#define TF_HasPrimaryKey   0x04    /* Table has a primary key */
9649#define TF_Autoincrement   0x08    /* Integer primary key is autoincrement */
9650#define TF_Virtual         0x10    /* Is a virtual table */
9651#define TF_NeedMetadata    0x20    /* aCol[].zType and aCol[].pColl missing */
9652
9653
9654
9655/*
9656** Test to see whether or not a table is a virtual table.  This is
9657** done as a macro so that it will be optimized out when virtual
9658** table support is omitted from the build.
9659*/
9660#ifndef SQLITE_OMIT_VIRTUALTABLE
9661#  define IsVirtual(X)      (((X)->tabFlags & TF_Virtual)!=0)
9662#  define IsHiddenColumn(X) ((X)->isHidden)
9663#else
9664#  define IsVirtual(X)      0
9665#  define IsHiddenColumn(X) 0
9666#endif
9667
9668/*
9669** Each foreign key constraint is an instance of the following structure.
9670**
9671** A foreign key is associated with two tables.  The "from" table is
9672** the table that contains the REFERENCES clause that creates the foreign
9673** key.  The "to" table is the table that is named in the REFERENCES clause.
9674** Consider this example:
9675**
9676**     CREATE TABLE ex1(
9677**       a INTEGER PRIMARY KEY,
9678**       b INTEGER CONSTRAINT fk1 REFERENCES ex2(x)
9679**     );
9680**
9681** For foreign key "fk1", the from-table is "ex1" and the to-table is "ex2".
9682**
9683** Each REFERENCES clause generates an instance of the following structure
9684** which is attached to the from-table.  The to-table need not exist when
9685** the from-table is created.  The existence of the to-table is not checked.
9686*/
9687struct FKey {
9688  Table *pFrom;     /* Table containing the REFERENCES clause (aka: Child) */
9689  FKey *pNextFrom;  /* Next foreign key in pFrom */
9690  char *zTo;        /* Name of table that the key points to (aka: Parent) */
9691  FKey *pNextTo;    /* Next foreign key on table named zTo */
9692  FKey *pPrevTo;    /* Previous foreign key on table named zTo */
9693  int nCol;         /* Number of columns in this key */
9694  /* EV: R-30323-21917 */
9695  u8 isDeferred;    /* True if constraint checking is deferred till COMMIT */
9696  u8 aAction[2];          /* ON DELETE and ON UPDATE actions, respectively */
9697  Trigger *apTrigger[2];  /* Triggers for aAction[] actions */
9698  struct sColMap {  /* Mapping of columns in pFrom to columns in zTo */
9699    int iFrom;         /* Index of column in pFrom */
9700    char *zCol;        /* Name of column in zTo.  If 0 use PRIMARY KEY */
9701  } aCol[1];        /* One entry for each of nCol column s */
9702};
9703
9704/*
9705** SQLite supports many different ways to resolve a constraint
9706** error.  ROLLBACK processing means that a constraint violation
9707** causes the operation in process to fail and for the current transaction
9708** to be rolled back.  ABORT processing means the operation in process
9709** fails and any prior changes from that one operation are backed out,
9710** but the transaction is not rolled back.  FAIL processing means that
9711** the operation in progress stops and returns an error code.  But prior
9712** changes due to the same operation are not backed out and no rollback
9713** occurs.  IGNORE means that the particular row that caused the constraint
9714** error is not inserted or updated.  Processing continues and no error
9715** is returned.  REPLACE means that preexisting database rows that caused
9716** a UNIQUE constraint violation are removed so that the new insert or
9717** update can proceed.  Processing continues and no error is reported.
9718**
9719** RESTRICT, SETNULL, and CASCADE actions apply only to foreign keys.
9720** RESTRICT is the same as ABORT for IMMEDIATE foreign keys and the
9721** same as ROLLBACK for DEFERRED keys.  SETNULL means that the foreign
9722** key is set to NULL.  CASCADE means that a DELETE or UPDATE of the
9723** referenced table row is propagated into the row that holds the
9724** foreign key.
9725**
9726** The following symbolic values are used to record which type
9727** of action to take.
9728*/
9729#define OE_None     0   /* There is no constraint to check */
9730#define OE_Rollback 1   /* Fail the operation and rollback the transaction */
9731#define OE_Abort    2   /* Back out changes but do no rollback transaction */
9732#define OE_Fail     3   /* Stop the operation but leave all prior changes */
9733#define OE_Ignore   4   /* Ignore the error. Do not do the INSERT or UPDATE */
9734#define OE_Replace  5   /* Delete existing record, then do INSERT or UPDATE */
9735
9736#define OE_Restrict 6   /* OE_Abort for IMMEDIATE, OE_Rollback for DEFERRED */
9737#define OE_SetNull  7   /* Set the foreign key value to NULL */
9738#define OE_SetDflt  8   /* Set the foreign key value to its default */
9739#define OE_Cascade  9   /* Cascade the changes */
9740
9741#define OE_Default  99  /* Do whatever the default action is */
9742
9743
9744/*
9745** An instance of the following structure is passed as the first
9746** argument to sqlite3VdbeKeyCompare and is used to control the
9747** comparison of the two index keys.
9748*/
9749struct KeyInfo {
9750  sqlite3 *db;        /* The database connection */
9751  u8 enc;             /* Text encoding - one of the SQLITE_UTF* values */
9752  u16 nField;         /* Number of entries in aColl[] */
9753  u8 *aSortOrder;     /* Sort order for each column.  May be NULL */
9754  CollSeq *aColl[1];  /* Collating sequence for each term of the key */
9755};
9756
9757/*
9758** An instance of the following structure holds information about a
9759** single index record that has already been parsed out into individual
9760** values.
9761**
9762** A record is an object that contains one or more fields of data.
9763** Records are used to store the content of a table row and to store
9764** the key of an index.  A blob encoding of a record is created by
9765** the OP_MakeRecord opcode of the VDBE and is disassembled by the
9766** OP_Column opcode.
9767**
9768** This structure holds a record that has already been disassembled
9769** into its constituent fields.
9770*/
9771struct UnpackedRecord {
9772  KeyInfo *pKeyInfo;  /* Collation and sort-order information */
9773  u16 nField;         /* Number of entries in apMem[] */
9774  u16 flags;          /* Boolean settings.  UNPACKED_... below */
9775  i64 rowid;          /* Used by UNPACKED_PREFIX_SEARCH */
9776  Mem *aMem;          /* Values */
9777};
9778
9779/*
9780** Allowed values of UnpackedRecord.flags
9781*/
9782#define UNPACKED_NEED_FREE     0x0001  /* Memory is from sqlite3Malloc() */
9783#define UNPACKED_NEED_DESTROY  0x0002  /* apMem[]s should all be destroyed */
9784#define UNPACKED_IGNORE_ROWID  0x0004  /* Ignore trailing rowid on key1 */
9785#define UNPACKED_INCRKEY       0x0008  /* Make this key an epsilon larger */
9786#define UNPACKED_PREFIX_MATCH  0x0010  /* A prefix match is considered OK */
9787#define UNPACKED_PREFIX_SEARCH 0x0020  /* A prefix match is considered OK */
9788
9789/*
9790** Each SQL index is represented in memory by an
9791** instance of the following structure.
9792**
9793** The columns of the table that are to be indexed are described
9794** by the aiColumn[] field of this structure.  For example, suppose
9795** we have the following table and index:
9796**
9797**     CREATE TABLE Ex1(c1 int, c2 int, c3 text);
9798**     CREATE INDEX Ex2 ON Ex1(c3,c1);
9799**
9800** In the Table structure describing Ex1, nCol==3 because there are
9801** three columns in the table.  In the Index structure describing
9802** Ex2, nColumn==2 since 2 of the 3 columns of Ex1 are indexed.
9803** The value of aiColumn is {2, 0}.  aiColumn[0]==2 because the
9804** first column to be indexed (c3) has an index of 2 in Ex1.aCol[].
9805** The second column to be indexed (c1) has an index of 0 in
9806** Ex1.aCol[], hence Ex2.aiColumn[1]==0.
9807**
9808** The Index.onError field determines whether or not the indexed columns
9809** must be unique and what to do if they are not.  When Index.onError=OE_None,
9810** it means this is not a unique index.  Otherwise it is a unique index
9811** and the value of Index.onError indicate the which conflict resolution
9812** algorithm to employ whenever an attempt is made to insert a non-unique
9813** element.
9814*/
9815struct Index {
9816  char *zName;     /* Name of this index */
9817  int nColumn;     /* Number of columns in the table used by this index */
9818  int *aiColumn;   /* Which columns are used by this index.  1st is 0 */
9819  unsigned *aiRowEst; /* Result of ANALYZE: Est. rows selected by each column */
9820  Table *pTable;   /* The SQL table being indexed */
9821  int tnum;        /* Page containing root of this index in database file */
9822  u8 onError;      /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
9823  u8 autoIndex;    /* True if is automatically created (ex: by UNIQUE) */
9824  u8 bUnordered;   /* Use this index for == or IN queries only */
9825  char *zColAff;   /* String defining the affinity of each column */
9826  Index *pNext;    /* The next index associated with the same table */
9827  Schema *pSchema; /* Schema containing this index */
9828  u8 *aSortOrder;  /* Array of size Index.nColumn. True==DESC, False==ASC */
9829  char **azColl;   /* Array of collation sequence names for index */
9830  IndexSample *aSample;    /* Array of SQLITE_INDEX_SAMPLES samples */
9831};
9832
9833/*
9834** Each sample stored in the sqlite_stat2 table is represented in memory
9835** using a structure of this type.
9836*/
9837struct IndexSample {
9838  union {
9839    char *z;        /* Value if eType is SQLITE_TEXT or SQLITE_BLOB */
9840    double r;       /* Value if eType is SQLITE_FLOAT or SQLITE_INTEGER */
9841  } u;
9842  u8 eType;         /* SQLITE_NULL, SQLITE_INTEGER ... etc. */
9843  u8 nByte;         /* Size in byte of text or blob. */
9844};
9845
9846/*
9847** Each token coming out of the lexer is an instance of
9848** this structure.  Tokens are also used as part of an expression.
9849**
9850** Note if Token.z==0 then Token.dyn and Token.n are undefined and
9851** may contain random values.  Do not make any assumptions about Token.dyn
9852** and Token.n when Token.z==0.
9853*/
9854struct Token {
9855  const char *z;     /* Text of the token.  Not NULL-terminated! */
9856  unsigned int n;    /* Number of characters in this token */
9857};
9858
9859/*
9860** An instance of this structure contains information needed to generate
9861** code for a SELECT that contains aggregate functions.
9862**
9863** If Expr.op==TK_AGG_COLUMN or TK_AGG_FUNCTION then Expr.pAggInfo is a
9864** pointer to this structure.  The Expr.iColumn field is the index in
9865** AggInfo.aCol[] or AggInfo.aFunc[] of information needed to generate
9866** code for that node.
9867**
9868** AggInfo.pGroupBy and AggInfo.aFunc.pExpr point to fields within the
9869** original Select structure that describes the SELECT statement.  These
9870** fields do not need to be freed when deallocating the AggInfo structure.
9871*/
9872struct AggInfo {
9873  u8 directMode;          /* Direct rendering mode means take data directly
9874                          ** from source tables rather than from accumulators */
9875  u8 useSortingIdx;       /* In direct mode, reference the sorting index rather
9876                          ** than the source table */
9877  int sortingIdx;         /* Cursor number of the sorting index */
9878  ExprList *pGroupBy;     /* The group by clause */
9879  int nSortingColumn;     /* Number of columns in the sorting index */
9880  struct AggInfo_col {    /* For each column used in source tables */
9881    Table *pTab;             /* Source table */
9882    int iTable;              /* Cursor number of the source table */
9883    int iColumn;             /* Column number within the source table */
9884    int iSorterColumn;       /* Column number in the sorting index */
9885    int iMem;                /* Memory location that acts as accumulator */
9886    Expr *pExpr;             /* The original expression */
9887  } *aCol;
9888  int nColumn;            /* Number of used entries in aCol[] */
9889  int nColumnAlloc;       /* Number of slots allocated for aCol[] */
9890  int nAccumulator;       /* Number of columns that show through to the output.
9891                          ** Additional columns are used only as parameters to
9892                          ** aggregate functions */
9893  struct AggInfo_func {   /* For each aggregate function */
9894    Expr *pExpr;             /* Expression encoding the function */
9895    FuncDef *pFunc;          /* The aggregate function implementation */
9896    int iMem;                /* Memory location that acts as accumulator */
9897    int iDistinct;           /* Ephemeral table used to enforce DISTINCT */
9898  } *aFunc;
9899  int nFunc;              /* Number of entries in aFunc[] */
9900  int nFuncAlloc;         /* Number of slots allocated for aFunc[] */
9901};
9902
9903/*
9904** The datatype ynVar is a signed integer, either 16-bit or 32-bit.
9905** Usually it is 16-bits.  But if SQLITE_MAX_VARIABLE_NUMBER is greater
9906** than 32767 we have to make it 32-bit.  16-bit is preferred because
9907** it uses less memory in the Expr object, which is a big memory user
9908** in systems with lots of prepared statements.  And few applications
9909** need more than about 10 or 20 variables.  But some extreme users want
9910** to have prepared statements with over 32767 variables, and for them
9911** the option is available (at compile-time).
9912*/
9913#if SQLITE_MAX_VARIABLE_NUMBER<=32767
9914typedef i16 ynVar;
9915#else
9916typedef int ynVar;
9917#endif
9918
9919/*
9920** Each node of an expression in the parse tree is an instance
9921** of this structure.
9922**
9923** Expr.op is the opcode. The integer parser token codes are reused
9924** as opcodes here. For example, the parser defines TK_GE to be an integer
9925** code representing the ">=" operator. This same integer code is reused
9926** to represent the greater-than-or-equal-to operator in the expression
9927** tree.
9928**
9929** If the expression is an SQL literal (TK_INTEGER, TK_FLOAT, TK_BLOB,
9930** or TK_STRING), then Expr.token contains the text of the SQL literal. If
9931** the expression is a variable (TK_VARIABLE), then Expr.token contains the
9932** variable name. Finally, if the expression is an SQL function (TK_FUNCTION),
9933** then Expr.token contains the name of the function.
9934**
9935** Expr.pRight and Expr.pLeft are the left and right subexpressions of a
9936** binary operator. Either or both may be NULL.
9937**
9938** Expr.x.pList is a list of arguments if the expression is an SQL function,
9939** a CASE expression or an IN expression of the form "<lhs> IN (<y>, <z>...)".
9940** Expr.x.pSelect is used if the expression is a sub-select or an expression of
9941** the form "<lhs> IN (SELECT ...)". If the EP_xIsSelect bit is set in the
9942** Expr.flags mask, then Expr.x.pSelect is valid. Otherwise, Expr.x.pList is
9943** valid.
9944**
9945** An expression of the form ID or ID.ID refers to a column in a table.
9946** For such expressions, Expr.op is set to TK_COLUMN and Expr.iTable is
9947** the integer cursor number of a VDBE cursor pointing to that table and
9948** Expr.iColumn is the column number for the specific column.  If the
9949** expression is used as a result in an aggregate SELECT, then the
9950** value is also stored in the Expr.iAgg column in the aggregate so that
9951** it can be accessed after all aggregates are computed.
9952**
9953** If the expression is an unbound variable marker (a question mark
9954** character '?' in the original SQL) then the Expr.iTable holds the index
9955** number for that variable.
9956**
9957** If the expression is a subquery then Expr.iColumn holds an integer
9958** register number containing the result of the subquery.  If the
9959** subquery gives a constant result, then iTable is -1.  If the subquery
9960** gives a different answer at different times during statement processing
9961** then iTable is the address of a subroutine that computes the subquery.
9962**
9963** If the Expr is of type OP_Column, and the table it is selecting from
9964** is a disk table or the "old.*" pseudo-table, then pTab points to the
9965** corresponding table definition.
9966**
9967** ALLOCATION NOTES:
9968**
9969** Expr objects can use a lot of memory space in database schema.  To
9970** help reduce memory requirements, sometimes an Expr object will be
9971** truncated.  And to reduce the number of memory allocations, sometimes
9972** two or more Expr objects will be stored in a single memory allocation,
9973** together with Expr.zToken strings.
9974**
9975** If the EP_Reduced and EP_TokenOnly flags are set when
9976** an Expr object is truncated.  When EP_Reduced is set, then all
9977** the child Expr objects in the Expr.pLeft and Expr.pRight subtrees
9978** are contained within the same memory allocation.  Note, however, that
9979** the subtrees in Expr.x.pList or Expr.x.pSelect are always separately
9980** allocated, regardless of whether or not EP_Reduced is set.
9981*/
9982struct Expr {
9983  u8 op;                 /* Operation performed by this node */
9984  char affinity;         /* The affinity of the column or 0 if not a column */
9985  u16 flags;             /* Various flags.  EP_* See below */
9986  union {
9987    char *zToken;          /* Token value. Zero terminated and dequoted */
9988    int iValue;            /* Non-negative integer value if EP_IntValue */
9989  } u;
9990
9991  /* If the EP_TokenOnly flag is set in the Expr.flags mask, then no
9992  ** space is allocated for the fields below this point. An attempt to
9993  ** access them will result in a segfault or malfunction.
9994  *********************************************************************/
9995
9996  Expr *pLeft;           /* Left subnode */
9997  Expr *pRight;          /* Right subnode */
9998  union {
9999    ExprList *pList;     /* Function arguments or in "<expr> IN (<expr-list)" */
10000    Select *pSelect;     /* Used for sub-selects and "<expr> IN (<select>)" */
10001  } x;
10002  CollSeq *pColl;        /* The collation type of the column or 0 */
10003
10004  /* If the EP_Reduced flag is set in the Expr.flags mask, then no
10005  ** space is allocated for the fields below this point. An attempt to
10006  ** access them will result in a segfault or malfunction.
10007  *********************************************************************/
10008
10009  int iTable;            /* TK_COLUMN: cursor number of table holding column
10010                         ** TK_REGISTER: register number
10011                         ** TK_TRIGGER: 1 -> new, 0 -> old */
10012  ynVar iColumn;         /* TK_COLUMN: column index.  -1 for rowid.
10013                         ** TK_VARIABLE: variable number (always >= 1). */
10014  i16 iAgg;              /* Which entry in pAggInfo->aCol[] or ->aFunc[] */
10015  i16 iRightJoinTable;   /* If EP_FromJoin, the right table of the join */
10016  u8 flags2;             /* Second set of flags.  EP2_... */
10017  u8 op2;                /* If a TK_REGISTER, the original value of Expr.op */
10018  AggInfo *pAggInfo;     /* Used by TK_AGG_COLUMN and TK_AGG_FUNCTION */
10019  Table *pTab;           /* Table for TK_COLUMN expressions. */
10020#if SQLITE_MAX_EXPR_DEPTH>0
10021  int nHeight;           /* Height of the tree headed by this node */
10022#endif
10023};
10024
10025/*
10026** The following are the meanings of bits in the Expr.flags field.
10027*/
10028#define EP_FromJoin   0x0001  /* Originated in ON or USING clause of a join */
10029#define EP_Agg        0x0002  /* Contains one or more aggregate functions */
10030#define EP_Resolved   0x0004  /* IDs have been resolved to COLUMNs */
10031#define EP_Error      0x0008  /* Expression contains one or more errors */
10032#define EP_Distinct   0x0010  /* Aggregate function with DISTINCT keyword */
10033#define EP_VarSelect  0x0020  /* pSelect is correlated, not constant */
10034#define EP_DblQuoted  0x0040  /* token.z was originally in "..." */
10035#define EP_InfixFunc  0x0080  /* True for an infix function: LIKE, GLOB, etc */
10036#define EP_ExpCollate 0x0100  /* Collating sequence specified explicitly */
10037#define EP_FixedDest  0x0200  /* Result needed in a specific register */
10038#define EP_IntValue   0x0400  /* Integer value contained in u.iValue */
10039#define EP_xIsSelect  0x0800  /* x.pSelect is valid (otherwise x.pList is) */
10040
10041#define EP_Reduced    0x1000  /* Expr struct is EXPR_REDUCEDSIZE bytes only */
10042#define EP_TokenOnly  0x2000  /* Expr struct is EXPR_TOKENONLYSIZE bytes only */
10043#define EP_Static     0x4000  /* Held in memory not obtained from malloc() */
10044
10045/*
10046** The following are the meanings of bits in the Expr.flags2 field.
10047*/
10048#define EP2_MallocedToken  0x0001  /* Need to sqlite3DbFree() Expr.zToken */
10049#define EP2_Irreducible    0x0002  /* Cannot EXPRDUP_REDUCE this Expr */
10050
10051/*
10052** The pseudo-routine sqlite3ExprSetIrreducible sets the EP2_Irreducible
10053** flag on an expression structure.  This flag is used for VV&A only.  The
10054** routine is implemented as a macro that only works when in debugging mode,
10055** so as not to burden production code.
10056*/
10057#ifdef SQLITE_DEBUG
10058# define ExprSetIrreducible(X)  (X)->flags2 |= EP2_Irreducible
10059#else
10060# define ExprSetIrreducible(X)
10061#endif
10062
10063/*
10064** These macros can be used to test, set, or clear bits in the
10065** Expr.flags field.
10066*/
10067#define ExprHasProperty(E,P)     (((E)->flags&(P))==(P))
10068#define ExprHasAnyProperty(E,P)  (((E)->flags&(P))!=0)
10069#define ExprSetProperty(E,P)     (E)->flags|=(P)
10070#define ExprClearProperty(E,P)   (E)->flags&=~(P)
10071
10072/*
10073** Macros to determine the number of bytes required by a normal Expr
10074** struct, an Expr struct with the EP_Reduced flag set in Expr.flags
10075** and an Expr struct with the EP_TokenOnly flag set.
10076*/
10077#define EXPR_FULLSIZE           sizeof(Expr)           /* Full size */
10078#define EXPR_REDUCEDSIZE        offsetof(Expr,iTable)  /* Common features */
10079#define EXPR_TOKENONLYSIZE      offsetof(Expr,pLeft)   /* Fewer features */
10080
10081/*
10082** Flags passed to the sqlite3ExprDup() function. See the header comment
10083** above sqlite3ExprDup() for details.
10084*/
10085#define EXPRDUP_REDUCE         0x0001  /* Used reduced-size Expr nodes */
10086
10087/*
10088** A list of expressions.  Each expression may optionally have a
10089** name.  An expr/name combination can be used in several ways, such
10090** as the list of "expr AS ID" fields following a "SELECT" or in the
10091** list of "ID = expr" items in an UPDATE.  A list of expressions can
10092** also be used as the argument to a function, in which case the a.zName
10093** field is not used.
10094*/
10095struct ExprList {
10096  int nExpr;             /* Number of expressions on the list */
10097  int nAlloc;            /* Number of entries allocated below */
10098  int iECursor;          /* VDBE Cursor associated with this ExprList */
10099  struct ExprList_item {
10100    Expr *pExpr;           /* The list of expressions */
10101    char *zName;           /* Token associated with this expression */
10102    char *zSpan;           /* Original text of the expression */
10103    u8 sortOrder;          /* 1 for DESC or 0 for ASC */
10104    u8 done;               /* A flag to indicate when processing is finished */
10105    u16 iCol;              /* For ORDER BY, column number in result set */
10106    u16 iAlias;            /* Index into Parse.aAlias[] for zName */
10107  } *a;                  /* One entry for each expression */
10108};
10109
10110/*
10111** An instance of this structure is used by the parser to record both
10112** the parse tree for an expression and the span of input text for an
10113** expression.
10114*/
10115struct ExprSpan {
10116  Expr *pExpr;          /* The expression parse tree */
10117  const char *zStart;   /* First character of input text */
10118  const char *zEnd;     /* One character past the end of input text */
10119};
10120
10121/*
10122** An instance of this structure can hold a simple list of identifiers,
10123** such as the list "a,b,c" in the following statements:
10124**
10125**      INSERT INTO t(a,b,c) VALUES ...;
10126**      CREATE INDEX idx ON t(a,b,c);
10127**      CREATE TRIGGER trig BEFORE UPDATE ON t(a,b,c) ...;
10128**
10129** The IdList.a.idx field is used when the IdList represents the list of
10130** column names after a table name in an INSERT statement.  In the statement
10131**
10132**     INSERT INTO t(a,b,c) ...
10133**
10134** If "a" is the k-th column of table "t", then IdList.a[0].idx==k.
10135*/
10136struct IdList {
10137  struct IdList_item {
10138    char *zName;      /* Name of the identifier */
10139    int idx;          /* Index in some Table.aCol[] of a column named zName */
10140  } *a;
10141  int nId;         /* Number of identifiers on the list */
10142  int nAlloc;      /* Number of entries allocated for a[] below */
10143};
10144
10145/*
10146** The bitmask datatype defined below is used for various optimizations.
10147**
10148** Changing this from a 64-bit to a 32-bit type limits the number of
10149** tables in a join to 32 instead of 64.  But it also reduces the size
10150** of the library by 738 bytes on ix86.
10151*/
10152typedef u64 Bitmask;
10153
10154/*
10155** The number of bits in a Bitmask.  "BMS" means "BitMask Size".
10156*/
10157#define BMS  ((int)(sizeof(Bitmask)*8))
10158
10159/*
10160** The following structure describes the FROM clause of a SELECT statement.
10161** Each table or subquery in the FROM clause is a separate element of
10162** the SrcList.a[] array.
10163**
10164** With the addition of multiple database support, the following structure
10165** can also be used to describe a particular table such as the table that
10166** is modified by an INSERT, DELETE, or UPDATE statement.  In standard SQL,
10167** such a table must be a simple name: ID.  But in SQLite, the table can
10168** now be identified by a database name, a dot, then the table name: ID.ID.
10169**
10170** The jointype starts out showing the join type between the current table
10171** and the next table on the list.  The parser builds the list this way.
10172** But sqlite3SrcListShiftJoinType() later shifts the jointypes so that each
10173** jointype expresses the join between the table and the previous table.
10174**
10175** In the colUsed field, the high-order bit (bit 63) is set if the table
10176** contains more than 63 columns and the 64-th or later column is used.
10177*/
10178struct SrcList {
10179  i16 nSrc;        /* Number of tables or subqueries in the FROM clause */
10180  i16 nAlloc;      /* Number of entries allocated in a[] below */
10181  struct SrcList_item {
10182    char *zDatabase;  /* Name of database holding this table */
10183    char *zName;      /* Name of the table */
10184    char *zAlias;     /* The "B" part of a "A AS B" phrase.  zName is the "A" */
10185    Table *pTab;      /* An SQL table corresponding to zName */
10186    Select *pSelect;  /* A SELECT statement used in place of a table name */
10187    u8 isPopulated;   /* Temporary table associated with SELECT is populated */
10188    u8 jointype;      /* Type of join between this able and the previous */
10189    u8 notIndexed;    /* True if there is a NOT INDEXED clause */
10190#ifndef SQLITE_OMIT_EXPLAIN
10191    u8 iSelectId;     /* If pSelect!=0, the id of the sub-select in EQP */
10192#endif
10193    int iCursor;      /* The VDBE cursor number used to access this table */
10194    Expr *pOn;        /* The ON clause of a join */
10195    IdList *pUsing;   /* The USING clause of a join */
10196    Bitmask colUsed;  /* Bit N (1<<N) set if column N of pTab is used */
10197    char *zIndex;     /* Identifier from "INDEXED BY <zIndex>" clause */
10198    Index *pIndex;    /* Index structure corresponding to zIndex, if any */
10199  } a[1];             /* One entry for each identifier on the list */
10200};
10201
10202/*
10203** Permitted values of the SrcList.a.jointype field
10204*/
10205#define JT_INNER     0x0001    /* Any kind of inner or cross join */
10206#define JT_CROSS     0x0002    /* Explicit use of the CROSS keyword */
10207#define JT_NATURAL   0x0004    /* True for a "natural" join */
10208#define JT_LEFT      0x0008    /* Left outer join */
10209#define JT_RIGHT     0x0010    /* Right outer join */
10210#define JT_OUTER     0x0020    /* The "OUTER" keyword is present */
10211#define JT_ERROR     0x0040    /* unknown or unsupported join type */
10212
10213
10214/*
10215** A WherePlan object holds information that describes a lookup
10216** strategy.
10217**
10218** This object is intended to be opaque outside of the where.c module.
10219** It is included here only so that that compiler will know how big it
10220** is.  None of the fields in this object should be used outside of
10221** the where.c module.
10222**
10223** Within the union, pIdx is only used when wsFlags&WHERE_INDEXED is true.
10224** pTerm is only used when wsFlags&WHERE_MULTI_OR is true.  And pVtabIdx
10225** is only used when wsFlags&WHERE_VIRTUALTABLE is true.  It is never the
10226** case that more than one of these conditions is true.
10227*/
10228struct WherePlan {
10229  u32 wsFlags;                   /* WHERE_* flags that describe the strategy */
10230  u32 nEq;                       /* Number of == constraints */
10231  double nRow;                   /* Estimated number of rows (for EQP) */
10232  union {
10233    Index *pIdx;                   /* Index when WHERE_INDEXED is true */
10234    struct WhereTerm *pTerm;       /* WHERE clause term for OR-search */
10235    sqlite3_index_info *pVtabIdx;  /* Virtual table index to use */
10236  } u;
10237};
10238
10239/*
10240** For each nested loop in a WHERE clause implementation, the WhereInfo
10241** structure contains a single instance of this structure.  This structure
10242** is intended to be private the the where.c module and should not be
10243** access or modified by other modules.
10244**
10245** The pIdxInfo field is used to help pick the best index on a
10246** virtual table.  The pIdxInfo pointer contains indexing
10247** information for the i-th table in the FROM clause before reordering.
10248** All the pIdxInfo pointers are freed by whereInfoFree() in where.c.
10249** All other information in the i-th WhereLevel object for the i-th table
10250** after FROM clause ordering.
10251*/
10252struct WhereLevel {
10253  WherePlan plan;       /* query plan for this element of the FROM clause */
10254  int iLeftJoin;        /* Memory cell used to implement LEFT OUTER JOIN */
10255  int iTabCur;          /* The VDBE cursor used to access the table */
10256  int iIdxCur;          /* The VDBE cursor used to access pIdx */
10257  int addrBrk;          /* Jump here to break out of the loop */
10258  int addrNxt;          /* Jump here to start the next IN combination */
10259  int addrCont;         /* Jump here to continue with the next loop cycle */
10260  int addrFirst;        /* First instruction of interior of the loop */
10261  u8 iFrom;             /* Which entry in the FROM clause */
10262  u8 op, p5;            /* Opcode and P5 of the opcode that ends the loop */
10263  int p1, p2;           /* Operands of the opcode used to ends the loop */
10264  union {               /* Information that depends on plan.wsFlags */
10265    struct {
10266      int nIn;              /* Number of entries in aInLoop[] */
10267      struct InLoop {
10268        int iCur;              /* The VDBE cursor used by this IN operator */
10269        int addrInTop;         /* Top of the IN loop */
10270      } *aInLoop;           /* Information about each nested IN operator */
10271    } in;                 /* Used when plan.wsFlags&WHERE_IN_ABLE */
10272  } u;
10273
10274  /* The following field is really not part of the current level.  But
10275  ** we need a place to cache virtual table index information for each
10276  ** virtual table in the FROM clause and the WhereLevel structure is
10277  ** a convenient place since there is one WhereLevel for each FROM clause
10278  ** element.
10279  */
10280  sqlite3_index_info *pIdxInfo;  /* Index info for n-th source table */
10281};
10282
10283/*
10284** Flags appropriate for the wctrlFlags parameter of sqlite3WhereBegin()
10285** and the WhereInfo.wctrlFlags member.
10286*/
10287#define WHERE_ORDERBY_NORMAL   0x0000 /* No-op */
10288#define WHERE_ORDERBY_MIN      0x0001 /* ORDER BY processing for min() func */
10289#define WHERE_ORDERBY_MAX      0x0002 /* ORDER BY processing for max() func */
10290#define WHERE_ONEPASS_DESIRED  0x0004 /* Want to do one-pass UPDATE/DELETE */
10291#define WHERE_DUPLICATES_OK    0x0008 /* Ok to return a row more than once */
10292#define WHERE_OMIT_OPEN        0x0010 /* Table cursors are already open */
10293#define WHERE_OMIT_CLOSE       0x0020 /* Omit close of table & index cursors */
10294#define WHERE_FORCE_TABLE      0x0040 /* Do not use an index-only search */
10295#define WHERE_ONETABLE_ONLY    0x0080 /* Only code the 1st table in pTabList */
10296
10297/*
10298** The WHERE clause processing routine has two halves.  The
10299** first part does the start of the WHERE loop and the second
10300** half does the tail of the WHERE loop.  An instance of
10301** this structure is returned by the first half and passed
10302** into the second half to give some continuity.
10303*/
10304struct WhereInfo {
10305  Parse *pParse;       /* Parsing and code generating context */
10306  u16 wctrlFlags;      /* Flags originally passed to sqlite3WhereBegin() */
10307  u8 okOnePass;        /* Ok to use one-pass algorithm for UPDATE or DELETE */
10308  u8 untestedTerms;    /* Not all WHERE terms resolved by outer loop */
10309  SrcList *pTabList;             /* List of tables in the join */
10310  int iTop;                      /* The very beginning of the WHERE loop */
10311  int iContinue;                 /* Jump here to continue with next record */
10312  int iBreak;                    /* Jump here to break out of the loop */
10313  int nLevel;                    /* Number of nested loop */
10314  struct WhereClause *pWC;       /* Decomposition of the WHERE clause */
10315  double savedNQueryLoop;        /* pParse->nQueryLoop outside the WHERE loop */
10316  double nRowOut;                /* Estimated number of output rows */
10317  WhereLevel a[1];               /* Information about each nest loop in WHERE */
10318};
10319
10320/*
10321** A NameContext defines a context in which to resolve table and column
10322** names.  The context consists of a list of tables (the pSrcList) field and
10323** a list of named expression (pEList).  The named expression list may
10324** be NULL.  The pSrc corresponds to the FROM clause of a SELECT or
10325** to the table being operated on by INSERT, UPDATE, or DELETE.  The
10326** pEList corresponds to the result set of a SELECT and is NULL for
10327** other statements.
10328**
10329** NameContexts can be nested.  When resolving names, the inner-most
10330** context is searched first.  If no match is found, the next outer
10331** context is checked.  If there is still no match, the next context
10332** is checked.  This process continues until either a match is found
10333** or all contexts are check.  When a match is found, the nRef member of
10334** the context containing the match is incremented.
10335**
10336** Each subquery gets a new NameContext.  The pNext field points to the
10337** NameContext in the parent query.  Thus the process of scanning the
10338** NameContext list corresponds to searching through successively outer
10339** subqueries looking for a match.
10340*/
10341struct NameContext {
10342  Parse *pParse;       /* The parser */
10343  SrcList *pSrcList;   /* One or more tables used to resolve names */
10344  ExprList *pEList;    /* Optional list of named expressions */
10345  int nRef;            /* Number of names resolved by this context */
10346  int nErr;            /* Number of errors encountered while resolving names */
10347  u8 allowAgg;         /* Aggregate functions allowed here */
10348  u8 hasAgg;           /* True if aggregates are seen */
10349  u8 isCheck;          /* True if resolving names in a CHECK constraint */
10350  int nDepth;          /* Depth of subquery recursion. 1 for no recursion */
10351  AggInfo *pAggInfo;   /* Information about aggregates at this level */
10352  NameContext *pNext;  /* Next outer name context.  NULL for outermost */
10353};
10354
10355/*
10356** An instance of the following structure contains all information
10357** needed to generate code for a single SELECT statement.
10358**
10359** nLimit is set to -1 if there is no LIMIT clause.  nOffset is set to 0.
10360** If there is a LIMIT clause, the parser sets nLimit to the value of the
10361** limit and nOffset to the value of the offset (or 0 if there is not
10362** offset).  But later on, nLimit and nOffset become the memory locations
10363** in the VDBE that record the limit and offset counters.
10364**
10365** addrOpenEphm[] entries contain the address of OP_OpenEphemeral opcodes.
10366** These addresses must be stored so that we can go back and fill in
10367** the P4_KEYINFO and P2 parameters later.  Neither the KeyInfo nor
10368** the number of columns in P2 can be computed at the same time
10369** as the OP_OpenEphm instruction is coded because not
10370** enough information about the compound query is known at that point.
10371** The KeyInfo for addrOpenTran[0] and [1] contains collating sequences
10372** for the result set.  The KeyInfo for addrOpenTran[2] contains collating
10373** sequences for the ORDER BY clause.
10374*/
10375struct Select {
10376  ExprList *pEList;      /* The fields of the result */
10377  u8 op;                 /* One of: TK_UNION TK_ALL TK_INTERSECT TK_EXCEPT */
10378  char affinity;         /* MakeRecord with this affinity for SRT_Set */
10379  u16 selFlags;          /* Various SF_* values */
10380  SrcList *pSrc;         /* The FROM clause */
10381  Expr *pWhere;          /* The WHERE clause */
10382  ExprList *pGroupBy;    /* The GROUP BY clause */
10383  Expr *pHaving;         /* The HAVING clause */
10384  ExprList *pOrderBy;    /* The ORDER BY clause */
10385  Select *pPrior;        /* Prior select in a compound select statement */
10386  Select *pNext;         /* Next select to the left in a compound */
10387  Select *pRightmost;    /* Right-most select in a compound select statement */
10388  Expr *pLimit;          /* LIMIT expression. NULL means not used. */
10389  Expr *pOffset;         /* OFFSET expression. NULL means not used. */
10390  int iLimit, iOffset;   /* Memory registers holding LIMIT & OFFSET counters */
10391  int addrOpenEphm[3];   /* OP_OpenEphem opcodes related to this select */
10392  double nSelectRow;     /* Estimated number of result rows */
10393};
10394
10395/*
10396** Allowed values for Select.selFlags.  The "SF" prefix stands for
10397** "Select Flag".
10398*/
10399#define SF_Distinct        0x0001  /* Output should be DISTINCT */
10400#define SF_Resolved        0x0002  /* Identifiers have been resolved */
10401#define SF_Aggregate       0x0004  /* Contains aggregate functions */
10402#define SF_UsesEphemeral   0x0008  /* Uses the OpenEphemeral opcode */
10403#define SF_Expanded        0x0010  /* sqlite3SelectExpand() called on this */
10404#define SF_HasTypeInfo     0x0020  /* FROM subqueries have Table metadata */
10405
10406
10407/*
10408** The results of a select can be distributed in several ways.  The
10409** "SRT" prefix means "SELECT Result Type".
10410*/
10411#define SRT_Union        1  /* Store result as keys in an index */
10412#define SRT_Except       2  /* Remove result from a UNION index */
10413#define SRT_Exists       3  /* Store 1 if the result is not empty */
10414#define SRT_Discard      4  /* Do not save the results anywhere */
10415
10416/* The ORDER BY clause is ignored for all of the above */
10417#define IgnorableOrderby(X) ((X->eDest)<=SRT_Discard)
10418
10419#define SRT_Output       5  /* Output each row of result */
10420#define SRT_Mem          6  /* Store result in a memory cell */
10421#define SRT_Set          7  /* Store results as keys in an index */
10422#define SRT_Table        8  /* Store result as data with an automatic rowid */
10423#define SRT_EphemTab     9  /* Create transient tab and store like SRT_Table */
10424#define SRT_Coroutine   10  /* Generate a single row of result */
10425
10426/*
10427** A structure used to customize the behavior of sqlite3Select(). See
10428** comments above sqlite3Select() for details.
10429*/
10430typedef struct SelectDest SelectDest;
10431struct SelectDest {
10432  u8 eDest;         /* How to dispose of the results */
10433  u8 affinity;      /* Affinity used when eDest==SRT_Set */
10434  int iParm;        /* A parameter used by the eDest disposal method */
10435  int iMem;         /* Base register where results are written */
10436  int nMem;         /* Number of registers allocated */
10437};
10438
10439/*
10440** During code generation of statements that do inserts into AUTOINCREMENT
10441** tables, the following information is attached to the Table.u.autoInc.p
10442** pointer of each autoincrement table to record some side information that
10443** the code generator needs.  We have to keep per-table autoincrement
10444** information in case inserts are down within triggers.  Triggers do not
10445** normally coordinate their activities, but we do need to coordinate the
10446** loading and saving of autoincrement information.
10447*/
10448struct AutoincInfo {
10449  AutoincInfo *pNext;   /* Next info block in a list of them all */
10450  Table *pTab;          /* Table this info block refers to */
10451  int iDb;              /* Index in sqlite3.aDb[] of database holding pTab */
10452  int regCtr;           /* Memory register holding the rowid counter */
10453};
10454
10455/*
10456** Size of the column cache
10457*/
10458#ifndef SQLITE_N_COLCACHE
10459# define SQLITE_N_COLCACHE 10
10460#endif
10461
10462/*
10463** At least one instance of the following structure is created for each
10464** trigger that may be fired while parsing an INSERT, UPDATE or DELETE
10465** statement. All such objects are stored in the linked list headed at
10466** Parse.pTriggerPrg and deleted once statement compilation has been
10467** completed.
10468**
10469** A Vdbe sub-program that implements the body and WHEN clause of trigger
10470** TriggerPrg.pTrigger, assuming a default ON CONFLICT clause of
10471** TriggerPrg.orconf, is stored in the TriggerPrg.pProgram variable.
10472** The Parse.pTriggerPrg list never contains two entries with the same
10473** values for both pTrigger and orconf.
10474**
10475** The TriggerPrg.aColmask[0] variable is set to a mask of old.* columns
10476** accessed (or set to 0 for triggers fired as a result of INSERT
10477** statements). Similarly, the TriggerPrg.aColmask[1] variable is set to
10478** a mask of new.* columns used by the program.
10479*/
10480struct TriggerPrg {
10481  Trigger *pTrigger;      /* Trigger this program was coded from */
10482  int orconf;             /* Default ON CONFLICT policy */
10483  SubProgram *pProgram;   /* Program implementing pTrigger/orconf */
10484  u32 aColmask[2];        /* Masks of old.*, new.* columns accessed */
10485  TriggerPrg *pNext;      /* Next entry in Parse.pTriggerPrg list */
10486};
10487
10488/*
10489** The yDbMask datatype for the bitmask of all attached databases.
10490*/
10491#if SQLITE_MAX_ATTACHED>30
10492  typedef sqlite3_uint64 yDbMask;
10493#else
10494  typedef unsigned int yDbMask;
10495#endif
10496
10497/*
10498** An SQL parser context.  A copy of this structure is passed through
10499** the parser and down into all the parser action routine in order to
10500** carry around information that is global to the entire parse.
10501**
10502** The structure is divided into two parts.  When the parser and code
10503** generate call themselves recursively, the first part of the structure
10504** is constant but the second part is reset at the beginning and end of
10505** each recursion.
10506**
10507** The nTableLock and aTableLock variables are only used if the shared-cache
10508** feature is enabled (if sqlite3Tsd()->useSharedData is true). They are
10509** used to store the set of table-locks required by the statement being
10510** compiled. Function sqlite3TableLock() is used to add entries to the
10511** list.
10512*/
10513struct Parse {
10514  sqlite3 *db;         /* The main database structure */
10515  int rc;              /* Return code from execution */
10516  char *zErrMsg;       /* An error message */
10517  Vdbe *pVdbe;         /* An engine for executing database bytecode */
10518  u8 colNamesSet;      /* TRUE after OP_ColumnName has been issued to pVdbe */
10519  u8 nameClash;        /* A permanent table name clashes with temp table name */
10520  u8 checkSchema;      /* Causes schema cookie check after an error */
10521  u8 nested;           /* Number of nested calls to the parser/code generator */
10522  u8 parseError;       /* True after a parsing error.  Ticket #1794 */
10523  u8 nTempReg;         /* Number of temporary registers in aTempReg[] */
10524  u8 nTempInUse;       /* Number of aTempReg[] currently checked out */
10525  int aTempReg[8];     /* Holding area for temporary registers */
10526  int nRangeReg;       /* Size of the temporary register block */
10527  int iRangeReg;       /* First register in temporary register block */
10528  int nErr;            /* Number of errors seen */
10529  int nTab;            /* Number of previously allocated VDBE cursors */
10530  int nMem;            /* Number of memory cells used so far */
10531  int nSet;            /* Number of sets used so far */
10532  int ckBase;          /* Base register of data during check constraints */
10533  int iCacheLevel;     /* ColCache valid when aColCache[].iLevel<=iCacheLevel */
10534  int iCacheCnt;       /* Counter used to generate aColCache[].lru values */
10535  u8 nColCache;        /* Number of entries in the column cache */
10536  u8 iColCache;        /* Next entry of the cache to replace */
10537  struct yColCache {
10538    int iTable;           /* Table cursor number */
10539    int iColumn;          /* Table column number */
10540    u8 tempReg;           /* iReg is a temp register that needs to be freed */
10541    int iLevel;           /* Nesting level */
10542    int iReg;             /* Reg with value of this column. 0 means none. */
10543    int lru;              /* Least recently used entry has the smallest value */
10544  } aColCache[SQLITE_N_COLCACHE];  /* One for each column cache entry */
10545  yDbMask writeMask;   /* Start a write transaction on these databases */
10546  yDbMask cookieMask;  /* Bitmask of schema verified databases */
10547  u8 isMultiWrite;     /* True if statement may affect/insert multiple rows */
10548  u8 mayAbort;         /* True if statement may throw an ABORT exception */
10549  int cookieGoto;      /* Address of OP_Goto to cookie verifier subroutine */
10550  int cookieValue[SQLITE_MAX_ATTACHED+2];  /* Values of cookies to verify */
10551#ifndef SQLITE_OMIT_SHARED_CACHE
10552  int nTableLock;        /* Number of locks in aTableLock */
10553  TableLock *aTableLock; /* Required table locks for shared-cache mode */
10554#endif
10555  int regRowid;        /* Register holding rowid of CREATE TABLE entry */
10556  int regRoot;         /* Register holding root page number for new objects */
10557  AutoincInfo *pAinc;  /* Information about AUTOINCREMENT counters */
10558  int nMaxArg;         /* Max args passed to user function by sub-program */
10559
10560  /* Information used while coding trigger programs. */
10561  Parse *pToplevel;    /* Parse structure for main program (or NULL) */
10562  Table *pTriggerTab;  /* Table triggers are being coded for */
10563  u32 oldmask;         /* Mask of old.* columns referenced */
10564  u32 newmask;         /* Mask of new.* columns referenced */
10565  u8 eTriggerOp;       /* TK_UPDATE, TK_INSERT or TK_DELETE */
10566  u8 eOrconf;          /* Default ON CONFLICT policy for trigger steps */
10567  u8 disableTriggers;  /* True to disable triggers */
10568  double nQueryLoop;   /* Estimated number of iterations of a query */
10569
10570  /* Above is constant between recursions.  Below is reset before and after
10571  ** each recursion */
10572
10573  int nVar;            /* Number of '?' variables seen in the SQL so far */
10574  int nVarExpr;        /* Number of used slots in apVarExpr[] */
10575  int nVarExprAlloc;   /* Number of allocated slots in apVarExpr[] */
10576  Expr **apVarExpr;    /* Pointers to :aaa and $aaaa wildcard expressions */
10577  Vdbe *pReprepare;    /* VM being reprepared (sqlite3Reprepare()) */
10578  int nAlias;          /* Number of aliased result set columns */
10579  int nAliasAlloc;     /* Number of allocated slots for aAlias[] */
10580  int *aAlias;         /* Register used to hold aliased result */
10581  u8 explain;          /* True if the EXPLAIN flag is found on the query */
10582  Token sNameToken;    /* Token with unqualified schema object name */
10583  Token sLastToken;    /* The last token parsed */
10584  const char *zTail;   /* All SQL text past the last semicolon parsed */
10585  Table *pNewTable;    /* A table being constructed by CREATE TABLE */
10586  Trigger *pNewTrigger;     /* Trigger under construct by a CREATE TRIGGER */
10587  const char *zAuthContext; /* The 6th parameter to db->xAuth callbacks */
10588#ifndef SQLITE_OMIT_VIRTUALTABLE
10589  Token sArg;                /* Complete text of a module argument */
10590  u8 declareVtab;            /* True if inside sqlite3_declare_vtab() */
10591  int nVtabLock;             /* Number of virtual tables to lock */
10592  Table **apVtabLock;        /* Pointer to virtual tables needing locking */
10593#endif
10594  int nHeight;            /* Expression tree height of current sub-select */
10595  Table *pZombieTab;      /* List of Table objects to delete after code gen */
10596  TriggerPrg *pTriggerPrg;    /* Linked list of coded triggers */
10597
10598#ifndef SQLITE_OMIT_EXPLAIN
10599  int iSelectId;
10600  int iNextSelectId;
10601#endif
10602};
10603
10604#ifdef SQLITE_OMIT_VIRTUALTABLE
10605  #define IN_DECLARE_VTAB 0
10606#else
10607  #define IN_DECLARE_VTAB (pParse->declareVtab)
10608#endif
10609
10610/*
10611** An instance of the following structure can be declared on a stack and used
10612** to save the Parse.zAuthContext value so that it can be restored later.
10613*/
10614struct AuthContext {
10615  const char *zAuthContext;   /* Put saved Parse.zAuthContext here */
10616  Parse *pParse;              /* The Parse structure */
10617};
10618
10619/*
10620** Bitfield flags for P5 value in OP_Insert and OP_Delete
10621*/
10622#define OPFLAG_NCHANGE       0x01    /* Set to update db->nChange */
10623#define OPFLAG_LASTROWID     0x02    /* Set to update db->lastRowid */
10624#define OPFLAG_ISUPDATE      0x04    /* This OP_Insert is an sql UPDATE */
10625#define OPFLAG_APPEND        0x08    /* This is likely to be an append */
10626#define OPFLAG_USESEEKRESULT 0x10    /* Try to avoid a seek in BtreeInsert() */
10627#define OPFLAG_CLEARCACHE    0x20    /* Clear pseudo-table cache in OP_Column */
10628
10629/*
10630 * Each trigger present in the database schema is stored as an instance of
10631 * struct Trigger.
10632 *
10633 * Pointers to instances of struct Trigger are stored in two ways.
10634 * 1. In the "trigHash" hash table (part of the sqlite3* that represents the
10635 *    database). This allows Trigger structures to be retrieved by name.
10636 * 2. All triggers associated with a single table form a linked list, using the
10637 *    pNext member of struct Trigger. A pointer to the first element of the
10638 *    linked list is stored as the "pTrigger" member of the associated
10639 *    struct Table.
10640 *
10641 * The "step_list" member points to the first element of a linked list
10642 * containing the SQL statements specified as the trigger program.
10643 */
10644struct Trigger {
10645  char *zName;            /* The name of the trigger                        */
10646  char *table;            /* The table or view to which the trigger applies */
10647  u8 op;                  /* One of TK_DELETE, TK_UPDATE, TK_INSERT         */
10648  u8 tr_tm;               /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
10649  Expr *pWhen;            /* The WHEN clause of the expression (may be NULL) */
10650  IdList *pColumns;       /* If this is an UPDATE OF <column-list> trigger,
10651                             the <column-list> is stored here */
10652  Schema *pSchema;        /* Schema containing the trigger */
10653  Schema *pTabSchema;     /* Schema containing the table */
10654  TriggerStep *step_list; /* Link list of trigger program steps             */
10655  Trigger *pNext;         /* Next trigger associated with the table */
10656};
10657
10658/*
10659** A trigger is either a BEFORE or an AFTER trigger.  The following constants
10660** determine which.
10661**
10662** If there are multiple triggers, you might of some BEFORE and some AFTER.
10663** In that cases, the constants below can be ORed together.
10664*/
10665#define TRIGGER_BEFORE  1
10666#define TRIGGER_AFTER   2
10667
10668/*
10669 * An instance of struct TriggerStep is used to store a single SQL statement
10670 * that is a part of a trigger-program.
10671 *
10672 * Instances of struct TriggerStep are stored in a singly linked list (linked
10673 * using the "pNext" member) referenced by the "step_list" member of the
10674 * associated struct Trigger instance. The first element of the linked list is
10675 * the first step of the trigger-program.
10676 *
10677 * The "op" member indicates whether this is a "DELETE", "INSERT", "UPDATE" or
10678 * "SELECT" statement. The meanings of the other members is determined by the
10679 * value of "op" as follows:
10680 *
10681 * (op == TK_INSERT)
10682 * orconf    -> stores the ON CONFLICT algorithm
10683 * pSelect   -> If this is an INSERT INTO ... SELECT ... statement, then
10684 *              this stores a pointer to the SELECT statement. Otherwise NULL.
10685 * target    -> A token holding the quoted name of the table to insert into.
10686 * pExprList -> If this is an INSERT INTO ... VALUES ... statement, then
10687 *              this stores values to be inserted. Otherwise NULL.
10688 * pIdList   -> If this is an INSERT INTO ... (<column-names>) VALUES ...
10689 *              statement, then this stores the column-names to be
10690 *              inserted into.
10691 *
10692 * (op == TK_DELETE)
10693 * target    -> A token holding the quoted name of the table to delete from.
10694 * pWhere    -> The WHERE clause of the DELETE statement if one is specified.
10695 *              Otherwise NULL.
10696 *
10697 * (op == TK_UPDATE)
10698 * target    -> A token holding the quoted name of the table to update rows of.
10699 * pWhere    -> The WHERE clause of the UPDATE statement if one is specified.
10700 *              Otherwise NULL.
10701 * pExprList -> A list of the columns to update and the expressions to update
10702 *              them to. See sqlite3Update() documentation of "pChanges"
10703 *              argument.
10704 *
10705 */
10706struct TriggerStep {
10707  u8 op;               /* One of TK_DELETE, TK_UPDATE, TK_INSERT, TK_SELECT */
10708  u8 orconf;           /* OE_Rollback etc. */
10709  Trigger *pTrig;      /* The trigger that this step is a part of */
10710  Select *pSelect;     /* SELECT statment or RHS of INSERT INTO .. SELECT ... */
10711  Token target;        /* Target table for DELETE, UPDATE, INSERT */
10712  Expr *pWhere;        /* The WHERE clause for DELETE or UPDATE steps */
10713  ExprList *pExprList; /* SET clause for UPDATE.  VALUES clause for INSERT */
10714  IdList *pIdList;     /* Column names for INSERT */
10715  TriggerStep *pNext;  /* Next in the link-list */
10716  TriggerStep *pLast;  /* Last element in link-list. Valid for 1st elem only */
10717};
10718
10719/*
10720** The following structure contains information used by the sqliteFix...
10721** routines as they walk the parse tree to make database references
10722** explicit.
10723*/
10724typedef struct DbFixer DbFixer;
10725struct DbFixer {
10726  Parse *pParse;      /* The parsing context.  Error messages written here */
10727  const char *zDb;    /* Make sure all objects are contained in this database */
10728  const char *zType;  /* Type of the container - used for error messages */
10729  const Token *pName; /* Name of the container - used for error messages */
10730};
10731
10732/*
10733** An objected used to accumulate the text of a string where we
10734** do not necessarily know how big the string will be in the end.
10735*/
10736struct StrAccum {
10737  sqlite3 *db;         /* Optional database for lookaside.  Can be NULL */
10738  char *zBase;         /* A base allocation.  Not from malloc. */
10739  char *zText;         /* The string collected so far */
10740  int  nChar;          /* Length of the string so far */
10741  int  nAlloc;         /* Amount of space allocated in zText */
10742  int  mxAlloc;        /* Maximum allowed string length */
10743  u8   mallocFailed;   /* Becomes true if any memory allocation fails */
10744  u8   useMalloc;      /* 0: none,  1: sqlite3DbMalloc,  2: sqlite3_malloc */
10745  u8   tooBig;         /* Becomes true if string size exceeds limits */
10746};
10747
10748/*
10749** A pointer to this structure is used to communicate information
10750** from sqlite3Init and OP_ParseSchema into the sqlite3InitCallback.
10751*/
10752typedef struct {
10753  sqlite3 *db;        /* The database being initialized */
10754  int iDb;            /* 0 for main database.  1 for TEMP, 2.. for ATTACHed */
10755  char **pzErrMsg;    /* Error message stored here */
10756  int rc;             /* Result code stored here */
10757} InitData;
10758
10759/*
10760** Structure containing global configuration data for the SQLite library.
10761**
10762** This structure also contains some state information.
10763*/
10764struct Sqlite3Config {
10765  int bMemstat;                     /* True to enable memory status */
10766  int bCoreMutex;                   /* True to enable core mutexing */
10767  int bFullMutex;                   /* True to enable full mutexing */
10768  int mxStrlen;                     /* Maximum string length */
10769  int szLookaside;                  /* Default lookaside buffer size */
10770  int nLookaside;                   /* Default lookaside buffer count */
10771  sqlite3_mem_methods m;            /* Low-level memory allocation interface */
10772  sqlite3_mutex_methods mutex;      /* Low-level mutex interface */
10773  sqlite3_pcache_methods pcache;    /* Low-level page-cache interface */
10774  void *pHeap;                      /* Heap storage space */
10775  int nHeap;                        /* Size of pHeap[] */
10776  int mnReq, mxReq;                 /* Min and max heap requests sizes */
10777  void *pScratch;                   /* Scratch memory */
10778  int szScratch;                    /* Size of each scratch buffer */
10779  int nScratch;                     /* Number of scratch buffers */
10780  void *pPage;                      /* Page cache memory */
10781  int szPage;                       /* Size of each page in pPage[] */
10782  int nPage;                        /* Number of pages in pPage[] */
10783  int mxParserStack;                /* maximum depth of the parser stack */
10784  int sharedCacheEnabled;           /* true if shared-cache mode enabled */
10785  /* The above might be initialized to non-zero.  The following need to always
10786  ** initially be zero, however. */
10787  int isInit;                       /* True after initialization has finished */
10788  int inProgress;                   /* True while initialization in progress */
10789  int isMutexInit;                  /* True after mutexes are initialized */
10790  int isMallocInit;                 /* True after malloc is initialized */
10791  int isPCacheInit;                 /* True after malloc is initialized */
10792  sqlite3_mutex *pInitMutex;        /* Mutex used by sqlite3_initialize() */
10793  int nRefInitMutex;                /* Number of users of pInitMutex */
10794  void (*xLog)(void*,int,const char*); /* Function for logging */
10795  void *pLogArg;                       /* First argument to xLog() */
10796};
10797
10798/*
10799** Context pointer passed down through the tree-walk.
10800*/
10801struct Walker {
10802  int (*xExprCallback)(Walker*, Expr*);     /* Callback for expressions */
10803  int (*xSelectCallback)(Walker*,Select*);  /* Callback for SELECTs */
10804  Parse *pParse;                            /* Parser context.  */
10805  union {                                   /* Extra data for callback */
10806    NameContext *pNC;                          /* Naming context */
10807    int i;                                     /* Integer value */
10808  } u;
10809};
10810
10811/* Forward declarations */
10812SQLITE_PRIVATE int sqlite3WalkExpr(Walker*, Expr*);
10813SQLITE_PRIVATE int sqlite3WalkExprList(Walker*, ExprList*);
10814SQLITE_PRIVATE int sqlite3WalkSelect(Walker*, Select*);
10815SQLITE_PRIVATE int sqlite3WalkSelectExpr(Walker*, Select*);
10816SQLITE_PRIVATE int sqlite3WalkSelectFrom(Walker*, Select*);
10817
10818/*
10819** Return code from the parse-tree walking primitives and their
10820** callbacks.
10821*/
10822#define WRC_Continue    0   /* Continue down into children */
10823#define WRC_Prune       1   /* Omit children but continue walking siblings */
10824#define WRC_Abort       2   /* Abandon the tree walk */
10825
10826/*
10827** Assuming zIn points to the first byte of a UTF-8 character,
10828** advance zIn to point to the first byte of the next UTF-8 character.
10829*/
10830#define SQLITE_SKIP_UTF8(zIn) {                        \
10831  if( (*(zIn++))>=0xc0 ){                              \
10832    while( (*zIn & 0xc0)==0x80 ){ zIn++; }             \
10833  }                                                    \
10834}
10835
10836/*
10837** The SQLITE_*_BKPT macros are substitutes for the error codes with
10838** the same name but without the _BKPT suffix.  These macros invoke
10839** routines that report the line-number on which the error originated
10840** using sqlite3_log().  The routines also provide a convenient place
10841** to set a debugger breakpoint.
10842*/
10843SQLITE_PRIVATE int sqlite3CorruptError(int);
10844SQLITE_PRIVATE int sqlite3MisuseError(int);
10845SQLITE_PRIVATE int sqlite3CantopenError(int);
10846#define SQLITE_CORRUPT_BKPT sqlite3CorruptError(__LINE__)
10847#define SQLITE_MISUSE_BKPT sqlite3MisuseError(__LINE__)
10848#define SQLITE_CANTOPEN_BKPT sqlite3CantopenError(__LINE__)
10849
10850
10851/*
10852** FTS4 is really an extension for FTS3.  It is enabled using the
10853** SQLITE_ENABLE_FTS3 macro.  But to avoid confusion we also all
10854** the SQLITE_ENABLE_FTS4 macro to serve as an alisse for SQLITE_ENABLE_FTS3.
10855*/
10856#if defined(SQLITE_ENABLE_FTS4) && !defined(SQLITE_ENABLE_FTS3)
10857# define SQLITE_ENABLE_FTS3
10858#endif
10859
10860/*
10861** The ctype.h header is needed for non-ASCII systems.  It is also
10862** needed by FTS3 when FTS3 is included in the amalgamation.
10863*/
10864#if !defined(SQLITE_ASCII) || \
10865    (defined(SQLITE_ENABLE_FTS3) && defined(SQLITE_AMALGAMATION))
10866# include <ctype.h>
10867#endif
10868
10869/*
10870** The CoreServices.h and CoreFoundation.h headers are needed for excluding a
10871** -journal file from Time Machine backups when its associated database has
10872** previously been excluded by the client code.
10873*/
10874#if defined(__APPLE__)
10875#include <CoreServices/CoreServices.h>
10876#include <CoreFoundation/CoreFoundation.h>
10877#endif
10878
10879/*
10880** The following macros mimic the standard library functions toupper(),
10881** isspace(), isalnum(), isdigit() and isxdigit(), respectively. The
10882** sqlite versions only work for ASCII characters, regardless of locale.
10883*/
10884#ifdef SQLITE_ASCII
10885# define sqlite3Toupper(x)  ((x)&~(sqlite3CtypeMap[(unsigned char)(x)]&0x20))
10886# define sqlite3Isspace(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x01)
10887# define sqlite3Isalnum(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x06)
10888# define sqlite3Isalpha(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x02)
10889# define sqlite3Isdigit(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x04)
10890# define sqlite3Isxdigit(x)  (sqlite3CtypeMap[(unsigned char)(x)]&0x08)
10891# define sqlite3Tolower(x)   (sqlite3UpperToLower[(unsigned char)(x)])
10892#else
10893# define sqlite3Toupper(x)   toupper((unsigned char)(x))
10894# define sqlite3Isspace(x)   isspace((unsigned char)(x))
10895# define sqlite3Isalnum(x)   isalnum((unsigned char)(x))
10896# define sqlite3Isalpha(x)   isalpha((unsigned char)(x))
10897# define sqlite3Isdigit(x)   isdigit((unsigned char)(x))
10898# define sqlite3Isxdigit(x)  isxdigit((unsigned char)(x))
10899# define sqlite3Tolower(x)   tolower((unsigned char)(x))
10900#endif
10901
10902/*
10903** Internal function prototypes
10904*/
10905SQLITE_PRIVATE int sqlite3StrICmp(const char *, const char *);
10906SQLITE_PRIVATE int sqlite3Strlen30(const char*);
10907#define sqlite3StrNICmp sqlite3_strnicmp
10908
10909SQLITE_PRIVATE int sqlite3MallocInit(void);
10910SQLITE_PRIVATE void sqlite3MallocEnd(void);
10911SQLITE_PRIVATE void *sqlite3Malloc(int);
10912SQLITE_PRIVATE void *sqlite3MallocZero(int);
10913SQLITE_PRIVATE void *sqlite3DbMallocZero(sqlite3*, int);
10914SQLITE_PRIVATE void *sqlite3DbMallocRaw(sqlite3*, int);
10915SQLITE_PRIVATE char *sqlite3DbStrDup(sqlite3*,const char*);
10916SQLITE_PRIVATE char *sqlite3DbStrNDup(sqlite3*,const char*, int);
10917SQLITE_PRIVATE void *sqlite3Realloc(void*, int);
10918SQLITE_PRIVATE void *sqlite3DbReallocOrFree(sqlite3 *, void *, int);
10919SQLITE_PRIVATE void *sqlite3DbRealloc(sqlite3 *, void *, int);
10920SQLITE_PRIVATE void sqlite3DbFree(sqlite3*, void*);
10921SQLITE_PRIVATE int sqlite3MallocSize(void*);
10922SQLITE_PRIVATE int sqlite3DbMallocSize(sqlite3*, void*);
10923SQLITE_PRIVATE void *sqlite3ScratchMalloc(int);
10924SQLITE_PRIVATE void sqlite3ScratchFree(void*);
10925SQLITE_PRIVATE void *sqlite3PageMalloc(int);
10926SQLITE_PRIVATE void sqlite3PageFree(void*);
10927SQLITE_PRIVATE void sqlite3MemSetDefault(void);
10928SQLITE_PRIVATE void sqlite3BenignMallocHooks(void (*)(void), void (*)(void));
10929SQLITE_PRIVATE int sqlite3HeapNearlyFull(void);
10930
10931/*
10932** On systems with ample stack space and that support alloca(), make
10933** use of alloca() to obtain space for large automatic objects.  By default,
10934** obtain space from malloc().
10935**
10936** The alloca() routine never returns NULL.  This will cause code paths
10937** that deal with sqlite3StackAlloc() failures to be unreachable.
10938*/
10939#ifdef SQLITE_USE_ALLOCA
10940# define sqlite3StackAllocRaw(D,N)   alloca(N)
10941# define sqlite3StackAllocZero(D,N)  memset(alloca(N), 0, N)
10942# define sqlite3StackFree(D,P)
10943#else
10944# define sqlite3StackAllocRaw(D,N)   sqlite3DbMallocRaw(D,N)
10945# define sqlite3StackAllocZero(D,N)  sqlite3DbMallocZero(D,N)
10946# define sqlite3StackFree(D,P)       sqlite3DbFree(D,P)
10947#endif
10948
10949#ifdef SQLITE_ENABLE_MEMSYS3
10950SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys3(void);
10951#endif
10952#ifdef SQLITE_ENABLE_MEMSYS5
10953SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys5(void);
10954#endif
10955
10956
10957#ifndef SQLITE_MUTEX_OMIT
10958SQLITE_PRIVATE   sqlite3_mutex_methods const *sqlite3DefaultMutex(void);
10959SQLITE_PRIVATE   sqlite3_mutex_methods const *sqlite3NoopMutex(void);
10960SQLITE_PRIVATE   sqlite3_mutex *sqlite3MutexAlloc(int);
10961SQLITE_PRIVATE   int sqlite3MutexInit(void);
10962SQLITE_PRIVATE   int sqlite3MutexEnd(void);
10963#endif
10964
10965SQLITE_PRIVATE int sqlite3StatusValue(int);
10966SQLITE_PRIVATE void sqlite3StatusAdd(int, int);
10967SQLITE_PRIVATE void sqlite3StatusSet(int, int);
10968
10969#ifndef SQLITE_OMIT_FLOATING_POINT
10970SQLITE_PRIVATE   int sqlite3IsNaN(double);
10971#else
10972# define sqlite3IsNaN(X)  0
10973#endif
10974
10975SQLITE_PRIVATE void sqlite3VXPrintf(StrAccum*, int, const char*, va_list);
10976#ifndef SQLITE_OMIT_TRACE
10977SQLITE_PRIVATE void sqlite3XPrintf(StrAccum*, const char*, ...);
10978#endif
10979SQLITE_PRIVATE char *sqlite3MPrintf(sqlite3*,const char*, ...);
10980SQLITE_PRIVATE char *sqlite3VMPrintf(sqlite3*,const char*, va_list);
10981SQLITE_PRIVATE char *sqlite3MAppendf(sqlite3*,char*,const char*,...);
10982#if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
10983SQLITE_PRIVATE   void sqlite3DebugPrintf(const char*, ...);
10984#endif
10985#if defined(SQLITE_TEST)
10986SQLITE_PRIVATE   void *sqlite3TestTextToPtr(const char*);
10987#endif
10988SQLITE_PRIVATE void sqlite3SetString(char **, sqlite3*, const char*, ...);
10989SQLITE_PRIVATE void sqlite3ErrorMsg(Parse*, const char*, ...);
10990SQLITE_PRIVATE int sqlite3Dequote(char*);
10991SQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char*, int);
10992SQLITE_PRIVATE int sqlite3RunParser(Parse*, const char*, char **);
10993SQLITE_PRIVATE void sqlite3FinishCoding(Parse*);
10994SQLITE_PRIVATE int sqlite3GetTempReg(Parse*);
10995SQLITE_PRIVATE void sqlite3ReleaseTempReg(Parse*,int);
10996SQLITE_PRIVATE int sqlite3GetTempRange(Parse*,int);
10997SQLITE_PRIVATE void sqlite3ReleaseTempRange(Parse*,int,int);
10998SQLITE_PRIVATE Expr *sqlite3ExprAlloc(sqlite3*,int,const Token*,int);
10999SQLITE_PRIVATE Expr *sqlite3Expr(sqlite3*,int,const char*);
11000SQLITE_PRIVATE void sqlite3ExprAttachSubtrees(sqlite3*,Expr*,Expr*,Expr*);
11001SQLITE_PRIVATE Expr *sqlite3PExpr(Parse*, int, Expr*, Expr*, const Token*);
11002SQLITE_PRIVATE Expr *sqlite3ExprAnd(sqlite3*,Expr*, Expr*);
11003SQLITE_PRIVATE Expr *sqlite3ExprFunction(Parse*,ExprList*, Token*);
11004SQLITE_PRIVATE void sqlite3ExprAssignVarNumber(Parse*, Expr*);
11005SQLITE_PRIVATE void sqlite3ExprDelete(sqlite3*, Expr*);
11006SQLITE_PRIVATE ExprList *sqlite3ExprListAppend(Parse*,ExprList*,Expr*);
11007SQLITE_PRIVATE void sqlite3ExprListSetName(Parse*,ExprList*,Token*,int);
11008SQLITE_PRIVATE void sqlite3ExprListSetSpan(Parse*,ExprList*,ExprSpan*);
11009SQLITE_PRIVATE void sqlite3ExprListDelete(sqlite3*, ExprList*);
11010SQLITE_PRIVATE int sqlite3Init(sqlite3*, char**);
11011SQLITE_PRIVATE int sqlite3InitCallback(void*, int, char**, char**);
11012SQLITE_PRIVATE void sqlite3Pragma(Parse*,Token*,Token*,Token*,int);
11013SQLITE_PRIVATE void sqlite3ResetInternalSchema(sqlite3*, int);
11014SQLITE_PRIVATE void sqlite3BeginParse(Parse*,int);
11015SQLITE_PRIVATE void sqlite3CommitInternalChanges(sqlite3*);
11016SQLITE_PRIVATE Table *sqlite3ResultSetOfSelect(Parse*,Select*);
11017SQLITE_PRIVATE void sqlite3OpenMasterTable(Parse *, int);
11018SQLITE_PRIVATE void sqlite3StartTable(Parse*,Token*,Token*,int,int,int,int);
11019SQLITE_PRIVATE void sqlite3AddColumn(Parse*,Token*);
11020SQLITE_PRIVATE void sqlite3AddNotNull(Parse*, int);
11021SQLITE_PRIVATE void sqlite3AddPrimaryKey(Parse*, ExprList*, int, int, int);
11022SQLITE_PRIVATE void sqlite3AddCheckConstraint(Parse*, Expr*);
11023SQLITE_PRIVATE void sqlite3AddColumnType(Parse*,Token*);
11024SQLITE_PRIVATE void sqlite3AddDefaultValue(Parse*,ExprSpan*);
11025SQLITE_PRIVATE void sqlite3AddCollateType(Parse*, Token*);
11026SQLITE_PRIVATE void sqlite3EndTable(Parse*,Token*,Token*,Select*);
11027
11028SQLITE_PRIVATE Bitvec *sqlite3BitvecCreate(u32);
11029SQLITE_PRIVATE int sqlite3BitvecTest(Bitvec*, u32);
11030SQLITE_PRIVATE int sqlite3BitvecSet(Bitvec*, u32);
11031SQLITE_PRIVATE void sqlite3BitvecClear(Bitvec*, u32, void*);
11032SQLITE_PRIVATE void sqlite3BitvecDestroy(Bitvec*);
11033SQLITE_PRIVATE u32 sqlite3BitvecSize(Bitvec*);
11034SQLITE_PRIVATE int sqlite3BitvecBuiltinTest(int,int*);
11035
11036SQLITE_PRIVATE RowSet *sqlite3RowSetInit(sqlite3*, void*, unsigned int);
11037SQLITE_PRIVATE void sqlite3RowSetClear(RowSet*);
11038SQLITE_PRIVATE void sqlite3RowSetInsert(RowSet*, i64);
11039SQLITE_PRIVATE int sqlite3RowSetTest(RowSet*, u8 iBatch, i64);
11040SQLITE_PRIVATE int sqlite3RowSetNext(RowSet*, i64*);
11041
11042SQLITE_PRIVATE void sqlite3CreateView(Parse*,Token*,Token*,Token*,Select*,int,int);
11043
11044#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
11045SQLITE_PRIVATE   int sqlite3ViewGetColumnNames(Parse*,Table*);
11046#else
11047# define sqlite3ViewGetColumnNames(A,B) 0
11048#endif
11049
11050SQLITE_PRIVATE void sqlite3DropTable(Parse*, SrcList*, int, int);
11051SQLITE_PRIVATE void sqlite3DeleteTable(sqlite3*, Table*);
11052#ifndef SQLITE_OMIT_AUTOINCREMENT
11053SQLITE_PRIVATE   void sqlite3AutoincrementBegin(Parse *pParse);
11054SQLITE_PRIVATE   void sqlite3AutoincrementEnd(Parse *pParse);
11055#else
11056# define sqlite3AutoincrementBegin(X)
11057# define sqlite3AutoincrementEnd(X)
11058#endif
11059SQLITE_PRIVATE void sqlite3Insert(Parse*, SrcList*, ExprList*, Select*, IdList*, int);
11060SQLITE_PRIVATE void *sqlite3ArrayAllocate(sqlite3*,void*,int,int,int*,int*,int*);
11061SQLITE_PRIVATE IdList *sqlite3IdListAppend(sqlite3*, IdList*, Token*);
11062SQLITE_PRIVATE int sqlite3IdListIndex(IdList*,const char*);
11063SQLITE_PRIVATE SrcList *sqlite3SrcListEnlarge(sqlite3*, SrcList*, int, int);
11064SQLITE_PRIVATE SrcList *sqlite3SrcListAppend(sqlite3*, SrcList*, Token*, Token*);
11065SQLITE_PRIVATE SrcList *sqlite3SrcListAppendFromTerm(Parse*, SrcList*, Token*, Token*,
11066                                      Token*, Select*, Expr*, IdList*);
11067SQLITE_PRIVATE void sqlite3SrcListIndexedBy(Parse *, SrcList *, Token *);
11068SQLITE_PRIVATE int sqlite3IndexedByLookup(Parse *, struct SrcList_item *);
11069SQLITE_PRIVATE void sqlite3SrcListShiftJoinType(SrcList*);
11070SQLITE_PRIVATE void sqlite3SrcListAssignCursors(Parse*, SrcList*);
11071SQLITE_PRIVATE void sqlite3IdListDelete(sqlite3*, IdList*);
11072SQLITE_PRIVATE void sqlite3SrcListDelete(sqlite3*, SrcList*);
11073SQLITE_PRIVATE Index *sqlite3CreateIndex(Parse*,Token*,Token*,SrcList*,ExprList*,int,Token*,
11074                        Token*, int, int);
11075SQLITE_PRIVATE void sqlite3DropIndex(Parse*, SrcList*, int);
11076SQLITE_PRIVATE int sqlite3Select(Parse*, Select*, SelectDest*);
11077SQLITE_PRIVATE Select *sqlite3SelectNew(Parse*,ExprList*,SrcList*,Expr*,ExprList*,
11078                         Expr*,ExprList*,int,Expr*,Expr*);
11079SQLITE_PRIVATE void sqlite3SelectDelete(sqlite3*, Select*);
11080SQLITE_PRIVATE Table *sqlite3SrcListLookup(Parse*, SrcList*);
11081SQLITE_PRIVATE int sqlite3IsReadOnly(Parse*, Table*, int);
11082SQLITE_PRIVATE void sqlite3OpenTable(Parse*, int iCur, int iDb, Table*, int);
11083#if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
11084SQLITE_PRIVATE Expr *sqlite3LimitWhere(Parse *, SrcList *, Expr *, ExprList *, Expr *, Expr *, char *);
11085#endif
11086SQLITE_PRIVATE void sqlite3DeleteFrom(Parse*, SrcList*, Expr*);
11087SQLITE_PRIVATE void sqlite3Update(Parse*, SrcList*, ExprList*, Expr*, int);
11088SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(Parse*, SrcList*, Expr*, ExprList**, u16);
11089SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo*);
11090SQLITE_PRIVATE int sqlite3ExprCodeGetColumn(Parse*, Table*, int, int, int);
11091SQLITE_PRIVATE void sqlite3ExprCodeGetColumnOfTable(Vdbe*, Table*, int, int, int);
11092SQLITE_PRIVATE void sqlite3ExprCodeMove(Parse*, int, int, int);
11093SQLITE_PRIVATE void sqlite3ExprCodeCopy(Parse*, int, int, int);
11094SQLITE_PRIVATE void sqlite3ExprCacheStore(Parse*, int, int, int);
11095SQLITE_PRIVATE void sqlite3ExprCachePush(Parse*);
11096SQLITE_PRIVATE void sqlite3ExprCachePop(Parse*, int);
11097SQLITE_PRIVATE void sqlite3ExprCacheRemove(Parse*, int, int);
11098SQLITE_PRIVATE void sqlite3ExprCacheClear(Parse*);
11099SQLITE_PRIVATE void sqlite3ExprCacheAffinityChange(Parse*, int, int);
11100SQLITE_PRIVATE int sqlite3ExprCode(Parse*, Expr*, int);
11101SQLITE_PRIVATE int sqlite3ExprCodeTemp(Parse*, Expr*, int*);
11102SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse*, Expr*, int);
11103SQLITE_PRIVATE int sqlite3ExprCodeAndCache(Parse*, Expr*, int);
11104SQLITE_PRIVATE void sqlite3ExprCodeConstants(Parse*, Expr*);
11105SQLITE_PRIVATE int sqlite3ExprCodeExprList(Parse*, ExprList*, int, int);
11106SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse*, Expr*, int, int);
11107SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse*, Expr*, int, int);
11108SQLITE_PRIVATE Table *sqlite3FindTable(sqlite3*,const char*, const char*);
11109SQLITE_PRIVATE Table *sqlite3LocateTable(Parse*,int isView,const char*, const char*);
11110SQLITE_PRIVATE Index *sqlite3FindIndex(sqlite3*,const char*, const char*);
11111SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTable(sqlite3*,int,const char*);
11112SQLITE_PRIVATE void sqlite3UnlinkAndDeleteIndex(sqlite3*,int,const char*);
11113SQLITE_PRIVATE void sqlite3Vacuum(Parse*);
11114SQLITE_PRIVATE int sqlite3RunVacuum(char**, sqlite3*);
11115SQLITE_PRIVATE char *sqlite3NameFromToken(sqlite3*, Token*);
11116SQLITE_PRIVATE int sqlite3ExprCompare(Expr*, Expr*);
11117SQLITE_PRIVATE int sqlite3ExprListCompare(ExprList*, ExprList*);
11118SQLITE_PRIVATE void sqlite3ExprAnalyzeAggregates(NameContext*, Expr*);
11119SQLITE_PRIVATE void sqlite3ExprAnalyzeAggList(NameContext*,ExprList*);
11120SQLITE_PRIVATE Vdbe *sqlite3GetVdbe(Parse*);
11121SQLITE_PRIVATE void sqlite3PrngSaveState(void);
11122SQLITE_PRIVATE void sqlite3PrngRestoreState(void);
11123SQLITE_PRIVATE void sqlite3PrngResetState(void);
11124SQLITE_PRIVATE void sqlite3RollbackAll(sqlite3*);
11125SQLITE_PRIVATE void sqlite3CodeVerifySchema(Parse*, int);
11126SQLITE_PRIVATE void sqlite3CodeVerifyNamedSchema(Parse*, const char *zDb);
11127SQLITE_PRIVATE void sqlite3BeginTransaction(Parse*, int);
11128SQLITE_PRIVATE void sqlite3CommitTransaction(Parse*);
11129SQLITE_PRIVATE void sqlite3RollbackTransaction(Parse*);
11130SQLITE_PRIVATE void sqlite3Savepoint(Parse*, int, Token*);
11131SQLITE_PRIVATE void sqlite3CloseSavepoints(sqlite3 *);
11132SQLITE_PRIVATE int sqlite3ExprIsConstant(Expr*);
11133SQLITE_PRIVATE int sqlite3ExprIsConstantNotJoin(Expr*);
11134SQLITE_PRIVATE int sqlite3ExprIsConstantOrFunction(Expr*);
11135SQLITE_PRIVATE int sqlite3ExprIsInteger(Expr*, int*);
11136SQLITE_PRIVATE int sqlite3ExprCanBeNull(const Expr*);
11137SQLITE_PRIVATE void sqlite3ExprCodeIsNullJump(Vdbe*, const Expr*, int, int);
11138SQLITE_PRIVATE int sqlite3ExprNeedsNoAffinityChange(const Expr*, char);
11139SQLITE_PRIVATE int sqlite3IsRowid(const char*);
11140SQLITE_PRIVATE void sqlite3GenerateRowDelete(Parse*, Table*, int, int, int, Trigger *, int);
11141SQLITE_PRIVATE void sqlite3GenerateRowIndexDelete(Parse*, Table*, int, int*);
11142SQLITE_PRIVATE int sqlite3GenerateIndexKey(Parse*, Index*, int, int, int);
11143SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(Parse*,Table*,int,int,
11144                                     int*,int,int,int,int,int*);
11145SQLITE_PRIVATE void sqlite3CompleteInsertion(Parse*, Table*, int, int, int*, int, int, int);
11146SQLITE_PRIVATE int sqlite3OpenTableAndIndices(Parse*, Table*, int, int);
11147SQLITE_PRIVATE void sqlite3BeginWriteOperation(Parse*, int, int);
11148SQLITE_PRIVATE void sqlite3MultiWrite(Parse*);
11149SQLITE_PRIVATE void sqlite3MayAbort(Parse*);
11150SQLITE_PRIVATE void sqlite3HaltConstraint(Parse*, int, char*, int);
11151SQLITE_PRIVATE Expr *sqlite3ExprDup(sqlite3*,Expr*,int);
11152SQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3*,ExprList*,int);
11153SQLITE_PRIVATE SrcList *sqlite3SrcListDup(sqlite3*,SrcList*,int);
11154SQLITE_PRIVATE IdList *sqlite3IdListDup(sqlite3*,IdList*);
11155SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3*,Select*,int);
11156SQLITE_PRIVATE void sqlite3FuncDefInsert(FuncDefHash*, FuncDef*);
11157SQLITE_PRIVATE FuncDef *sqlite3FindFunction(sqlite3*,const char*,int,int,u8,int);
11158SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(sqlite3*);
11159SQLITE_PRIVATE void sqlite3RegisterDateTimeFunctions(void);
11160SQLITE_PRIVATE void sqlite3RegisterGlobalFunctions(void);
11161SQLITE_PRIVATE int sqlite3SafetyCheckOk(sqlite3*);
11162SQLITE_PRIVATE int sqlite3SafetyCheckSickOrOk(sqlite3*);
11163SQLITE_PRIVATE void sqlite3ChangeCookie(Parse*, int);
11164
11165#if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
11166SQLITE_PRIVATE void sqlite3MaterializeView(Parse*, Table*, Expr*, int);
11167#endif
11168
11169#ifndef SQLITE_OMIT_TRIGGER
11170SQLITE_PRIVATE   void sqlite3BeginTrigger(Parse*, Token*,Token*,int,int,IdList*,SrcList*,
11171                           Expr*,int, int);
11172SQLITE_PRIVATE   void sqlite3FinishTrigger(Parse*, TriggerStep*, Token*);
11173SQLITE_PRIVATE   void sqlite3DropTrigger(Parse*, SrcList*, int);
11174SQLITE_PRIVATE   void sqlite3DropTriggerPtr(Parse*, Trigger*);
11175SQLITE_PRIVATE   Trigger *sqlite3TriggersExist(Parse *, Table*, int, ExprList*, int *pMask);
11176SQLITE_PRIVATE   Trigger *sqlite3TriggerList(Parse *, Table *);
11177SQLITE_PRIVATE   void sqlite3CodeRowTrigger(Parse*, Trigger *, int, ExprList*, int, Table *,
11178                            int, int, int);
11179SQLITE_PRIVATE   void sqlite3CodeRowTriggerDirect(Parse *, Trigger *, Table *, int, int, int);
11180  void sqliteViewTriggers(Parse*, Table*, Expr*, int, ExprList*);
11181SQLITE_PRIVATE   void sqlite3DeleteTriggerStep(sqlite3*, TriggerStep*);
11182SQLITE_PRIVATE   TriggerStep *sqlite3TriggerSelectStep(sqlite3*,Select*);
11183SQLITE_PRIVATE   TriggerStep *sqlite3TriggerInsertStep(sqlite3*,Token*, IdList*,
11184                                        ExprList*,Select*,u8);
11185SQLITE_PRIVATE   TriggerStep *sqlite3TriggerUpdateStep(sqlite3*,Token*,ExprList*, Expr*, u8);
11186SQLITE_PRIVATE   TriggerStep *sqlite3TriggerDeleteStep(sqlite3*,Token*, Expr*);
11187SQLITE_PRIVATE   void sqlite3DeleteTrigger(sqlite3*, Trigger*);
11188SQLITE_PRIVATE   void sqlite3UnlinkAndDeleteTrigger(sqlite3*,int,const char*);
11189SQLITE_PRIVATE   u32 sqlite3TriggerColmask(Parse*,Trigger*,ExprList*,int,int,Table*,int);
11190# define sqlite3ParseToplevel(p) ((p)->pToplevel ? (p)->pToplevel : (p))
11191#else
11192# define sqlite3TriggersExist(B,C,D,E,F) 0
11193# define sqlite3DeleteTrigger(A,B)
11194# define sqlite3DropTriggerPtr(A,B)
11195# define sqlite3UnlinkAndDeleteTrigger(A,B,C)
11196# define sqlite3CodeRowTrigger(A,B,C,D,E,F,G,H,I)
11197# define sqlite3CodeRowTriggerDirect(A,B,C,D,E,F)
11198# define sqlite3TriggerList(X, Y) 0
11199# define sqlite3ParseToplevel(p) p
11200# define sqlite3TriggerColmask(A,B,C,D,E,F,G) 0
11201#endif
11202
11203SQLITE_PRIVATE int sqlite3JoinType(Parse*, Token*, Token*, Token*);
11204SQLITE_PRIVATE void sqlite3CreateForeignKey(Parse*, ExprList*, Token*, ExprList*, int);
11205SQLITE_PRIVATE void sqlite3DeferForeignKey(Parse*, int);
11206#ifndef SQLITE_OMIT_AUTHORIZATION
11207SQLITE_PRIVATE   void sqlite3AuthRead(Parse*,Expr*,Schema*,SrcList*);
11208SQLITE_PRIVATE   int sqlite3AuthCheck(Parse*,int, const char*, const char*, const char*);
11209SQLITE_PRIVATE   void sqlite3AuthContextPush(Parse*, AuthContext*, const char*);
11210SQLITE_PRIVATE   void sqlite3AuthContextPop(AuthContext*);
11211SQLITE_PRIVATE   int sqlite3AuthReadCol(Parse*, const char *, const char *, int);
11212#else
11213# define sqlite3AuthRead(a,b,c,d)
11214# define sqlite3AuthCheck(a,b,c,d,e)    SQLITE_OK
11215# define sqlite3AuthContextPush(a,b,c)
11216# define sqlite3AuthContextPop(a)  ((void)(a))
11217#endif
11218SQLITE_PRIVATE void sqlite3Attach(Parse*, Expr*, Expr*, Expr*);
11219SQLITE_PRIVATE void sqlite3Detach(Parse*, Expr*);
11220SQLITE_PRIVATE int sqlite3FixInit(DbFixer*, Parse*, int, const char*, const Token*);
11221SQLITE_PRIVATE int sqlite3FixSrcList(DbFixer*, SrcList*);
11222SQLITE_PRIVATE int sqlite3FixSelect(DbFixer*, Select*);
11223SQLITE_PRIVATE int sqlite3FixExpr(DbFixer*, Expr*);
11224SQLITE_PRIVATE int sqlite3FixExprList(DbFixer*, ExprList*);
11225SQLITE_PRIVATE int sqlite3FixTriggerStep(DbFixer*, TriggerStep*);
11226SQLITE_PRIVATE int sqlite3AtoF(const char *z, double*, int, u8);
11227SQLITE_PRIVATE int sqlite3GetInt32(const char *, int*);
11228SQLITE_PRIVATE int sqlite3Atoi(const char*);
11229SQLITE_PRIVATE int sqlite3Utf16ByteLen(const void *pData, int nChar);
11230SQLITE_PRIVATE int sqlite3Utf8CharLen(const char *pData, int nByte);
11231SQLITE_PRIVATE int sqlite3Utf8Read(const u8*, const u8**);
11232
11233/*
11234** Routines to read and write variable-length integers.  These used to
11235** be defined locally, but now we use the varint routines in the util.c
11236** file.  Code should use the MACRO forms below, as the Varint32 versions
11237** are coded to assume the single byte case is already handled (which
11238** the MACRO form does).
11239*/
11240SQLITE_PRIVATE int sqlite3PutVarint(unsigned char*, u64);
11241SQLITE_PRIVATE int sqlite3PutVarint32(unsigned char*, u32);
11242SQLITE_PRIVATE u8 sqlite3GetVarint(const unsigned char *, u64 *);
11243SQLITE_PRIVATE u8 sqlite3GetVarint32(const unsigned char *, u32 *);
11244SQLITE_PRIVATE int sqlite3VarintLen(u64 v);
11245
11246/*
11247** The header of a record consists of a sequence variable-length integers.
11248** These integers are almost always small and are encoded as a single byte.
11249** The following macros take advantage this fact to provide a fast encode
11250** and decode of the integers in a record header.  It is faster for the common
11251** case where the integer is a single byte.  It is a little slower when the
11252** integer is two or more bytes.  But overall it is faster.
11253**
11254** The following expressions are equivalent:
11255**
11256**     x = sqlite3GetVarint32( A, &B );
11257**     x = sqlite3PutVarint32( A, B );
11258**
11259**     x = getVarint32( A, B );
11260**     x = putVarint32( A, B );
11261**
11262*/
11263#define getVarint32(A,B)  (u8)((*(A)<(u8)0x80) ? ((B) = (u32)*(A)),1 : sqlite3GetVarint32((A), (u32 *)&(B)))
11264#define putVarint32(A,B)  (u8)(((u32)(B)<(u32)0x80) ? (*(A) = (unsigned char)(B)),1 : sqlite3PutVarint32((A), (B)))
11265#define getVarint    sqlite3GetVarint
11266#define putVarint    sqlite3PutVarint
11267
11268
11269SQLITE_PRIVATE const char *sqlite3IndexAffinityStr(Vdbe *, Index *);
11270SQLITE_PRIVATE void sqlite3TableAffinityStr(Vdbe *, Table *);
11271SQLITE_PRIVATE char sqlite3CompareAffinity(Expr *pExpr, char aff2);
11272SQLITE_PRIVATE int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity);
11273SQLITE_PRIVATE char sqlite3ExprAffinity(Expr *pExpr);
11274SQLITE_PRIVATE int sqlite3Atoi64(const char*, i64*, int, u8);
11275SQLITE_PRIVATE void sqlite3Error(sqlite3*, int, const char*,...);
11276SQLITE_PRIVATE void *sqlite3HexToBlob(sqlite3*, const char *z, int n);
11277SQLITE_PRIVATE int sqlite3TwoPartName(Parse *, Token *, Token *, Token **);
11278SQLITE_PRIVATE const char *sqlite3ErrStr(int);
11279SQLITE_PRIVATE int sqlite3ReadSchema(Parse *pParse);
11280SQLITE_PRIVATE CollSeq *sqlite3FindCollSeq(sqlite3*,u8 enc, const char*,int);
11281SQLITE_PRIVATE CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char*zName);
11282SQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr);
11283SQLITE_PRIVATE Expr *sqlite3ExprSetColl(Expr*, CollSeq*);
11284SQLITE_PRIVATE Expr *sqlite3ExprSetCollByToken(Parse *pParse, Expr*, Token*);
11285SQLITE_PRIVATE int sqlite3CheckCollSeq(Parse *, CollSeq *);
11286SQLITE_PRIVATE int sqlite3CheckObjectName(Parse *, const char *);
11287SQLITE_PRIVATE void sqlite3VdbeSetChanges(sqlite3 *, int);
11288SQLITE_PRIVATE int sqlite3AddInt64(i64*,i64);
11289SQLITE_PRIVATE int sqlite3SubInt64(i64*,i64);
11290SQLITE_PRIVATE int sqlite3MulInt64(i64*,i64);
11291SQLITE_PRIVATE int sqlite3AbsInt32(int);
11292
11293SQLITE_PRIVATE const void *sqlite3ValueText(sqlite3_value*, u8);
11294SQLITE_PRIVATE int sqlite3ValueBytes(sqlite3_value*, u8);
11295SQLITE_PRIVATE void sqlite3ValueSetStr(sqlite3_value*, int, const void *,u8,
11296                        void(*)(void*));
11297SQLITE_PRIVATE void sqlite3ValueFree(sqlite3_value*);
11298SQLITE_PRIVATE sqlite3_value *sqlite3ValueNew(sqlite3 *);
11299SQLITE_PRIVATE char *sqlite3Utf16to8(sqlite3 *, const void*, int, u8);
11300#ifdef SQLITE_ENABLE_STAT2
11301SQLITE_PRIVATE char *sqlite3Utf8to16(sqlite3 *, u8, char *, int, int *);
11302#endif
11303SQLITE_PRIVATE int sqlite3ValueFromExpr(sqlite3 *, Expr *, u8, u8, sqlite3_value **);
11304SQLITE_PRIVATE void sqlite3ValueApplyAffinity(sqlite3_value *, u8, u8);
11305#ifndef SQLITE_AMALGAMATION
11306SQLITE_PRIVATE const unsigned char sqlite3OpcodeProperty[];
11307SQLITE_PRIVATE const unsigned char sqlite3UpperToLower[];
11308SQLITE_PRIVATE const unsigned char sqlite3CtypeMap[];
11309SQLITE_PRIVATE const Token sqlite3IntTokens[];
11310SQLITE_PRIVATE SQLITE_WSD struct Sqlite3Config sqlite3Config;
11311SQLITE_PRIVATE SQLITE_WSD FuncDefHash sqlite3GlobalFunctions;
11312#ifndef SQLITE_OMIT_WSD
11313SQLITE_PRIVATE int sqlite3PendingByte;
11314#endif
11315#endif
11316SQLITE_PRIVATE void sqlite3RootPageMoved(sqlite3*, int, int, int);
11317SQLITE_PRIVATE void sqlite3Reindex(Parse*, Token*, Token*);
11318SQLITE_PRIVATE void sqlite3AlterFunctions(void);
11319SQLITE_PRIVATE void sqlite3AlterRenameTable(Parse*, SrcList*, Token*);
11320SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *, int *);
11321SQLITE_PRIVATE void sqlite3NestedParse(Parse*, const char*, ...);
11322SQLITE_PRIVATE void sqlite3ExpirePreparedStatements(sqlite3*);
11323SQLITE_PRIVATE int sqlite3CodeSubselect(Parse *, Expr *, int, int);
11324SQLITE_PRIVATE void sqlite3SelectPrep(Parse*, Select*, NameContext*);
11325SQLITE_PRIVATE int sqlite3ResolveExprNames(NameContext*, Expr*);
11326SQLITE_PRIVATE void sqlite3ResolveSelectNames(Parse*, Select*, NameContext*);
11327SQLITE_PRIVATE int sqlite3ResolveOrderGroupBy(Parse*, Select*, ExprList*, const char*);
11328SQLITE_PRIVATE void sqlite3ColumnDefault(Vdbe *, Table *, int, int);
11329SQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *, Token *);
11330SQLITE_PRIVATE void sqlite3AlterBeginAddColumn(Parse *, SrcList *);
11331SQLITE_PRIVATE CollSeq *sqlite3GetCollSeq(sqlite3*, u8, CollSeq *, const char*);
11332SQLITE_PRIVATE char sqlite3AffinityType(const char*);
11333SQLITE_PRIVATE void sqlite3Analyze(Parse*, Token*, Token*);
11334SQLITE_PRIVATE int sqlite3InvokeBusyHandler(BusyHandler*);
11335SQLITE_PRIVATE int sqlite3FindDb(sqlite3*, Token*);
11336SQLITE_PRIVATE int sqlite3FindDbName(sqlite3 *, const char *);
11337SQLITE_PRIVATE int sqlite3AnalysisLoad(sqlite3*,int iDB);
11338SQLITE_PRIVATE void sqlite3DeleteIndexSamples(sqlite3*,Index*);
11339SQLITE_PRIVATE void sqlite3DefaultRowEst(Index*);
11340SQLITE_PRIVATE void sqlite3RegisterLikeFunctions(sqlite3*, int);
11341SQLITE_PRIVATE int sqlite3IsLikeFunction(sqlite3*,Expr*,int*,char*);
11342SQLITE_PRIVATE void sqlite3MinimumFileFormat(Parse*, int, int);
11343SQLITE_PRIVATE void sqlite3SchemaClear(void *);
11344SQLITE_PRIVATE Schema *sqlite3SchemaGet(sqlite3 *, Btree *);
11345SQLITE_PRIVATE int sqlite3SchemaToIndex(sqlite3 *db, Schema *);
11346SQLITE_PRIVATE KeyInfo *sqlite3IndexKeyinfo(Parse *, Index *);
11347SQLITE_PRIVATE int sqlite3CreateFunc(sqlite3 *, const char *, int, int, void *,
11348  void (*)(sqlite3_context*,int,sqlite3_value **),
11349  void (*)(sqlite3_context*,int,sqlite3_value **), void (*)(sqlite3_context*),
11350  FuncDestructor *pDestructor
11351);
11352SQLITE_PRIVATE int sqlite3ApiExit(sqlite3 *db, int);
11353SQLITE_PRIVATE int sqlite3OpenTempDatabase(Parse *);
11354
11355SQLITE_PRIVATE void sqlite3StrAccumInit(StrAccum*, char*, int, int);
11356SQLITE_PRIVATE void sqlite3StrAccumAppend(StrAccum*,const char*,int);
11357SQLITE_PRIVATE char *sqlite3StrAccumFinish(StrAccum*);
11358SQLITE_PRIVATE void sqlite3StrAccumReset(StrAccum*);
11359SQLITE_PRIVATE void sqlite3SelectDestInit(SelectDest*,int,int);
11360SQLITE_PRIVATE Expr *sqlite3CreateColumnExpr(sqlite3 *, SrcList *, int, int);
11361
11362SQLITE_PRIVATE void sqlite3BackupRestart(sqlite3_backup *);
11363SQLITE_PRIVATE void sqlite3BackupUpdate(sqlite3_backup *, Pgno, const u8 *);
11364
11365/*
11366** The interface to the LEMON-generated parser
11367*/
11368SQLITE_PRIVATE void *sqlite3ParserAlloc(void*(*)(size_t));
11369SQLITE_PRIVATE void sqlite3ParserFree(void*, void(*)(void*));
11370SQLITE_PRIVATE void sqlite3Parser(void*, int, Token, Parse*);
11371#ifdef YYTRACKMAXSTACKDEPTH
11372SQLITE_PRIVATE   int sqlite3ParserStackPeak(void*);
11373#endif
11374
11375SQLITE_PRIVATE void sqlite3AutoLoadExtensions(sqlite3*);
11376#ifndef SQLITE_OMIT_LOAD_EXTENSION
11377SQLITE_PRIVATE   void sqlite3CloseExtensions(sqlite3*);
11378#else
11379# define sqlite3CloseExtensions(X)
11380#endif
11381
11382#ifndef SQLITE_OMIT_SHARED_CACHE
11383SQLITE_PRIVATE   void sqlite3TableLock(Parse *, int, int, u8, const char *);
11384#else
11385  #define sqlite3TableLock(v,w,x,y,z)
11386#endif
11387
11388#ifdef SQLITE_TEST
11389SQLITE_PRIVATE   int sqlite3Utf8To8(unsigned char*);
11390#endif
11391
11392#ifdef SQLITE_OMIT_VIRTUALTABLE
11393#  define sqlite3VtabClear(Y)
11394#  define sqlite3VtabSync(X,Y) SQLITE_OK
11395#  define sqlite3VtabRollback(X)
11396#  define sqlite3VtabCommit(X)
11397#  define sqlite3VtabInSync(db) 0
11398#  define sqlite3VtabLock(X)
11399#  define sqlite3VtabUnlock(X)
11400#  define sqlite3VtabUnlockList(X)
11401#else
11402SQLITE_PRIVATE    void sqlite3VtabClear(sqlite3 *db, Table*);
11403SQLITE_PRIVATE    int sqlite3VtabSync(sqlite3 *db, char **);
11404SQLITE_PRIVATE    int sqlite3VtabRollback(sqlite3 *db);
11405SQLITE_PRIVATE    int sqlite3VtabCommit(sqlite3 *db);
11406SQLITE_PRIVATE    void sqlite3VtabLock(VTable *);
11407SQLITE_PRIVATE    void sqlite3VtabUnlock(VTable *);
11408SQLITE_PRIVATE    void sqlite3VtabUnlockList(sqlite3*);
11409#  define sqlite3VtabInSync(db) ((db)->nVTrans>0 && (db)->aVTrans==0)
11410#endif
11411SQLITE_PRIVATE void sqlite3VtabMakeWritable(Parse*,Table*);
11412SQLITE_PRIVATE void sqlite3VtabBeginParse(Parse*, Token*, Token*, Token*);
11413SQLITE_PRIVATE void sqlite3VtabFinishParse(Parse*, Token*);
11414SQLITE_PRIVATE void sqlite3VtabArgInit(Parse*);
11415SQLITE_PRIVATE void sqlite3VtabArgExtend(Parse*, Token*);
11416SQLITE_PRIVATE int sqlite3VtabCallCreate(sqlite3*, int, const char *, char **);
11417SQLITE_PRIVATE int sqlite3VtabCallConnect(Parse*, Table*);
11418SQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3*, int, const char *);
11419SQLITE_PRIVATE int sqlite3VtabBegin(sqlite3 *, VTable *);
11420SQLITE_PRIVATE FuncDef *sqlite3VtabOverloadFunction(sqlite3 *,FuncDef*, int nArg, Expr*);
11421SQLITE_PRIVATE void sqlite3InvalidFunction(sqlite3_context*,int,sqlite3_value**);
11422SQLITE_PRIVATE int sqlite3VdbeParameterIndex(Vdbe*, const char*, int);
11423SQLITE_PRIVATE int sqlite3TransferBindings(sqlite3_stmt *, sqlite3_stmt *);
11424SQLITE_PRIVATE int sqlite3Reprepare(Vdbe*);
11425SQLITE_PRIVATE void sqlite3ExprListCheckLength(Parse*, ExprList*, const char*);
11426SQLITE_PRIVATE CollSeq *sqlite3BinaryCompareCollSeq(Parse *, Expr *, Expr *);
11427SQLITE_PRIVATE int sqlite3TempInMemory(const sqlite3*);
11428SQLITE_PRIVATE VTable *sqlite3GetVTable(sqlite3*, Table*);
11429SQLITE_PRIVATE const char *sqlite3JournalModename(int);
11430SQLITE_PRIVATE int sqlite3Checkpoint(sqlite3*, int, int, int*, int*);
11431SQLITE_PRIVATE int sqlite3WalDefaultHook(void*,sqlite3*,const char*,int);
11432
11433/* Declarations for functions in fkey.c. All of these are replaced by
11434** no-op macros if OMIT_FOREIGN_KEY is defined. In this case no foreign
11435** key functionality is available. If OMIT_TRIGGER is defined but
11436** OMIT_FOREIGN_KEY is not, only some of the functions are no-oped. In
11437** this case foreign keys are parsed, but no other functionality is
11438** provided (enforcement of FK constraints requires the triggers sub-system).
11439*/
11440#if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
11441SQLITE_PRIVATE   void sqlite3FkCheck(Parse*, Table*, int, int);
11442SQLITE_PRIVATE   void sqlite3FkDropTable(Parse*, SrcList *, Table*);
11443SQLITE_PRIVATE   void sqlite3FkActions(Parse*, Table*, ExprList*, int);
11444SQLITE_PRIVATE   int sqlite3FkRequired(Parse*, Table*, int*, int);
11445SQLITE_PRIVATE   u32 sqlite3FkOldmask(Parse*, Table*);
11446SQLITE_PRIVATE   FKey *sqlite3FkReferences(Table *);
11447#else
11448  #define sqlite3FkActions(a,b,c,d)
11449  #define sqlite3FkCheck(a,b,c,d)
11450  #define sqlite3FkDropTable(a,b,c)
11451  #define sqlite3FkOldmask(a,b)      0
11452  #define sqlite3FkRequired(a,b,c,d) 0
11453#endif
11454#ifndef SQLITE_OMIT_FOREIGN_KEY
11455SQLITE_PRIVATE   void sqlite3FkDelete(sqlite3 *, Table*);
11456#else
11457  #define sqlite3FkDelete(a,b)
11458#endif
11459
11460
11461/*
11462** Available fault injectors.  Should be numbered beginning with 0.
11463*/
11464#define SQLITE_FAULTINJECTOR_MALLOC     0
11465#define SQLITE_FAULTINJECTOR_COUNT      1
11466
11467/*
11468** The interface to the code in fault.c used for identifying "benign"
11469** malloc failures. This is only present if SQLITE_OMIT_BUILTIN_TEST
11470** is not defined.
11471*/
11472#ifndef SQLITE_OMIT_BUILTIN_TEST
11473SQLITE_PRIVATE   void sqlite3BeginBenignMalloc(void);
11474SQLITE_PRIVATE   void sqlite3EndBenignMalloc(void);
11475#else
11476  #define sqlite3BeginBenignMalloc()
11477  #define sqlite3EndBenignMalloc()
11478#endif
11479
11480#define IN_INDEX_ROWID           1
11481#define IN_INDEX_EPH             2
11482#define IN_INDEX_INDEX           3
11483SQLITE_PRIVATE int sqlite3FindInIndex(Parse *, Expr *, int*);
11484
11485#ifdef SQLITE_ENABLE_ATOMIC_WRITE
11486SQLITE_PRIVATE   int sqlite3JournalOpen(sqlite3_vfs *, const char *, sqlite3_file *, int, int);
11487SQLITE_PRIVATE   int sqlite3JournalSize(sqlite3_vfs *);
11488SQLITE_PRIVATE   int sqlite3JournalCreate(sqlite3_file *);
11489#else
11490  #define sqlite3JournalSize(pVfs) ((pVfs)->szOsFile)
11491#endif
11492
11493SQLITE_PRIVATE void sqlite3MemJournalOpen(sqlite3_file *);
11494SQLITE_PRIVATE int sqlite3MemJournalSize(void);
11495SQLITE_PRIVATE int sqlite3IsMemJournal(sqlite3_file *);
11496
11497#if SQLITE_MAX_EXPR_DEPTH>0
11498SQLITE_PRIVATE   void sqlite3ExprSetHeight(Parse *pParse, Expr *p);
11499SQLITE_PRIVATE   int sqlite3SelectExprHeight(Select *);
11500SQLITE_PRIVATE   int sqlite3ExprCheckHeight(Parse*, int);
11501#else
11502  #define sqlite3ExprSetHeight(x,y)
11503  #define sqlite3SelectExprHeight(x) 0
11504  #define sqlite3ExprCheckHeight(x,y)
11505#endif
11506
11507SQLITE_PRIVATE u32 sqlite3Get4byte(const u8*);
11508SQLITE_PRIVATE void sqlite3Put4byte(u8*, u32);
11509
11510#ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
11511SQLITE_PRIVATE   void sqlite3ConnectionBlocked(sqlite3 *, sqlite3 *);
11512SQLITE_PRIVATE   void sqlite3ConnectionUnlocked(sqlite3 *db);
11513SQLITE_PRIVATE   void sqlite3ConnectionClosed(sqlite3 *db);
11514#else
11515  #define sqlite3ConnectionBlocked(x,y)
11516  #define sqlite3ConnectionUnlocked(x)
11517  #define sqlite3ConnectionClosed(x)
11518#endif
11519
11520#ifdef SQLITE_DEBUG
11521SQLITE_PRIVATE   void sqlite3ParserTrace(FILE*, char *);
11522#endif
11523
11524/*
11525** If the SQLITE_ENABLE IOTRACE exists then the global variable
11526** sqlite3IoTrace is a pointer to a printf-like routine used to
11527** print I/O tracing messages.
11528*/
11529#ifdef SQLITE_ENABLE_IOTRACE
11530# define IOTRACE(A)  if( sqlite3IoTrace ){ sqlite3IoTrace A; }
11531SQLITE_PRIVATE   void sqlite3VdbeIOTraceSql(Vdbe*);
11532SQLITE_PRIVATE void (*sqlite3IoTrace)(const char*,...);
11533#else
11534# define IOTRACE(A)
11535# define sqlite3VdbeIOTraceSql(X)
11536#endif
11537
11538/*
11539** These routines are available for the mem2.c debugging memory allocator
11540** only.  They are used to verify that different "types" of memory
11541** allocations are properly tracked by the system.
11542**
11543** sqlite3MemdebugSetType() sets the "type" of an allocation to one of
11544** the MEMTYPE_* macros defined below.  The type must be a bitmask with
11545** a single bit set.
11546**
11547** sqlite3MemdebugHasType() returns true if any of the bits in its second
11548** argument match the type set by the previous sqlite3MemdebugSetType().
11549** sqlite3MemdebugHasType() is intended for use inside assert() statements.
11550**
11551** sqlite3MemdebugNoType() returns true if none of the bits in its second
11552** argument match the type set by the previous sqlite3MemdebugSetType().
11553**
11554** Perhaps the most important point is the difference between MEMTYPE_HEAP
11555** and MEMTYPE_LOOKASIDE.  If an allocation is MEMTYPE_LOOKASIDE, that means
11556** it might have been allocated by lookaside, except the allocation was
11557** too large or lookaside was already full.  It is important to verify
11558** that allocations that might have been satisfied by lookaside are not
11559** passed back to non-lookaside free() routines.  Asserts such as the
11560** example above are placed on the non-lookaside free() routines to verify
11561** this constraint.
11562**
11563** All of this is no-op for a production build.  It only comes into
11564** play when the SQLITE_MEMDEBUG compile-time option is used.
11565*/
11566#ifdef SQLITE_MEMDEBUG
11567SQLITE_PRIVATE   void sqlite3MemdebugSetType(void*,u8);
11568SQLITE_PRIVATE   int sqlite3MemdebugHasType(void*,u8);
11569SQLITE_PRIVATE   int sqlite3MemdebugNoType(void*,u8);
11570#else
11571# define sqlite3MemdebugSetType(X,Y)  /* no-op */
11572# define sqlite3MemdebugHasType(X,Y)  1
11573# define sqlite3MemdebugNoType(X,Y)   1
11574#endif
11575#define MEMTYPE_HEAP       0x01  /* General heap allocations */
11576#define MEMTYPE_LOOKASIDE  0x02  /* Might have been lookaside memory */
11577#define MEMTYPE_SCRATCH    0x04  /* Scratch allocations */
11578#define MEMTYPE_PCACHE     0x08  /* Page cache allocations */
11579#define MEMTYPE_DB         0x10  /* Uses sqlite3DbMalloc, not sqlite_malloc */
11580
11581#endif /* _SQLITEINT_H_ */
11582
11583/************** End of sqliteInt.h *******************************************/
11584/************** Begin file global.c ******************************************/
11585/*
11586** 2008 June 13
11587**
11588** The author disclaims copyright to this source code.  In place of
11589** a legal notice, here is a blessing:
11590**
11591**    May you do good and not evil.
11592**    May you find forgiveness for yourself and forgive others.
11593**    May you share freely, never taking more than you give.
11594**
11595*************************************************************************
11596**
11597** This file contains definitions of global variables and contants.
11598*/
11599
11600/* An array to map all upper-case characters into their corresponding
11601** lower-case character.
11602**
11603** SQLite only considers US-ASCII (or EBCDIC) characters.  We do not
11604** handle case conversions for the UTF character set since the tables
11605** involved are nearly as big or bigger than SQLite itself.
11606*/
11607SQLITE_PRIVATE const unsigned char sqlite3UpperToLower[] = {
11608#ifdef SQLITE_ASCII
11609      0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16, 17,
11610     18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35,
11611     36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53,
11612     54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 97, 98, 99,100,101,102,103,
11613    104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,
11614    122, 91, 92, 93, 94, 95, 96, 97, 98, 99,100,101,102,103,104,105,106,107,
11615    108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,
11616    126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,
11617    144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,161,
11618    162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179,
11619    180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197,
11620    198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,213,214,215,
11621    216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231,232,233,
11622    234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,251,
11623    252,253,254,255
11624#endif
11625#ifdef SQLITE_EBCDIC
11626      0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, /* 0x */
11627     16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, /* 1x */
11628     32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, /* 2x */
11629     48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, /* 3x */
11630     64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, /* 4x */
11631     80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, /* 5x */
11632     96, 97, 66, 67, 68, 69, 70, 71, 72, 73,106,107,108,109,110,111, /* 6x */
11633    112, 81, 82, 83, 84, 85, 86, 87, 88, 89,122,123,124,125,126,127, /* 7x */
11634    128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143, /* 8x */
11635    144,145,146,147,148,149,150,151,152,153,154,155,156,157,156,159, /* 9x */
11636    160,161,162,163,164,165,166,167,168,169,170,171,140,141,142,175, /* Ax */
11637    176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191, /* Bx */
11638    192,129,130,131,132,133,134,135,136,137,202,203,204,205,206,207, /* Cx */
11639    208,145,146,147,148,149,150,151,152,153,218,219,220,221,222,223, /* Dx */
11640    224,225,162,163,164,165,166,167,168,169,232,203,204,205,206,207, /* Ex */
11641    239,240,241,242,243,244,245,246,247,248,249,219,220,221,222,255, /* Fx */
11642#endif
11643};
11644
11645/*
11646** The following 256 byte lookup table is used to support SQLites built-in
11647** equivalents to the following standard library functions:
11648**
11649**   isspace()                        0x01
11650**   isalpha()                        0x02
11651**   isdigit()                        0x04
11652**   isalnum()                        0x06
11653**   isxdigit()                       0x08
11654**   toupper()                        0x20
11655**   SQLite identifier character      0x40
11656**
11657** Bit 0x20 is set if the mapped character requires translation to upper
11658** case. i.e. if the character is a lower-case ASCII character.
11659** If x is a lower-case ASCII character, then its upper-case equivalent
11660** is (x - 0x20). Therefore toupper() can be implemented as:
11661**
11662**   (x & ~(map[x]&0x20))
11663**
11664** Standard function tolower() is implemented using the sqlite3UpperToLower[]
11665** array. tolower() is used more often than toupper() by SQLite.
11666**
11667** Bit 0x40 is set if the character non-alphanumeric and can be used in an
11668** SQLite identifier.  Identifiers are alphanumerics, "_", "$", and any
11669** non-ASCII UTF character. Hence the test for whether or not a character is
11670** part of an identifier is 0x46.
11671**
11672** SQLite's versions are identical to the standard versions assuming a
11673** locale of "C". They are implemented as macros in sqliteInt.h.
11674*/
11675#ifdef SQLITE_ASCII
11676SQLITE_PRIVATE const unsigned char sqlite3CtypeMap[256] = {
11677  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 00..07    ........ */
11678  0x00, 0x01, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00,  /* 08..0f    ........ */
11679  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 10..17    ........ */
11680  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 18..1f    ........ */
11681  0x01, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00,  /* 20..27     !"#$%&' */
11682  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 28..2f    ()*+,-./ */
11683  0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c,  /* 30..37    01234567 */
11684  0x0c, 0x0c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 38..3f    89:;<=>? */
11685
11686  0x00, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x02,  /* 40..47    @ABCDEFG */
11687  0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02,  /* 48..4f    HIJKLMNO */
11688  0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02,  /* 50..57    PQRSTUVW */
11689  0x02, 0x02, 0x02, 0x00, 0x00, 0x00, 0x00, 0x40,  /* 58..5f    XYZ[\]^_ */
11690  0x00, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x22,  /* 60..67    `abcdefg */
11691  0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22,  /* 68..6f    hijklmno */
11692  0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22,  /* 70..77    pqrstuvw */
11693  0x22, 0x22, 0x22, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 78..7f    xyz{|}~. */
11694
11695  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* 80..87    ........ */
11696  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* 88..8f    ........ */
11697  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* 90..97    ........ */
11698  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* 98..9f    ........ */
11699  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* a0..a7    ........ */
11700  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* a8..af    ........ */
11701  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* b0..b7    ........ */
11702  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* b8..bf    ........ */
11703
11704  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* c0..c7    ........ */
11705  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* c8..cf    ........ */
11706  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* d0..d7    ........ */
11707  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* d8..df    ........ */
11708  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* e0..e7    ........ */
11709  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* e8..ef    ........ */
11710  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* f0..f7    ........ */
11711  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40   /* f8..ff    ........ */
11712};
11713#endif
11714
11715
11716
11717/*
11718** The following singleton contains the global configuration for
11719** the SQLite library.
11720*/
11721SQLITE_PRIVATE SQLITE_WSD struct Sqlite3Config sqlite3Config = {
11722   SQLITE_DEFAULT_MEMSTATUS,  /* bMemstat */
11723   1,                         /* bCoreMutex */
11724   SQLITE_THREADSAFE==1,      /* bFullMutex */
11725   0x7ffffffe,                /* mxStrlen */
11726   100,                       /* szLookaside */
11727   500,                       /* nLookaside */
11728   {0,0,0,0,0,0,0,0},         /* m */
11729   {0,0,0,0,0,0,0,0,0},       /* mutex */
11730   {0,0,0,0,0,0,0,0,0,0,0},   /* pcache */
11731   (void*)0,                  /* pHeap */
11732   0,                         /* nHeap */
11733   0, 0,                      /* mnHeap, mxHeap */
11734   (void*)0,                  /* pScratch */
11735   0,                         /* szScratch */
11736   0,                         /* nScratch */
11737   (void*)0,                  /* pPage */
11738   0,                         /* szPage */
11739   0,                         /* nPage */
11740   0,                         /* mxParserStack */
11741   0,                         /* sharedCacheEnabled */
11742   /* All the rest should always be initialized to zero */
11743   0,                         /* isInit */
11744   0,                         /* inProgress */
11745   0,                         /* isMutexInit */
11746   0,                         /* isMallocInit */
11747   0,                         /* isPCacheInit */
11748   0,                         /* pInitMutex */
11749   0,                         /* nRefInitMutex */
11750   0,                         /* xLog */
11751   0,                         /* pLogArg */
11752};
11753
11754
11755/*
11756** Hash table for global functions - functions common to all
11757** database connections.  After initialization, this table is
11758** read-only.
11759*/
11760SQLITE_PRIVATE SQLITE_WSD FuncDefHash sqlite3GlobalFunctions;
11761
11762/*
11763** Constant tokens for values 0 and 1.
11764*/
11765SQLITE_PRIVATE const Token sqlite3IntTokens[] = {
11766   { "0", 1 },
11767   { "1", 1 }
11768};
11769
11770
11771/*
11772** The value of the "pending" byte must be 0x40000000 (1 byte past the
11773** 1-gibabyte boundary) in a compatible database.  SQLite never uses
11774** the database page that contains the pending byte.  It never attempts
11775** to read or write that page.  The pending byte page is set assign
11776** for use by the VFS layers as space for managing file locks.
11777**
11778** During testing, it is often desirable to move the pending byte to
11779** a different position in the file.  This allows code that has to
11780** deal with the pending byte to run on files that are much smaller
11781** than 1 GiB.  The sqlite3_test_control() interface can be used to
11782** move the pending byte.
11783**
11784** IMPORTANT:  Changing the pending byte to any value other than
11785** 0x40000000 results in an incompatible database file format!
11786** Changing the pending byte during operating results in undefined
11787** and dileterious behavior.
11788*/
11789#ifndef SQLITE_OMIT_WSD
11790SQLITE_PRIVATE int sqlite3PendingByte = 0x40000000;
11791#endif
11792
11793/*
11794** Properties of opcodes.  The OPFLG_INITIALIZER macro is
11795** created by mkopcodeh.awk during compilation.  Data is obtained
11796** from the comments following the "case OP_xxxx:" statements in
11797** the vdbe.c file.
11798*/
11799SQLITE_PRIVATE const unsigned char sqlite3OpcodeProperty[] = OPFLG_INITIALIZER;
11800
11801/************** End of global.c **********************************************/
11802/************** Begin file ctime.c *******************************************/
11803/*
11804** 2010 February 23
11805**
11806** The author disclaims copyright to this source code.  In place of
11807** a legal notice, here is a blessing:
11808**
11809**    May you do good and not evil.
11810**    May you find forgiveness for yourself and forgive others.
11811**    May you share freely, never taking more than you give.
11812**
11813*************************************************************************
11814**
11815** This file implements routines used to report what compile-time options
11816** SQLite was built with.
11817*/
11818
11819#ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
11820
11821
11822/*
11823** An array of names of all compile-time options.  This array should
11824** be sorted A-Z.
11825**
11826** This array looks large, but in a typical installation actually uses
11827** only a handful of compile-time options, so most times this array is usually
11828** rather short and uses little memory space.
11829*/
11830static const char * const azCompileOpt[] = {
11831
11832/* These macros are provided to "stringify" the value of the define
11833** for those options in which the value is meaningful. */
11834#define CTIMEOPT_VAL_(opt) #opt
11835#define CTIMEOPT_VAL(opt) CTIMEOPT_VAL_(opt)
11836
11837#ifdef SQLITE_32BIT_ROWID
11838  "32BIT_ROWID",
11839#endif
11840#ifdef SQLITE_4_BYTE_ALIGNED_MALLOC
11841  "4_BYTE_ALIGNED_MALLOC",
11842#endif
11843#ifdef SQLITE_CASE_SENSITIVE_LIKE
11844  "CASE_SENSITIVE_LIKE",
11845#endif
11846#ifdef SQLITE_CHECK_PAGES
11847  "CHECK_PAGES",
11848#endif
11849#ifdef SQLITE_COVERAGE_TEST
11850  "COVERAGE_TEST",
11851#endif
11852#ifdef SQLITE_DEBUG
11853  "DEBUG",
11854#endif
11855#ifdef SQLITE_DEFAULT_LOCKING_MODE
11856  "DEFAULT_LOCKING_MODE=" CTIMEOPT_VAL(SQLITE_DEFAULT_LOCKING_MODE),
11857#endif
11858#ifdef SQLITE_DISABLE_DIRSYNC
11859  "DISABLE_DIRSYNC",
11860#endif
11861#ifdef SQLITE_DISABLE_LFS
11862  "DISABLE_LFS",
11863#endif
11864#ifdef SQLITE_ENABLE_ATOMIC_WRITE
11865  "ENABLE_ATOMIC_WRITE",
11866#endif
11867#ifdef SQLITE_ENABLE_CEROD
11868  "ENABLE_CEROD",
11869#endif
11870#ifdef SQLITE_ENABLE_COLUMN_METADATA
11871  "ENABLE_COLUMN_METADATA",
11872#endif
11873#ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
11874  "ENABLE_EXPENSIVE_ASSERT",
11875#endif
11876#ifdef SQLITE_ENABLE_FTS1
11877  "ENABLE_FTS1",
11878#endif
11879#ifdef SQLITE_ENABLE_FTS2
11880  "ENABLE_FTS2",
11881#endif
11882#ifdef SQLITE_ENABLE_FTS3
11883  "ENABLE_FTS3",
11884#endif
11885#ifdef SQLITE_ENABLE_FTS3_PARENTHESIS
11886  "ENABLE_FTS3_PARENTHESIS",
11887#endif
11888#ifdef SQLITE_ENABLE_FTS4
11889  "ENABLE_FTS4",
11890#endif
11891#ifdef SQLITE_ENABLE_ICU
11892  "ENABLE_ICU",
11893#endif
11894#ifdef SQLITE_ENABLE_IOTRACE
11895  "ENABLE_IOTRACE",
11896#endif
11897#ifdef SQLITE_ENABLE_LOAD_EXTENSION
11898  "ENABLE_LOAD_EXTENSION",
11899#endif
11900#ifdef SQLITE_ENABLE_LOCKING_STYLE
11901  "ENABLE_LOCKING_STYLE=" CTIMEOPT_VAL(SQLITE_ENABLE_LOCKING_STYLE),
11902#endif
11903#ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
11904  "ENABLE_MEMORY_MANAGEMENT",
11905#endif
11906#ifdef SQLITE_ENABLE_MEMSYS3
11907  "ENABLE_MEMSYS3",
11908#endif
11909#ifdef SQLITE_ENABLE_MEMSYS5
11910  "ENABLE_MEMSYS5",
11911#endif
11912#ifdef SQLITE_ENABLE_OVERSIZE_CELL_CHECK
11913  "ENABLE_OVERSIZE_CELL_CHECK",
11914#endif
11915#ifdef SQLITE_ENABLE_RTREE
11916  "ENABLE_RTREE",
11917#endif
11918#ifdef SQLITE_ENABLE_STAT2
11919  "ENABLE_STAT2",
11920#endif
11921#ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
11922  "ENABLE_UNLOCK_NOTIFY",
11923#endif
11924#ifdef SQLITE_ENABLE_UPDATE_DELETE_LIMIT
11925  "ENABLE_UPDATE_DELETE_LIMIT",
11926#endif
11927#ifdef SQLITE_HAS_CODEC
11928  "HAS_CODEC",
11929#endif
11930#ifdef SQLITE_HAVE_ISNAN
11931  "HAVE_ISNAN",
11932#endif
11933#ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
11934  "HOMEGROWN_RECURSIVE_MUTEX",
11935#endif
11936#ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
11937  "IGNORE_AFP_LOCK_ERRORS",
11938#endif
11939#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
11940  "IGNORE_FLOCK_LOCK_ERRORS",
11941#endif
11942#ifdef SQLITE_INT64_TYPE
11943  "INT64_TYPE",
11944#endif
11945#ifdef SQLITE_LOCK_TRACE
11946  "LOCK_TRACE",
11947#endif
11948#ifdef SQLITE_MEMDEBUG
11949  "MEMDEBUG",
11950#endif
11951#ifdef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
11952  "MIXED_ENDIAN_64BIT_FLOAT",
11953#endif
11954#ifdef SQLITE_NO_SYNC
11955  "NO_SYNC",
11956#endif
11957#ifdef SQLITE_OMIT_ALTERTABLE
11958  "OMIT_ALTERTABLE",
11959#endif
11960#ifdef SQLITE_OMIT_ANALYZE
11961  "OMIT_ANALYZE",
11962#endif
11963#ifdef SQLITE_OMIT_ATTACH
11964  "OMIT_ATTACH",
11965#endif
11966#ifdef SQLITE_OMIT_AUTHORIZATION
11967  "OMIT_AUTHORIZATION",
11968#endif
11969#ifdef SQLITE_OMIT_AUTOINCREMENT
11970  "OMIT_AUTOINCREMENT",
11971#endif
11972#ifdef SQLITE_OMIT_AUTOINIT
11973  "OMIT_AUTOINIT",
11974#endif
11975#ifdef SQLITE_OMIT_AUTOMATIC_INDEX
11976  "OMIT_AUTOMATIC_INDEX",
11977#endif
11978#ifdef SQLITE_OMIT_AUTORESET
11979  "OMIT_AUTORESET",
11980#endif
11981#ifdef SQLITE_OMIT_AUTOVACUUM
11982  "OMIT_AUTOVACUUM",
11983#endif
11984#ifdef SQLITE_OMIT_BETWEEN_OPTIMIZATION
11985  "OMIT_BETWEEN_OPTIMIZATION",
11986#endif
11987#ifdef SQLITE_OMIT_BLOB_LITERAL
11988  "OMIT_BLOB_LITERAL",
11989#endif
11990#ifdef SQLITE_OMIT_BTREECOUNT
11991  "OMIT_BTREECOUNT",
11992#endif
11993#ifdef SQLITE_OMIT_BUILTIN_TEST
11994  "OMIT_BUILTIN_TEST",
11995#endif
11996#ifdef SQLITE_OMIT_CAST
11997  "OMIT_CAST",
11998#endif
11999#ifdef SQLITE_OMIT_CHECK
12000  "OMIT_CHECK",
12001#endif
12002/* // redundant
12003** #ifdef SQLITE_OMIT_COMPILEOPTION_DIAGS
12004**   "OMIT_COMPILEOPTION_DIAGS",
12005** #endif
12006*/
12007#ifdef SQLITE_OMIT_COMPLETE
12008  "OMIT_COMPLETE",
12009#endif
12010#ifdef SQLITE_OMIT_COMPOUND_SELECT
12011  "OMIT_COMPOUND_SELECT",
12012#endif
12013#ifdef SQLITE_OMIT_DATETIME_FUNCS
12014  "OMIT_DATETIME_FUNCS",
12015#endif
12016#ifdef SQLITE_OMIT_DECLTYPE
12017  "OMIT_DECLTYPE",
12018#endif
12019#ifdef SQLITE_OMIT_DEPRECATED
12020  "OMIT_DEPRECATED",
12021#endif
12022#ifdef SQLITE_OMIT_DISKIO
12023  "OMIT_DISKIO",
12024#endif
12025#ifdef SQLITE_OMIT_EXPLAIN
12026  "OMIT_EXPLAIN",
12027#endif
12028#ifdef SQLITE_OMIT_FLAG_PRAGMAS
12029  "OMIT_FLAG_PRAGMAS",
12030#endif
12031#ifdef SQLITE_OMIT_FLOATING_POINT
12032  "OMIT_FLOATING_POINT",
12033#endif
12034#ifdef SQLITE_OMIT_FOREIGN_KEY
12035  "OMIT_FOREIGN_KEY",
12036#endif
12037#ifdef SQLITE_OMIT_GET_TABLE
12038  "OMIT_GET_TABLE",
12039#endif
12040#ifdef SQLITE_OMIT_INCRBLOB
12041  "OMIT_INCRBLOB",
12042#endif
12043#ifdef SQLITE_OMIT_INTEGRITY_CHECK
12044  "OMIT_INTEGRITY_CHECK",
12045#endif
12046#ifdef SQLITE_OMIT_LIKE_OPTIMIZATION
12047  "OMIT_LIKE_OPTIMIZATION",
12048#endif
12049#ifdef SQLITE_OMIT_LOAD_EXTENSION
12050  "OMIT_LOAD_EXTENSION",
12051#endif
12052#ifdef SQLITE_OMIT_LOCALTIME
12053  "OMIT_LOCALTIME",
12054#endif
12055#ifdef SQLITE_OMIT_LOOKASIDE
12056  "OMIT_LOOKASIDE",
12057#endif
12058#ifdef SQLITE_OMIT_MEMORYDB
12059  "OMIT_MEMORYDB",
12060#endif
12061#ifdef SQLITE_OMIT_OR_OPTIMIZATION
12062  "OMIT_OR_OPTIMIZATION",
12063#endif
12064#ifdef SQLITE_OMIT_PAGER_PRAGMAS
12065  "OMIT_PAGER_PRAGMAS",
12066#endif
12067#ifdef SQLITE_OMIT_PRAGMA
12068  "OMIT_PRAGMA",
12069#endif
12070#ifdef SQLITE_OMIT_PROGRESS_CALLBACK
12071  "OMIT_PROGRESS_CALLBACK",
12072#endif
12073#ifdef SQLITE_OMIT_QUICKBALANCE
12074  "OMIT_QUICKBALANCE",
12075#endif
12076#ifdef SQLITE_OMIT_REINDEX
12077  "OMIT_REINDEX",
12078#endif
12079#ifdef SQLITE_OMIT_SCHEMA_PRAGMAS
12080  "OMIT_SCHEMA_PRAGMAS",
12081#endif
12082#ifdef SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS
12083  "OMIT_SCHEMA_VERSION_PRAGMAS",
12084#endif
12085#ifdef SQLITE_OMIT_SHARED_CACHE
12086  "OMIT_SHARED_CACHE",
12087#endif
12088#ifdef SQLITE_OMIT_SUBQUERY
12089  "OMIT_SUBQUERY",
12090#endif
12091#ifdef SQLITE_OMIT_TCL_VARIABLE
12092  "OMIT_TCL_VARIABLE",
12093#endif
12094#ifdef SQLITE_OMIT_TEMPDB
12095  "OMIT_TEMPDB",
12096#endif
12097#ifdef SQLITE_OMIT_TRACE
12098  "OMIT_TRACE",
12099#endif
12100#ifdef SQLITE_OMIT_TRIGGER
12101  "OMIT_TRIGGER",
12102#endif
12103#ifdef SQLITE_OMIT_TRUNCATE_OPTIMIZATION
12104  "OMIT_TRUNCATE_OPTIMIZATION",
12105#endif
12106#ifdef SQLITE_OMIT_UTF16
12107  "OMIT_UTF16",
12108#endif
12109#ifdef SQLITE_OMIT_VACUUM
12110  "OMIT_VACUUM",
12111#endif
12112#ifdef SQLITE_OMIT_VIEW
12113  "OMIT_VIEW",
12114#endif
12115#ifdef SQLITE_OMIT_VIRTUALTABLE
12116  "OMIT_VIRTUALTABLE",
12117#endif
12118#ifdef SQLITE_OMIT_WAL
12119  "OMIT_WAL",
12120#endif
12121#ifdef SQLITE_OMIT_WSD
12122  "OMIT_WSD",
12123#endif
12124#ifdef SQLITE_OMIT_XFER_OPT
12125  "OMIT_XFER_OPT",
12126#endif
12127#ifdef SQLITE_PERFORMANCE_TRACE
12128  "PERFORMANCE_TRACE",
12129#endif
12130#ifdef SQLITE_PROXY_DEBUG
12131  "PROXY_DEBUG",
12132#endif
12133#ifdef SQLITE_SECURE_DELETE
12134  "SECURE_DELETE",
12135#endif
12136#ifdef SQLITE_SMALL_STACK
12137  "SMALL_STACK",
12138#endif
12139#ifdef SQLITE_SOUNDEX
12140  "SOUNDEX",
12141#endif
12142#ifdef SQLITE_TCL
12143  "TCL",
12144#endif
12145#ifdef SQLITE_TEMP_STORE
12146  "TEMP_STORE=" CTIMEOPT_VAL(SQLITE_TEMP_STORE),
12147#endif
12148#ifdef SQLITE_TEST
12149  "TEST",
12150#endif
12151#ifdef SQLITE_THREADSAFE
12152  "THREADSAFE=" CTIMEOPT_VAL(SQLITE_THREADSAFE),
12153#endif
12154#ifdef SQLITE_USE_ALLOCA
12155  "USE_ALLOCA",
12156#endif
12157#ifdef SQLITE_ZERO_MALLOC
12158  "ZERO_MALLOC"
12159#endif
12160};
12161
12162/*
12163** Given the name of a compile-time option, return true if that option
12164** was used and false if not.
12165**
12166** The name can optionally begin with "SQLITE_" but the "SQLITE_" prefix
12167** is not required for a match.
12168*/
12169SQLITE_API int sqlite3_compileoption_used(const char *zOptName){
12170  int i, n;
12171  if( sqlite3StrNICmp(zOptName, "SQLITE_", 7)==0 ) zOptName += 7;
12172  n = sqlite3Strlen30(zOptName);
12173
12174  /* Since ArraySize(azCompileOpt) is normally in single digits, a
12175  ** linear search is adequate.  No need for a binary search. */
12176  for(i=0; i<ArraySize(azCompileOpt); i++){
12177    if(   (sqlite3StrNICmp(zOptName, azCompileOpt[i], n)==0)
12178       && ( (azCompileOpt[i][n]==0) || (azCompileOpt[i][n]=='=') ) ) return 1;
12179  }
12180  return 0;
12181}
12182
12183/*
12184** Return the N-th compile-time option string.  If N is out of range,
12185** return a NULL pointer.
12186*/
12187SQLITE_API const char *sqlite3_compileoption_get(int N){
12188  if( N>=0 && N<ArraySize(azCompileOpt) ){
12189    return azCompileOpt[N];
12190  }
12191  return 0;
12192}
12193
12194#endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
12195
12196/************** End of ctime.c ***********************************************/
12197/************** Begin file status.c ******************************************/
12198/*
12199** 2008 June 18
12200**
12201** The author disclaims copyright to this source code.  In place of
12202** a legal notice, here is a blessing:
12203**
12204**    May you do good and not evil.
12205**    May you find forgiveness for yourself and forgive others.
12206**    May you share freely, never taking more than you give.
12207**
12208*************************************************************************
12209**
12210** This module implements the sqlite3_status() interface and related
12211** functionality.
12212*/
12213/************** Include vdbeInt.h in the middle of status.c ******************/
12214/************** Begin file vdbeInt.h *****************************************/
12215/*
12216** 2003 September 6
12217**
12218** The author disclaims copyright to this source code.  In place of
12219** a legal notice, here is a blessing:
12220**
12221**    May you do good and not evil.
12222**    May you find forgiveness for yourself and forgive others.
12223**    May you share freely, never taking more than you give.
12224**
12225*************************************************************************
12226** This is the header file for information that is private to the
12227** VDBE.  This information used to all be at the top of the single
12228** source code file "vdbe.c".  When that file became too big (over
12229** 6000 lines long) it was split up into several smaller files and
12230** this header information was factored out.
12231*/
12232#ifndef _VDBEINT_H_
12233#define _VDBEINT_H_
12234
12235/*
12236** SQL is translated into a sequence of instructions to be
12237** executed by a virtual machine.  Each instruction is an instance
12238** of the following structure.
12239*/
12240typedef struct VdbeOp Op;
12241
12242/*
12243** Boolean values
12244*/
12245typedef unsigned char Bool;
12246
12247/*
12248** A cursor is a pointer into a single BTree within a database file.
12249** The cursor can seek to a BTree entry with a particular key, or
12250** loop over all entries of the Btree.  You can also insert new BTree
12251** entries or retrieve the key or data from the entry that the cursor
12252** is currently pointing to.
12253**
12254** Every cursor that the virtual machine has open is represented by an
12255** instance of the following structure.
12256*/
12257struct VdbeCursor {
12258  BtCursor *pCursor;    /* The cursor structure of the backend */
12259  Btree *pBt;           /* Separate file holding temporary table */
12260  KeyInfo *pKeyInfo;    /* Info about index keys needed by index cursors */
12261  int iDb;              /* Index of cursor database in db->aDb[] (or -1) */
12262  int pseudoTableReg;   /* Register holding pseudotable content. */
12263  int nField;           /* Number of fields in the header */
12264  Bool zeroed;          /* True if zeroed out and ready for reuse */
12265  Bool rowidIsValid;    /* True if lastRowid is valid */
12266  Bool atFirst;         /* True if pointing to first entry */
12267  Bool useRandomRowid;  /* Generate new record numbers semi-randomly */
12268  Bool nullRow;         /* True if pointing to a row with no data */
12269  Bool deferredMoveto;  /* A call to sqlite3BtreeMoveto() is needed */
12270  Bool isTable;         /* True if a table requiring integer keys */
12271  Bool isIndex;         /* True if an index containing keys only - no data */
12272  Bool isOrdered;       /* True if the underlying table is BTREE_UNORDERED */
12273  sqlite3_vtab_cursor *pVtabCursor;  /* The cursor for a virtual table */
12274  const sqlite3_module *pModule;     /* Module for cursor pVtabCursor */
12275  i64 seqCount;         /* Sequence counter */
12276  i64 movetoTarget;     /* Argument to the deferred sqlite3BtreeMoveto() */
12277  i64 lastRowid;        /* Last rowid from a Next or NextIdx operation */
12278
12279  /* Result of last sqlite3BtreeMoveto() done by an OP_NotExists or
12280  ** OP_IsUnique opcode on this cursor. */
12281  int seekResult;
12282
12283  /* Cached information about the header for the data record that the
12284  ** cursor is currently pointing to.  Only valid if cacheStatus matches
12285  ** Vdbe.cacheCtr.  Vdbe.cacheCtr will never take on the value of
12286  ** CACHE_STALE and so setting cacheStatus=CACHE_STALE guarantees that
12287  ** the cache is out of date.
12288  **
12289  ** aRow might point to (ephemeral) data for the current row, or it might
12290  ** be NULL.
12291  */
12292  u32 cacheStatus;      /* Cache is valid if this matches Vdbe.cacheCtr */
12293  int payloadSize;      /* Total number of bytes in the record */
12294  u32 *aType;           /* Type values for all entries in the record */
12295  u32 *aOffset;         /* Cached offsets to the start of each columns data */
12296  u8 *aRow;             /* Data for the current row, if all on one page */
12297};
12298typedef struct VdbeCursor VdbeCursor;
12299
12300/*
12301** When a sub-program is executed (OP_Program), a structure of this type
12302** is allocated to store the current value of the program counter, as
12303** well as the current memory cell array and various other frame specific
12304** values stored in the Vdbe struct. When the sub-program is finished,
12305** these values are copied back to the Vdbe from the VdbeFrame structure,
12306** restoring the state of the VM to as it was before the sub-program
12307** began executing.
12308**
12309** The memory for a VdbeFrame object is allocated and managed by a memory
12310** cell in the parent (calling) frame. When the memory cell is deleted or
12311** overwritten, the VdbeFrame object is not freed immediately. Instead, it
12312** is linked into the Vdbe.pDelFrame list. The contents of the Vdbe.pDelFrame
12313** list is deleted when the VM is reset in VdbeHalt(). The reason for doing
12314** this instead of deleting the VdbeFrame immediately is to avoid recursive
12315** calls to sqlite3VdbeMemRelease() when the memory cells belonging to the
12316** child frame are released.
12317**
12318** The currently executing frame is stored in Vdbe.pFrame. Vdbe.pFrame is
12319** set to NULL if the currently executing frame is the main program.
12320*/
12321typedef struct VdbeFrame VdbeFrame;
12322struct VdbeFrame {
12323  Vdbe *v;                /* VM this frame belongs to */
12324  int pc;                 /* Program Counter in parent (calling) frame */
12325  Op *aOp;                /* Program instructions for parent frame */
12326  int nOp;                /* Size of aOp array */
12327  Mem *aMem;              /* Array of memory cells for parent frame */
12328  int nMem;               /* Number of entries in aMem */
12329  VdbeCursor **apCsr;     /* Array of Vdbe cursors for parent frame */
12330  u16 nCursor;            /* Number of entries in apCsr */
12331  void *token;            /* Copy of SubProgram.token */
12332  int nChildMem;          /* Number of memory cells for child frame */
12333  int nChildCsr;          /* Number of cursors for child frame */
12334  i64 lastRowid;          /* Last insert rowid (sqlite3.lastRowid) */
12335  int nChange;            /* Statement changes (Vdbe.nChanges)     */
12336  VdbeFrame *pParent;     /* Parent of this frame, or NULL if parent is main */
12337};
12338
12339#define VdbeFrameMem(p) ((Mem *)&((u8 *)p)[ROUND8(sizeof(VdbeFrame))])
12340
12341/*
12342** A value for VdbeCursor.cacheValid that means the cache is always invalid.
12343*/
12344#define CACHE_STALE 0
12345
12346/*
12347** Internally, the vdbe manipulates nearly all SQL values as Mem
12348** structures. Each Mem struct may cache multiple representations (string,
12349** integer etc.) of the same value.
12350*/
12351struct Mem {
12352  sqlite3 *db;        /* The associated database connection */
12353  char *z;            /* String or BLOB value */
12354  double r;           /* Real value */
12355  union {
12356    i64 i;              /* Integer value used when MEM_Int is set in flags */
12357    int nZero;          /* Used when bit MEM_Zero is set in flags */
12358    FuncDef *pDef;      /* Used only when flags==MEM_Agg */
12359    RowSet *pRowSet;    /* Used only when flags==MEM_RowSet */
12360    VdbeFrame *pFrame;  /* Used when flags==MEM_Frame */
12361  } u;
12362  int n;              /* Number of characters in string value, excluding '\0' */
12363  u16 flags;          /* Some combination of MEM_Null, MEM_Str, MEM_Dyn, etc. */
12364  u8  type;           /* One of SQLITE_NULL, SQLITE_TEXT, SQLITE_INTEGER, etc */
12365  u8  enc;            /* SQLITE_UTF8, SQLITE_UTF16BE, SQLITE_UTF16LE */
12366#ifdef SQLITE_DEBUG
12367  Mem *pScopyFrom;    /* This Mem is a shallow copy of pScopyFrom */
12368  void *pFiller;      /* So that sizeof(Mem) is a multiple of 8 */
12369#endif
12370  void (*xDel)(void *);  /* If not null, call this function to delete Mem.z */
12371  char *zMalloc;      /* Dynamic buffer allocated by sqlite3_malloc() */
12372};
12373
12374/* One or more of the following flags are set to indicate the validOK
12375** representations of the value stored in the Mem struct.
12376**
12377** If the MEM_Null flag is set, then the value is an SQL NULL value.
12378** No other flags may be set in this case.
12379**
12380** If the MEM_Str flag is set then Mem.z points at a string representation.
12381** Usually this is encoded in the same unicode encoding as the main
12382** database (see below for exceptions). If the MEM_Term flag is also
12383** set, then the string is nul terminated. The MEM_Int and MEM_Real
12384** flags may coexist with the MEM_Str flag.
12385*/
12386#define MEM_Null      0x0001   /* Value is NULL */
12387#define MEM_Str       0x0002   /* Value is a string */
12388#define MEM_Int       0x0004   /* Value is an integer */
12389#define MEM_Real      0x0008   /* Value is a real number */
12390#define MEM_Blob      0x0010   /* Value is a BLOB */
12391#define MEM_RowSet    0x0020   /* Value is a RowSet object */
12392#define MEM_Frame     0x0040   /* Value is a VdbeFrame object */
12393#define MEM_Invalid   0x0080   /* Value is undefined */
12394#define MEM_TypeMask  0x00ff   /* Mask of type bits */
12395
12396/* Whenever Mem contains a valid string or blob representation, one of
12397** the following flags must be set to determine the memory management
12398** policy for Mem.z.  The MEM_Term flag tells us whether or not the
12399** string is \000 or \u0000 terminated
12400*/
12401#define MEM_Term      0x0200   /* String rep is nul terminated */
12402#define MEM_Dyn       0x0400   /* Need to call sqliteFree() on Mem.z */
12403#define MEM_Static    0x0800   /* Mem.z points to a static string */
12404#define MEM_Ephem     0x1000   /* Mem.z points to an ephemeral string */
12405#define MEM_Agg       0x2000   /* Mem.z points to an agg function context */
12406#define MEM_Zero      0x4000   /* Mem.i contains count of 0s appended to blob */
12407#ifdef SQLITE_OMIT_INCRBLOB
12408  #undef MEM_Zero
12409  #define MEM_Zero 0x0000
12410#endif
12411
12412/*
12413** Clear any existing type flags from a Mem and replace them with f
12414*/
12415#define MemSetTypeFlag(p, f) \
12416   ((p)->flags = ((p)->flags&~(MEM_TypeMask|MEM_Zero))|f)
12417
12418/*
12419** Return true if a memory cell is not marked as invalid.  This macro
12420** is for use inside assert() statements only.
12421*/
12422#ifdef SQLITE_DEBUG
12423#define memIsValid(M)  ((M)->flags & MEM_Invalid)==0
12424#endif
12425
12426
12427/* A VdbeFunc is just a FuncDef (defined in sqliteInt.h) that contains
12428** additional information about auxiliary information bound to arguments
12429** of the function.  This is used to implement the sqlite3_get_auxdata()
12430** and sqlite3_set_auxdata() APIs.  The "auxdata" is some auxiliary data
12431** that can be associated with a constant argument to a function.  This
12432** allows functions such as "regexp" to compile their constant regular
12433** expression argument once and reused the compiled code for multiple
12434** invocations.
12435*/
12436struct VdbeFunc {
12437  FuncDef *pFunc;               /* The definition of the function */
12438  int nAux;                     /* Number of entries allocated for apAux[] */
12439  struct AuxData {
12440    void *pAux;                   /* Aux data for the i-th argument */
12441    void (*xDelete)(void *);      /* Destructor for the aux data */
12442  } apAux[1];                   /* One slot for each function argument */
12443};
12444
12445/*
12446** The "context" argument for a installable function.  A pointer to an
12447** instance of this structure is the first argument to the routines used
12448** implement the SQL functions.
12449**
12450** There is a typedef for this structure in sqlite.h.  So all routines,
12451** even the public interface to SQLite, can use a pointer to this structure.
12452** But this file is the only place where the internal details of this
12453** structure are known.
12454**
12455** This structure is defined inside of vdbeInt.h because it uses substructures
12456** (Mem) which are only defined there.
12457*/
12458struct sqlite3_context {
12459  FuncDef *pFunc;       /* Pointer to function information.  MUST BE FIRST */
12460  VdbeFunc *pVdbeFunc;  /* Auxilary data, if created. */
12461  Mem s;                /* The return value is stored here */
12462  Mem *pMem;            /* Memory cell used to store aggregate context */
12463  int isError;          /* Error code returned by the function. */
12464  CollSeq *pColl;       /* Collating sequence */
12465};
12466
12467/*
12468** An instance of the virtual machine.  This structure contains the complete
12469** state of the virtual machine.
12470**
12471** The "sqlite3_stmt" structure pointer that is returned by sqlite3_prepare()
12472** is really a pointer to an instance of this structure.
12473**
12474** The Vdbe.inVtabMethod variable is set to non-zero for the duration of
12475** any virtual table method invocations made by the vdbe program. It is
12476** set to 2 for xDestroy method calls and 1 for all other methods. This
12477** variable is used for two purposes: to allow xDestroy methods to execute
12478** "DROP TABLE" statements and to prevent some nasty side effects of
12479** malloc failure when SQLite is invoked recursively by a virtual table
12480** method function.
12481*/
12482struct Vdbe {
12483  sqlite3 *db;            /* The database connection that owns this statement */
12484  Op *aOp;                /* Space to hold the virtual machine's program */
12485  Mem *aMem;              /* The memory locations */
12486  Mem **apArg;            /* Arguments to currently executing user function */
12487  Mem *aColName;          /* Column names to return */
12488  Mem *pResultSet;        /* Pointer to an array of results */
12489  int nMem;               /* Number of memory locations currently allocated */
12490  int nOp;                /* Number of instructions in the program */
12491  int nOpAlloc;           /* Number of slots allocated for aOp[] */
12492  int nLabel;             /* Number of labels used */
12493  int nLabelAlloc;        /* Number of slots allocated in aLabel[] */
12494  int *aLabel;            /* Space to hold the labels */
12495  u16 nResColumn;         /* Number of columns in one row of the result set */
12496  u16 nCursor;            /* Number of slots in apCsr[] */
12497  u32 magic;              /* Magic number for sanity checking */
12498  char *zErrMsg;          /* Error message written here */
12499  Vdbe *pPrev,*pNext;     /* Linked list of VDBEs with the same Vdbe.db */
12500  VdbeCursor **apCsr;     /* One element of this array for each open cursor */
12501  Mem *aVar;              /* Values for the OP_Variable opcode. */
12502  char **azVar;           /* Name of variables */
12503  ynVar nVar;             /* Number of entries in aVar[] */
12504  u32 cacheCtr;           /* VdbeCursor row cache generation counter */
12505  int pc;                 /* The program counter */
12506  int rc;                 /* Value to return */
12507  u8 errorAction;         /* Recovery action to do in case of an error */
12508  u8 okVar;               /* True if azVar[] has been initialized */
12509  u8 explain;             /* True if EXPLAIN present on SQL command */
12510  u8 changeCntOn;         /* True to update the change-counter */
12511  u8 expired;             /* True if the VM needs to be recompiled */
12512  u8 runOnlyOnce;         /* Automatically expire on reset */
12513  u8 minWriteFileFormat;  /* Minimum file format for writable database files */
12514  u8 inVtabMethod;        /* See comments above */
12515  u8 usesStmtJournal;     /* True if uses a statement journal */
12516  u8 readOnly;            /* True for read-only statements */
12517  u8 isPrepareV2;         /* True if prepared with prepare_v2() */
12518  int nChange;            /* Number of db changes made since last reset */
12519  yDbMask btreeMask;      /* Bitmask of db->aDb[] entries referenced */
12520  yDbMask lockMask;       /* Subset of btreeMask that requires a lock */
12521  int iStatement;         /* Statement number (or 0 if has not opened stmt) */
12522  int aCounter[3];        /* Counters used by sqlite3_stmt_status() */
12523#ifndef SQLITE_OMIT_TRACE
12524  i64 startTime;          /* Time when query started - used for profiling */
12525#endif
12526  i64 nFkConstraint;      /* Number of imm. FK constraints this VM */
12527  i64 nStmtDefCons;       /* Number of def. constraints when stmt started */
12528  char *zSql;             /* Text of the SQL statement that generated this */
12529  void *pFree;            /* Free this when deleting the vdbe */
12530#ifdef SQLITE_DEBUG
12531  FILE *trace;            /* Write an execution trace here, if not NULL */
12532#endif
12533  VdbeFrame *pFrame;      /* Parent frame */
12534  VdbeFrame *pDelFrame;   /* List of frame objects to free on VM reset */
12535  int nFrame;             /* Number of frames in pFrame list */
12536  u32 expmask;            /* Binding to these vars invalidates VM */
12537  SubProgram *pProgram;   /* Linked list of all sub-programs used by VM */
12538};
12539
12540/*
12541** The following are allowed values for Vdbe.magic
12542*/
12543#define VDBE_MAGIC_INIT     0x26bceaa5    /* Building a VDBE program */
12544#define VDBE_MAGIC_RUN      0xbdf20da3    /* VDBE is ready to execute */
12545#define VDBE_MAGIC_HALT     0x519c2973    /* VDBE has completed execution */
12546#define VDBE_MAGIC_DEAD     0xb606c3c8    /* The VDBE has been deallocated */
12547
12548/*
12549** Function prototypes
12550*/
12551SQLITE_PRIVATE void sqlite3VdbeFreeCursor(Vdbe *, VdbeCursor*);
12552void sqliteVdbePopStack(Vdbe*,int);
12553SQLITE_PRIVATE int sqlite3VdbeCursorMoveto(VdbeCursor*);
12554#if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
12555SQLITE_PRIVATE void sqlite3VdbePrintOp(FILE*, int, Op*);
12556#endif
12557SQLITE_PRIVATE u32 sqlite3VdbeSerialTypeLen(u32);
12558SQLITE_PRIVATE u32 sqlite3VdbeSerialType(Mem*, int);
12559SQLITE_PRIVATE u32 sqlite3VdbeSerialPut(unsigned char*, int, Mem*, int);
12560SQLITE_PRIVATE u32 sqlite3VdbeSerialGet(const unsigned char*, u32, Mem*);
12561SQLITE_PRIVATE void sqlite3VdbeDeleteAuxData(VdbeFunc*, int);
12562
12563int sqlite2BtreeKeyCompare(BtCursor *, const void *, int, int, int *);
12564SQLITE_PRIVATE int sqlite3VdbeIdxKeyCompare(VdbeCursor*,UnpackedRecord*,int*);
12565SQLITE_PRIVATE int sqlite3VdbeIdxRowid(sqlite3*, BtCursor *, i64 *);
12566SQLITE_PRIVATE int sqlite3MemCompare(const Mem*, const Mem*, const CollSeq*);
12567SQLITE_PRIVATE int sqlite3VdbeExec(Vdbe*);
12568SQLITE_PRIVATE int sqlite3VdbeList(Vdbe*);
12569SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe*);
12570SQLITE_PRIVATE int sqlite3VdbeChangeEncoding(Mem *, int);
12571SQLITE_PRIVATE int sqlite3VdbeMemTooBig(Mem*);
12572SQLITE_PRIVATE int sqlite3VdbeMemCopy(Mem*, const Mem*);
12573SQLITE_PRIVATE void sqlite3VdbeMemShallowCopy(Mem*, const Mem*, int);
12574SQLITE_PRIVATE void sqlite3VdbeMemMove(Mem*, Mem*);
12575SQLITE_PRIVATE int sqlite3VdbeMemNulTerminate(Mem*);
12576SQLITE_PRIVATE int sqlite3VdbeMemSetStr(Mem*, const char*, int, u8, void(*)(void*));
12577SQLITE_PRIVATE void sqlite3VdbeMemSetInt64(Mem*, i64);
12578#ifdef SQLITE_OMIT_FLOATING_POINT
12579# define sqlite3VdbeMemSetDouble sqlite3VdbeMemSetInt64
12580#else
12581SQLITE_PRIVATE   void sqlite3VdbeMemSetDouble(Mem*, double);
12582#endif
12583SQLITE_PRIVATE void sqlite3VdbeMemSetNull(Mem*);
12584SQLITE_PRIVATE void sqlite3VdbeMemSetZeroBlob(Mem*,int);
12585SQLITE_PRIVATE void sqlite3VdbeMemSetRowSet(Mem*);
12586SQLITE_PRIVATE int sqlite3VdbeMemMakeWriteable(Mem*);
12587SQLITE_PRIVATE int sqlite3VdbeMemStringify(Mem*, int);
12588SQLITE_PRIVATE i64 sqlite3VdbeIntValue(Mem*);
12589SQLITE_PRIVATE int sqlite3VdbeMemIntegerify(Mem*);
12590SQLITE_PRIVATE double sqlite3VdbeRealValue(Mem*);
12591SQLITE_PRIVATE void sqlite3VdbeIntegerAffinity(Mem*);
12592SQLITE_PRIVATE int sqlite3VdbeMemRealify(Mem*);
12593SQLITE_PRIVATE int sqlite3VdbeMemNumerify(Mem*);
12594SQLITE_PRIVATE int sqlite3VdbeMemFromBtree(BtCursor*,int,int,int,Mem*);
12595SQLITE_PRIVATE void sqlite3VdbeMemRelease(Mem *p);
12596SQLITE_PRIVATE void sqlite3VdbeMemReleaseExternal(Mem *p);
12597SQLITE_PRIVATE int sqlite3VdbeMemFinalize(Mem*, FuncDef*);
12598SQLITE_PRIVATE const char *sqlite3OpcodeName(int);
12599SQLITE_PRIVATE int sqlite3VdbeMemGrow(Mem *pMem, int n, int preserve);
12600SQLITE_PRIVATE int sqlite3VdbeCloseStatement(Vdbe *, int);
12601SQLITE_PRIVATE void sqlite3VdbeFrameDelete(VdbeFrame*);
12602SQLITE_PRIVATE int sqlite3VdbeFrameRestore(VdbeFrame *);
12603SQLITE_PRIVATE void sqlite3VdbeMemStoreType(Mem *pMem);
12604
12605#if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0
12606SQLITE_PRIVATE   void sqlite3VdbeEnter(Vdbe*);
12607SQLITE_PRIVATE   void sqlite3VdbeLeave(Vdbe*);
12608#else
12609# define sqlite3VdbeEnter(X)
12610# define sqlite3VdbeLeave(X)
12611#endif
12612
12613#ifdef SQLITE_DEBUG
12614SQLITE_PRIVATE void sqlite3VdbeMemPrepareToChange(Vdbe*,Mem*);
12615#endif
12616
12617#ifndef SQLITE_OMIT_FOREIGN_KEY
12618SQLITE_PRIVATE int sqlite3VdbeCheckFk(Vdbe *, int);
12619#else
12620# define sqlite3VdbeCheckFk(p,i) 0
12621#endif
12622
12623SQLITE_PRIVATE int sqlite3VdbeMemTranslate(Mem*, u8);
12624#ifdef SQLITE_DEBUG
12625SQLITE_PRIVATE   void sqlite3VdbePrintSql(Vdbe*);
12626SQLITE_PRIVATE   void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf);
12627#endif
12628SQLITE_PRIVATE int sqlite3VdbeMemHandleBom(Mem *pMem);
12629
12630#ifndef SQLITE_OMIT_INCRBLOB
12631SQLITE_PRIVATE   int sqlite3VdbeMemExpandBlob(Mem *);
12632#else
12633  #define sqlite3VdbeMemExpandBlob(x) SQLITE_OK
12634#endif
12635
12636#endif /* !defined(_VDBEINT_H_) */
12637
12638/************** End of vdbeInt.h *********************************************/
12639/************** Continuing where we left off in status.c *********************/
12640
12641/*
12642** Variables in which to record status information.
12643*/
12644typedef struct sqlite3StatType sqlite3StatType;
12645static SQLITE_WSD struct sqlite3StatType {
12646  int nowValue[10];         /* Current value */
12647  int mxValue[10];          /* Maximum value */
12648} sqlite3Stat = { {0,}, {0,} };
12649
12650
12651/* The "wsdStat" macro will resolve to the status information
12652** state vector.  If writable static data is unsupported on the target,
12653** we have to locate the state vector at run-time.  In the more common
12654** case where writable static data is supported, wsdStat can refer directly
12655** to the "sqlite3Stat" state vector declared above.
12656*/
12657#ifdef SQLITE_OMIT_WSD
12658# define wsdStatInit  sqlite3StatType *x = &GLOBAL(sqlite3StatType,sqlite3Stat)
12659# define wsdStat x[0]
12660#else
12661# define wsdStatInit
12662# define wsdStat sqlite3Stat
12663#endif
12664
12665/*
12666** Return the current value of a status parameter.
12667*/
12668SQLITE_PRIVATE int sqlite3StatusValue(int op){
12669  wsdStatInit;
12670  assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
12671  return wsdStat.nowValue[op];
12672}
12673
12674/*
12675** Add N to the value of a status record.  It is assumed that the
12676** caller holds appropriate locks.
12677*/
12678SQLITE_PRIVATE void sqlite3StatusAdd(int op, int N){
12679  wsdStatInit;
12680  assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
12681  wsdStat.nowValue[op] += N;
12682  if( wsdStat.nowValue[op]>wsdStat.mxValue[op] ){
12683    wsdStat.mxValue[op] = wsdStat.nowValue[op];
12684  }
12685}
12686
12687/*
12688** Set the value of a status to X.
12689*/
12690SQLITE_PRIVATE void sqlite3StatusSet(int op, int X){
12691  wsdStatInit;
12692  assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
12693  wsdStat.nowValue[op] = X;
12694  if( wsdStat.nowValue[op]>wsdStat.mxValue[op] ){
12695    wsdStat.mxValue[op] = wsdStat.nowValue[op];
12696  }
12697}
12698
12699/*
12700** Query status information.
12701**
12702** This implementation assumes that reading or writing an aligned
12703** 32-bit integer is an atomic operation.  If that assumption is not true,
12704** then this routine is not threadsafe.
12705*/
12706SQLITE_API int sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag){
12707  wsdStatInit;
12708  if( op<0 || op>=ArraySize(wsdStat.nowValue) ){
12709    return SQLITE_MISUSE_BKPT;
12710  }
12711  *pCurrent = wsdStat.nowValue[op];
12712  *pHighwater = wsdStat.mxValue[op];
12713  if( resetFlag ){
12714    wsdStat.mxValue[op] = wsdStat.nowValue[op];
12715  }
12716  return SQLITE_OK;
12717}
12718
12719/*
12720** Query status information for a single database connection
12721*/
12722SQLITE_API int sqlite3_db_status(
12723  sqlite3 *db,          /* The database connection whose status is desired */
12724  int op,               /* Status verb */
12725  int *pCurrent,        /* Write current value here */
12726  int *pHighwater,      /* Write high-water mark here */
12727  int resetFlag         /* Reset high-water mark if true */
12728){
12729  int rc = SQLITE_OK;   /* Return code */
12730  sqlite3_mutex_enter(db->mutex);
12731  switch( op ){
12732    case SQLITE_DBSTATUS_LOOKASIDE_USED: {
12733      *pCurrent = db->lookaside.nOut;
12734      *pHighwater = db->lookaside.mxOut;
12735      if( resetFlag ){
12736        db->lookaside.mxOut = db->lookaside.nOut;
12737      }
12738      break;
12739    }
12740
12741    case SQLITE_DBSTATUS_LOOKASIDE_HIT:
12742    case SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE:
12743    case SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL: {
12744      testcase( op==SQLITE_DBSTATUS_LOOKASIDE_HIT );
12745      testcase( op==SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE );
12746      testcase( op==SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL );
12747      assert( (op-SQLITE_DBSTATUS_LOOKASIDE_HIT)>=0 );
12748      assert( (op-SQLITE_DBSTATUS_LOOKASIDE_HIT)<3 );
12749      *pCurrent = 0;
12750      *pHighwater = db->lookaside.anStat[op - SQLITE_DBSTATUS_LOOKASIDE_HIT];
12751      if( resetFlag ){
12752        db->lookaside.anStat[op - SQLITE_DBSTATUS_LOOKASIDE_HIT] = 0;
12753      }
12754      break;
12755    }
12756
12757    /*
12758    ** Return an approximation for the amount of memory currently used
12759    ** by all pagers associated with the given database connection.  The
12760    ** highwater mark is meaningless and is returned as zero.
12761    */
12762    case SQLITE_DBSTATUS_CACHE_USED: {
12763      int totalUsed = 0;
12764      int i;
12765      sqlite3BtreeEnterAll(db);
12766      for(i=0; i<db->nDb; i++){
12767        Btree *pBt = db->aDb[i].pBt;
12768        if( pBt ){
12769          Pager *pPager = sqlite3BtreePager(pBt);
12770          totalUsed += sqlite3PagerMemUsed(pPager);
12771        }
12772      }
12773      sqlite3BtreeLeaveAll(db);
12774      *pCurrent = totalUsed;
12775      *pHighwater = 0;
12776      break;
12777    }
12778
12779    /*
12780    ** *pCurrent gets an accurate estimate of the amount of memory used
12781    ** to store the schema for all databases (main, temp, and any ATTACHed
12782    ** databases.  *pHighwater is set to zero.
12783    */
12784    case SQLITE_DBSTATUS_SCHEMA_USED: {
12785      int i;                      /* Used to iterate through schemas */
12786      int nByte = 0;              /* Used to accumulate return value */
12787
12788      sqlite3BtreeEnterAll(db);
12789      db->pnBytesFreed = &nByte;
12790      for(i=0; i<db->nDb; i++){
12791        Schema *pSchema = db->aDb[i].pSchema;
12792        if( ALWAYS(pSchema!=0) ){
12793          HashElem *p;
12794
12795          nByte += sqlite3GlobalConfig.m.xRoundup(sizeof(HashElem)) * (
12796              pSchema->tblHash.count
12797            + pSchema->trigHash.count
12798            + pSchema->idxHash.count
12799            + pSchema->fkeyHash.count
12800          );
12801          nByte += sqlite3MallocSize(pSchema->tblHash.ht);
12802          nByte += sqlite3MallocSize(pSchema->trigHash.ht);
12803          nByte += sqlite3MallocSize(pSchema->idxHash.ht);
12804          nByte += sqlite3MallocSize(pSchema->fkeyHash.ht);
12805
12806          for(p=sqliteHashFirst(&pSchema->trigHash); p; p=sqliteHashNext(p)){
12807            sqlite3DeleteTrigger(db, (Trigger*)sqliteHashData(p));
12808          }
12809          for(p=sqliteHashFirst(&pSchema->tblHash); p; p=sqliteHashNext(p)){
12810            sqlite3DeleteTable(db, (Table *)sqliteHashData(p));
12811          }
12812        }
12813      }
12814      db->pnBytesFreed = 0;
12815      sqlite3BtreeLeaveAll(db);
12816
12817      *pHighwater = 0;
12818      *pCurrent = nByte;
12819      break;
12820    }
12821
12822    /*
12823    ** *pCurrent gets an accurate estimate of the amount of memory used
12824    ** to store all prepared statements.
12825    ** *pHighwater is set to zero.
12826    */
12827    case SQLITE_DBSTATUS_STMT_USED: {
12828      struct Vdbe *pVdbe;         /* Used to iterate through VMs */
12829      int nByte = 0;              /* Used to accumulate return value */
12830
12831      db->pnBytesFreed = &nByte;
12832      for(pVdbe=db->pVdbe; pVdbe; pVdbe=pVdbe->pNext){
12833        sqlite3VdbeDeleteObject(db, pVdbe);
12834      }
12835      db->pnBytesFreed = 0;
12836
12837      *pHighwater = 0;
12838      *pCurrent = nByte;
12839
12840      break;
12841    }
12842
12843    default: {
12844      rc = SQLITE_ERROR;
12845    }
12846  }
12847  sqlite3_mutex_leave(db->mutex);
12848  return rc;
12849}
12850
12851/************** End of status.c **********************************************/
12852/************** Begin file date.c ********************************************/
12853/*
12854** 2003 October 31
12855**
12856** The author disclaims copyright to this source code.  In place of
12857** a legal notice, here is a blessing:
12858**
12859**    May you do good and not evil.
12860**    May you find forgiveness for yourself and forgive others.
12861**    May you share freely, never taking more than you give.
12862**
12863*************************************************************************
12864** This file contains the C functions that implement date and time
12865** functions for SQLite.
12866**
12867** There is only one exported symbol in this file - the function
12868** sqlite3RegisterDateTimeFunctions() found at the bottom of the file.
12869** All other code has file scope.
12870**
12871** SQLite processes all times and dates as Julian Day numbers.  The
12872** dates and times are stored as the number of days since noon
12873** in Greenwich on November 24, 4714 B.C. according to the Gregorian
12874** calendar system.
12875**
12876** 1970-01-01 00:00:00 is JD 2440587.5
12877** 2000-01-01 00:00:00 is JD 2451544.5
12878**
12879** This implemention requires years to be expressed as a 4-digit number
12880** which means that only dates between 0000-01-01 and 9999-12-31 can
12881** be represented, even though julian day numbers allow a much wider
12882** range of dates.
12883**
12884** The Gregorian calendar system is used for all dates and times,
12885** even those that predate the Gregorian calendar.  Historians usually
12886** use the Julian calendar for dates prior to 1582-10-15 and for some
12887** dates afterwards, depending on locale.  Beware of this difference.
12888**
12889** The conversion algorithms are implemented based on descriptions
12890** in the following text:
12891**
12892**      Jean Meeus
12893**      Astronomical Algorithms, 2nd Edition, 1998
12894**      ISBM 0-943396-61-1
12895**      Willmann-Bell, Inc
12896**      Richmond, Virginia (USA)
12897*/
12898#include <time.h>
12899
12900#ifndef SQLITE_OMIT_DATETIME_FUNCS
12901
12902/*
12903** On recent Windows platforms, the localtime_s() function is available
12904** as part of the "Secure CRT". It is essentially equivalent to
12905** localtime_r() available under most POSIX platforms, except that the
12906** order of the parameters is reversed.
12907**
12908** See http://msdn.microsoft.com/en-us/library/a442x3ye(VS.80).aspx.
12909**
12910** If the user has not indicated to use localtime_r() or localtime_s()
12911** already, check for an MSVC build environment that provides
12912** localtime_s().
12913*/
12914#if !defined(HAVE_LOCALTIME_R) && !defined(HAVE_LOCALTIME_S) && \
12915     defined(_MSC_VER) && defined(_CRT_INSECURE_DEPRECATE)
12916#define HAVE_LOCALTIME_S 1
12917#endif
12918
12919/*
12920** A structure for holding a single date and time.
12921*/
12922typedef struct DateTime DateTime;
12923struct DateTime {
12924  sqlite3_int64 iJD; /* The julian day number times 86400000 */
12925  int Y, M, D;       /* Year, month, and day */
12926  int h, m;          /* Hour and minutes */
12927  int tz;            /* Timezone offset in minutes */
12928  double s;          /* Seconds */
12929  char validYMD;     /* True (1) if Y,M,D are valid */
12930  char validHMS;     /* True (1) if h,m,s are valid */
12931  char validJD;      /* True (1) if iJD is valid */
12932  char validTZ;      /* True (1) if tz is valid */
12933};
12934
12935
12936/*
12937** Convert zDate into one or more integers.  Additional arguments
12938** come in groups of 5 as follows:
12939**
12940**       N       number of digits in the integer
12941**       min     minimum allowed value of the integer
12942**       max     maximum allowed value of the integer
12943**       nextC   first character after the integer
12944**       pVal    where to write the integers value.
12945**
12946** Conversions continue until one with nextC==0 is encountered.
12947** The function returns the number of successful conversions.
12948*/
12949static int getDigits(const char *zDate, ...){
12950  va_list ap;
12951  int val;
12952  int N;
12953  int min;
12954  int max;
12955  int nextC;
12956  int *pVal;
12957  int cnt = 0;
12958  va_start(ap, zDate);
12959  do{
12960    N = va_arg(ap, int);
12961    min = va_arg(ap, int);
12962    max = va_arg(ap, int);
12963    nextC = va_arg(ap, int);
12964    pVal = va_arg(ap, int*);
12965    val = 0;
12966    while( N-- ){
12967      if( !sqlite3Isdigit(*zDate) ){
12968        goto end_getDigits;
12969      }
12970      val = val*10 + *zDate - '0';
12971      zDate++;
12972    }
12973    if( val<min || val>max || (nextC!=0 && nextC!=*zDate) ){
12974      goto end_getDigits;
12975    }
12976    *pVal = val;
12977    zDate++;
12978    cnt++;
12979  }while( nextC );
12980end_getDigits:
12981  va_end(ap);
12982  return cnt;
12983}
12984
12985/*
12986** Parse a timezone extension on the end of a date-time.
12987** The extension is of the form:
12988**
12989**        (+/-)HH:MM
12990**
12991** Or the "zulu" notation:
12992**
12993**        Z
12994**
12995** If the parse is successful, write the number of minutes
12996** of change in p->tz and return 0.  If a parser error occurs,
12997** return non-zero.
12998**
12999** A missing specifier is not considered an error.
13000*/
13001static int parseTimezone(const char *zDate, DateTime *p){
13002  int sgn = 0;
13003  int nHr, nMn;
13004  int c;
13005  while( sqlite3Isspace(*zDate) ){ zDate++; }
13006  p->tz = 0;
13007  c = *zDate;
13008  if( c=='-' ){
13009    sgn = -1;
13010  }else if( c=='+' ){
13011    sgn = +1;
13012  }else if( c=='Z' || c=='z' ){
13013    zDate++;
13014    goto zulu_time;
13015  }else{
13016    return c!=0;
13017  }
13018  zDate++;
13019  if( getDigits(zDate, 2, 0, 14, ':', &nHr, 2, 0, 59, 0, &nMn)!=2 ){
13020    return 1;
13021  }
13022  zDate += 5;
13023  p->tz = sgn*(nMn + nHr*60);
13024zulu_time:
13025  while( sqlite3Isspace(*zDate) ){ zDate++; }
13026  return *zDate!=0;
13027}
13028
13029/*
13030** Parse times of the form HH:MM or HH:MM:SS or HH:MM:SS.FFFF.
13031** The HH, MM, and SS must each be exactly 2 digits.  The
13032** fractional seconds FFFF can be one or more digits.
13033**
13034** Return 1 if there is a parsing error and 0 on success.
13035*/
13036static int parseHhMmSs(const char *zDate, DateTime *p){
13037  int h, m, s;
13038  double ms = 0.0;
13039  if( getDigits(zDate, 2, 0, 24, ':', &h, 2, 0, 59, 0, &m)!=2 ){
13040    return 1;
13041  }
13042  zDate += 5;
13043  if( *zDate==':' ){
13044    zDate++;
13045    if( getDigits(zDate, 2, 0, 59, 0, &s)!=1 ){
13046      return 1;
13047    }
13048    zDate += 2;
13049    if( *zDate=='.' && sqlite3Isdigit(zDate[1]) ){
13050      double rScale = 1.0;
13051      zDate++;
13052      while( sqlite3Isdigit(*zDate) ){
13053        ms = ms*10.0 + *zDate - '0';
13054        rScale *= 10.0;
13055        zDate++;
13056      }
13057      ms /= rScale;
13058    }
13059  }else{
13060    s = 0;
13061  }
13062  p->validJD = 0;
13063  p->validHMS = 1;
13064  p->h = h;
13065  p->m = m;
13066  p->s = s + ms;
13067  if( parseTimezone(zDate, p) ) return 1;
13068  p->validTZ = (p->tz!=0)?1:0;
13069  return 0;
13070}
13071
13072/*
13073** Convert from YYYY-MM-DD HH:MM:SS to julian day.  We always assume
13074** that the YYYY-MM-DD is according to the Gregorian calendar.
13075**
13076** Reference:  Meeus page 61
13077*/
13078static void computeJD(DateTime *p){
13079  int Y, M, D, A, B, X1, X2;
13080
13081  if( p->validJD ) return;
13082  if( p->validYMD ){
13083    Y = p->Y;
13084    M = p->M;
13085    D = p->D;
13086  }else{
13087    Y = 2000;  /* If no YMD specified, assume 2000-Jan-01 */
13088    M = 1;
13089    D = 1;
13090  }
13091  if( M<=2 ){
13092    Y--;
13093    M += 12;
13094  }
13095  A = Y/100;
13096  B = 2 - A + (A/4);
13097  X1 = 36525*(Y+4716)/100;
13098  X2 = 306001*(M+1)/10000;
13099  p->iJD = (sqlite3_int64)((X1 + X2 + D + B - 1524.5 ) * 86400000);
13100  p->validJD = 1;
13101  if( p->validHMS ){
13102    p->iJD += p->h*3600000 + p->m*60000 + (sqlite3_int64)(p->s*1000);
13103    if( p->validTZ ){
13104      p->iJD -= p->tz*60000;
13105      p->validYMD = 0;
13106      p->validHMS = 0;
13107      p->validTZ = 0;
13108    }
13109  }
13110}
13111
13112/*
13113** Parse dates of the form
13114**
13115**     YYYY-MM-DD HH:MM:SS.FFF
13116**     YYYY-MM-DD HH:MM:SS
13117**     YYYY-MM-DD HH:MM
13118**     YYYY-MM-DD
13119**
13120** Write the result into the DateTime structure and return 0
13121** on success and 1 if the input string is not a well-formed
13122** date.
13123*/
13124static int parseYyyyMmDd(const char *zDate, DateTime *p){
13125  int Y, M, D, neg;
13126
13127  if( zDate[0]=='-' ){
13128    zDate++;
13129    neg = 1;
13130  }else{
13131    neg = 0;
13132  }
13133  if( getDigits(zDate,4,0,9999,'-',&Y,2,1,12,'-',&M,2,1,31,0,&D)!=3 ){
13134    return 1;
13135  }
13136  zDate += 10;
13137  while( sqlite3Isspace(*zDate) || 'T'==*(u8*)zDate ){ zDate++; }
13138  if( parseHhMmSs(zDate, p)==0 ){
13139    /* We got the time */
13140  }else if( *zDate==0 ){
13141    p->validHMS = 0;
13142  }else{
13143    return 1;
13144  }
13145  p->validJD = 0;
13146  p->validYMD = 1;
13147  p->Y = neg ? -Y : Y;
13148  p->M = M;
13149  p->D = D;
13150  if( p->validTZ ){
13151    computeJD(p);
13152  }
13153  return 0;
13154}
13155
13156/*
13157** Set the time to the current time reported by the VFS
13158*/
13159static void setDateTimeToCurrent(sqlite3_context *context, DateTime *p){
13160  sqlite3 *db = sqlite3_context_db_handle(context);
13161  sqlite3OsCurrentTimeInt64(db->pVfs, &p->iJD);
13162  p->validJD = 1;
13163}
13164
13165/*
13166** Attempt to parse the given string into a Julian Day Number.  Return
13167** the number of errors.
13168**
13169** The following are acceptable forms for the input string:
13170**
13171**      YYYY-MM-DD HH:MM:SS.FFF  +/-HH:MM
13172**      DDDD.DD
13173**      now
13174**
13175** In the first form, the +/-HH:MM is always optional.  The fractional
13176** seconds extension (the ".FFF") is optional.  The seconds portion
13177** (":SS.FFF") is option.  The year and date can be omitted as long
13178** as there is a time string.  The time string can be omitted as long
13179** as there is a year and date.
13180*/
13181static int parseDateOrTime(
13182  sqlite3_context *context,
13183  const char *zDate,
13184  DateTime *p
13185){
13186  double r;
13187  if( parseYyyyMmDd(zDate,p)==0 ){
13188    return 0;
13189  }else if( parseHhMmSs(zDate, p)==0 ){
13190    return 0;
13191  }else if( sqlite3StrICmp(zDate,"now")==0){
13192    setDateTimeToCurrent(context, p);
13193    return 0;
13194  }else if( sqlite3AtoF(zDate, &r, sqlite3Strlen30(zDate), SQLITE_UTF8) ){
13195    p->iJD = (sqlite3_int64)(r*86400000.0 + 0.5);
13196    p->validJD = 1;
13197    return 0;
13198  }
13199  return 1;
13200}
13201
13202/*
13203** Compute the Year, Month, and Day from the julian day number.
13204*/
13205static void computeYMD(DateTime *p){
13206  int Z, A, B, C, D, E, X1;
13207  if( p->validYMD ) return;
13208  if( !p->validJD ){
13209    p->Y = 2000;
13210    p->M = 1;
13211    p->D = 1;
13212  }else{
13213    Z = (int)((p->iJD + 43200000)/86400000);
13214    A = (int)((Z - 1867216.25)/36524.25);
13215    A = Z + 1 + A - (A/4);
13216    B = A + 1524;
13217    C = (int)((B - 122.1)/365.25);
13218    D = (36525*C)/100;
13219    E = (int)((B-D)/30.6001);
13220    X1 = (int)(30.6001*E);
13221    p->D = B - D - X1;
13222    p->M = E<14 ? E-1 : E-13;
13223    p->Y = p->M>2 ? C - 4716 : C - 4715;
13224  }
13225  p->validYMD = 1;
13226}
13227
13228/*
13229** Compute the Hour, Minute, and Seconds from the julian day number.
13230*/
13231static void computeHMS(DateTime *p){
13232  int s;
13233  if( p->validHMS ) return;
13234  computeJD(p);
13235  s = (int)((p->iJD + 43200000) % 86400000);
13236  p->s = s/1000.0;
13237  s = (int)p->s;
13238  p->s -= s;
13239  p->h = s/3600;
13240  s -= p->h*3600;
13241  p->m = s/60;
13242  p->s += s - p->m*60;
13243  p->validHMS = 1;
13244}
13245
13246/*
13247** Compute both YMD and HMS
13248*/
13249static void computeYMD_HMS(DateTime *p){
13250  computeYMD(p);
13251  computeHMS(p);
13252}
13253
13254/*
13255** Clear the YMD and HMS and the TZ
13256*/
13257static void clearYMD_HMS_TZ(DateTime *p){
13258  p->validYMD = 0;
13259  p->validHMS = 0;
13260  p->validTZ = 0;
13261}
13262
13263#ifndef SQLITE_OMIT_LOCALTIME
13264/*
13265** Compute the difference (in milliseconds)
13266** between localtime and UTC (a.k.a. GMT)
13267** for the time value p where p is in UTC.
13268*/
13269static sqlite3_int64 localtimeOffset(DateTime *p){
13270  DateTime x, y;
13271  time_t t;
13272  x = *p;
13273  computeYMD_HMS(&x);
13274  if( x.Y<1971 || x.Y>=2038 ){
13275    x.Y = 2000;
13276    x.M = 1;
13277    x.D = 1;
13278    x.h = 0;
13279    x.m = 0;
13280    x.s = 0.0;
13281  } else {
13282    int s = (int)(x.s + 0.5);
13283    x.s = s;
13284  }
13285  x.tz = 0;
13286  x.validJD = 0;
13287  computeJD(&x);
13288  t = (time_t)(x.iJD/1000 - 21086676*(i64)10000);
13289#ifdef HAVE_LOCALTIME_R
13290  {
13291    struct tm sLocal;
13292    localtime_r(&t, &sLocal);
13293    y.Y = sLocal.tm_year + 1900;
13294    y.M = sLocal.tm_mon + 1;
13295    y.D = sLocal.tm_mday;
13296    y.h = sLocal.tm_hour;
13297    y.m = sLocal.tm_min;
13298    y.s = sLocal.tm_sec;
13299  }
13300#elif defined(HAVE_LOCALTIME_S) && HAVE_LOCALTIME_S
13301  {
13302    struct tm sLocal;
13303    localtime_s(&sLocal, &t);
13304    y.Y = sLocal.tm_year + 1900;
13305    y.M = sLocal.tm_mon + 1;
13306    y.D = sLocal.tm_mday;
13307    y.h = sLocal.tm_hour;
13308    y.m = sLocal.tm_min;
13309    y.s = sLocal.tm_sec;
13310  }
13311#else
13312  {
13313    struct tm *pTm;
13314    sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
13315    pTm = localtime(&t);
13316    y.Y = pTm->tm_year + 1900;
13317    y.M = pTm->tm_mon + 1;
13318    y.D = pTm->tm_mday;
13319    y.h = pTm->tm_hour;
13320    y.m = pTm->tm_min;
13321    y.s = pTm->tm_sec;
13322    sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
13323  }
13324#endif
13325  y.validYMD = 1;
13326  y.validHMS = 1;
13327  y.validJD = 0;
13328  y.validTZ = 0;
13329  computeJD(&y);
13330  return y.iJD - x.iJD;
13331}
13332#endif /* SQLITE_OMIT_LOCALTIME */
13333
13334/*
13335** Process a modifier to a date-time stamp.  The modifiers are
13336** as follows:
13337**
13338**     NNN days
13339**     NNN hours
13340**     NNN minutes
13341**     NNN.NNNN seconds
13342**     NNN months
13343**     NNN years
13344**     start of month
13345**     start of year
13346**     start of week
13347**     start of day
13348**     weekday N
13349**     unixepoch
13350**     localtime
13351**     utc
13352**
13353** Return 0 on success and 1 if there is any kind of error.
13354*/
13355static int parseModifier(const char *zMod, DateTime *p){
13356  int rc = 1;
13357  int n;
13358  double r;
13359  char *z, zBuf[30];
13360  z = zBuf;
13361  for(n=0; n<ArraySize(zBuf)-1 && zMod[n]; n++){
13362    z[n] = (char)sqlite3UpperToLower[(u8)zMod[n]];
13363  }
13364  z[n] = 0;
13365  switch( z[0] ){
13366#ifndef SQLITE_OMIT_LOCALTIME
13367    case 'l': {
13368      /*    localtime
13369      **
13370      ** Assuming the current time value is UTC (a.k.a. GMT), shift it to
13371      ** show local time.
13372      */
13373      if( strcmp(z, "localtime")==0 ){
13374        computeJD(p);
13375        p->iJD += localtimeOffset(p);
13376        clearYMD_HMS_TZ(p);
13377        rc = 0;
13378      }
13379      break;
13380    }
13381#endif
13382    case 'u': {
13383      /*
13384      **    unixepoch
13385      **
13386      ** Treat the current value of p->iJD as the number of
13387      ** seconds since 1970.  Convert to a real julian day number.
13388      */
13389      if( strcmp(z, "unixepoch")==0 && p->validJD ){
13390        p->iJD = (p->iJD + 43200)/86400 + 21086676*(i64)10000000;
13391        clearYMD_HMS_TZ(p);
13392        rc = 0;
13393      }
13394#ifndef SQLITE_OMIT_LOCALTIME
13395      else if( strcmp(z, "utc")==0 ){
13396        sqlite3_int64 c1;
13397        computeJD(p);
13398        c1 = localtimeOffset(p);
13399        p->iJD -= c1;
13400        clearYMD_HMS_TZ(p);
13401        p->iJD += c1 - localtimeOffset(p);
13402        rc = 0;
13403      }
13404#endif
13405      break;
13406    }
13407    case 'w': {
13408      /*
13409      **    weekday N
13410      **
13411      ** Move the date to the same time on the next occurrence of
13412      ** weekday N where 0==Sunday, 1==Monday, and so forth.  If the
13413      ** date is already on the appropriate weekday, this is a no-op.
13414      */
13415      if( strncmp(z, "weekday ", 8)==0
13416               && sqlite3AtoF(&z[8], &r, sqlite3Strlen30(&z[8]), SQLITE_UTF8)
13417               && (n=(int)r)==r && n>=0 && r<7 ){
13418        sqlite3_int64 Z;
13419        computeYMD_HMS(p);
13420        p->validTZ = 0;
13421        p->validJD = 0;
13422        computeJD(p);
13423        Z = ((p->iJD + 129600000)/86400000) % 7;
13424        if( Z>n ) Z -= 7;
13425        p->iJD += (n - Z)*86400000;
13426        clearYMD_HMS_TZ(p);
13427        rc = 0;
13428      }
13429      break;
13430    }
13431    case 's': {
13432      /*
13433      **    start of TTTTT
13434      **
13435      ** Move the date backwards to the beginning of the current day,
13436      ** or month or year.
13437      */
13438      if( strncmp(z, "start of ", 9)!=0 ) break;
13439      z += 9;
13440      computeYMD(p);
13441      p->validHMS = 1;
13442      p->h = p->m = 0;
13443      p->s = 0.0;
13444      p->validTZ = 0;
13445      p->validJD = 0;
13446      if( strcmp(z,"month")==0 ){
13447        p->D = 1;
13448        rc = 0;
13449      }else if( strcmp(z,"year")==0 ){
13450        computeYMD(p);
13451        p->M = 1;
13452        p->D = 1;
13453        rc = 0;
13454      }else if( strcmp(z,"day")==0 ){
13455        rc = 0;
13456      }
13457      break;
13458    }
13459    case '+':
13460    case '-':
13461    case '0':
13462    case '1':
13463    case '2':
13464    case '3':
13465    case '4':
13466    case '5':
13467    case '6':
13468    case '7':
13469    case '8':
13470    case '9': {
13471      double rRounder;
13472      for(n=1; z[n] && z[n]!=':' && !sqlite3Isspace(z[n]); n++){}
13473      if( !sqlite3AtoF(z, &r, n, SQLITE_UTF8) ){
13474        rc = 1;
13475        break;
13476      }
13477      if( z[n]==':' ){
13478        /* A modifier of the form (+|-)HH:MM:SS.FFF adds (or subtracts) the
13479        ** specified number of hours, minutes, seconds, and fractional seconds
13480        ** to the time.  The ".FFF" may be omitted.  The ":SS.FFF" may be
13481        ** omitted.
13482        */
13483        const char *z2 = z;
13484        DateTime tx;
13485        sqlite3_int64 day;
13486        if( !sqlite3Isdigit(*z2) ) z2++;
13487        memset(&tx, 0, sizeof(tx));
13488        if( parseHhMmSs(z2, &tx) ) break;
13489        computeJD(&tx);
13490        tx.iJD -= 43200000;
13491        day = tx.iJD/86400000;
13492        tx.iJD -= day*86400000;
13493        if( z[0]=='-' ) tx.iJD = -tx.iJD;
13494        computeJD(p);
13495        clearYMD_HMS_TZ(p);
13496        p->iJD += tx.iJD;
13497        rc = 0;
13498        break;
13499      }
13500      z += n;
13501      while( sqlite3Isspace(*z) ) z++;
13502      n = sqlite3Strlen30(z);
13503      if( n>10 || n<3 ) break;
13504      if( z[n-1]=='s' ){ z[n-1] = 0; n--; }
13505      computeJD(p);
13506      rc = 0;
13507      rRounder = r<0 ? -0.5 : +0.5;
13508      if( n==3 && strcmp(z,"day")==0 ){
13509        p->iJD += (sqlite3_int64)(r*86400000.0 + rRounder);
13510      }else if( n==4 && strcmp(z,"hour")==0 ){
13511        p->iJD += (sqlite3_int64)(r*(86400000.0/24.0) + rRounder);
13512      }else if( n==6 && strcmp(z,"minute")==0 ){
13513        p->iJD += (sqlite3_int64)(r*(86400000.0/(24.0*60.0)) + rRounder);
13514      }else if( n==6 && strcmp(z,"second")==0 ){
13515        p->iJD += (sqlite3_int64)(r*(86400000.0/(24.0*60.0*60.0)) + rRounder);
13516      }else if( n==5 && strcmp(z,"month")==0 ){
13517        int x, y;
13518        computeYMD_HMS(p);
13519        p->M += (int)r;
13520        x = p->M>0 ? (p->M-1)/12 : (p->M-12)/12;
13521        p->Y += x;
13522        p->M -= x*12;
13523        p->validJD = 0;
13524        computeJD(p);
13525        y = (int)r;
13526        if( y!=r ){
13527          p->iJD += (sqlite3_int64)((r - y)*30.0*86400000.0 + rRounder);
13528        }
13529      }else if( n==4 && strcmp(z,"year")==0 ){
13530        int y = (int)r;
13531        computeYMD_HMS(p);
13532        p->Y += y;
13533        p->validJD = 0;
13534        computeJD(p);
13535        if( y!=r ){
13536          p->iJD += (sqlite3_int64)((r - y)*365.0*86400000.0 + rRounder);
13537        }
13538      }else{
13539        rc = 1;
13540      }
13541      clearYMD_HMS_TZ(p);
13542      break;
13543    }
13544    default: {
13545      break;
13546    }
13547  }
13548  return rc;
13549}
13550
13551/*
13552** Process time function arguments.  argv[0] is a date-time stamp.
13553** argv[1] and following are modifiers.  Parse them all and write
13554** the resulting time into the DateTime structure p.  Return 0
13555** on success and 1 if there are any errors.
13556**
13557** If there are zero parameters (if even argv[0] is undefined)
13558** then assume a default value of "now" for argv[0].
13559*/
13560static int isDate(
13561  sqlite3_context *context,
13562  int argc,
13563  sqlite3_value **argv,
13564  DateTime *p
13565){
13566  int i;
13567  const unsigned char *z;
13568  int eType;
13569  memset(p, 0, sizeof(*p));
13570  if( argc==0 ){
13571    setDateTimeToCurrent(context, p);
13572  }else if( (eType = sqlite3_value_type(argv[0]))==SQLITE_FLOAT
13573                   || eType==SQLITE_INTEGER ){
13574    p->iJD = (sqlite3_int64)(sqlite3_value_double(argv[0])*86400000.0 + 0.5);
13575    p->validJD = 1;
13576  }else{
13577    z = sqlite3_value_text(argv[0]);
13578    if( !z || parseDateOrTime(context, (char*)z, p) ){
13579      return 1;
13580    }
13581  }
13582  for(i=1; i<argc; i++){
13583    if( (z = sqlite3_value_text(argv[i]))==0 || parseModifier((char*)z, p) ){
13584      return 1;
13585    }
13586  }
13587  return 0;
13588}
13589
13590
13591/*
13592** The following routines implement the various date and time functions
13593** of SQLite.
13594*/
13595
13596/*
13597**    julianday( TIMESTRING, MOD, MOD, ...)
13598**
13599** Return the julian day number of the date specified in the arguments
13600*/
13601static void juliandayFunc(
13602  sqlite3_context *context,
13603  int argc,
13604  sqlite3_value **argv
13605){
13606  DateTime x;
13607  if( isDate(context, argc, argv, &x)==0 ){
13608    computeJD(&x);
13609    sqlite3_result_double(context, x.iJD/86400000.0);
13610  }
13611}
13612
13613/*
13614**    datetime( TIMESTRING, MOD, MOD, ...)
13615**
13616** Return YYYY-MM-DD HH:MM:SS
13617*/
13618static void datetimeFunc(
13619  sqlite3_context *context,
13620  int argc,
13621  sqlite3_value **argv
13622){
13623  DateTime x;
13624  if( isDate(context, argc, argv, &x)==0 ){
13625    char zBuf[100];
13626    computeYMD_HMS(&x);
13627    sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d %02d:%02d:%02d",
13628                     x.Y, x.M, x.D, x.h, x.m, (int)(x.s));
13629    sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
13630  }
13631}
13632
13633/*
13634**    time( TIMESTRING, MOD, MOD, ...)
13635**
13636** Return HH:MM:SS
13637*/
13638static void timeFunc(
13639  sqlite3_context *context,
13640  int argc,
13641  sqlite3_value **argv
13642){
13643  DateTime x;
13644  if( isDate(context, argc, argv, &x)==0 ){
13645    char zBuf[100];
13646    computeHMS(&x);
13647    sqlite3_snprintf(sizeof(zBuf), zBuf, "%02d:%02d:%02d", x.h, x.m, (int)x.s);
13648    sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
13649  }
13650}
13651
13652/*
13653**    date( TIMESTRING, MOD, MOD, ...)
13654**
13655** Return YYYY-MM-DD
13656*/
13657static void dateFunc(
13658  sqlite3_context *context,
13659  int argc,
13660  sqlite3_value **argv
13661){
13662  DateTime x;
13663  if( isDate(context, argc, argv, &x)==0 ){
13664    char zBuf[100];
13665    computeYMD(&x);
13666    sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d", x.Y, x.M, x.D);
13667    sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
13668  }
13669}
13670
13671/*
13672**    strftime( FORMAT, TIMESTRING, MOD, MOD, ...)
13673**
13674** Return a string described by FORMAT.  Conversions as follows:
13675**
13676**   %d  day of month
13677**   %f  ** fractional seconds  SS.SSS
13678**   %H  hour 00-24
13679**   %j  day of year 000-366
13680**   %J  ** Julian day number
13681**   %m  month 01-12
13682**   %M  minute 00-59
13683**   %s  seconds since 1970-01-01
13684**   %S  seconds 00-59
13685**   %w  day of week 0-6  sunday==0
13686**   %W  week of year 00-53
13687**   %Y  year 0000-9999
13688**   %%  %
13689*/
13690static void strftimeFunc(
13691  sqlite3_context *context,
13692  int argc,
13693  sqlite3_value **argv
13694){
13695  DateTime x;
13696  u64 n;
13697  size_t i,j;
13698  char *z;
13699  sqlite3 *db;
13700  const char *zFmt = (const char*)sqlite3_value_text(argv[0]);
13701  char zBuf[100];
13702  if( zFmt==0 || isDate(context, argc-1, argv+1, &x) ) return;
13703  db = sqlite3_context_db_handle(context);
13704  for(i=0, n=1; zFmt[i]; i++, n++){
13705    if( zFmt[i]=='%' ){
13706      switch( zFmt[i+1] ){
13707        case 'd':
13708        case 'H':
13709        case 'm':
13710        case 'M':
13711        case 'S':
13712        case 'W':
13713          n++;
13714          /* fall thru */
13715        case 'w':
13716        case '%':
13717          break;
13718        case 'f':
13719          n += 8;
13720          break;
13721        case 'j':
13722          n += 3;
13723          break;
13724        case 'Y':
13725          n += 8;
13726          break;
13727        case 's':
13728        case 'J':
13729          n += 50;
13730          break;
13731        default:
13732          return;  /* ERROR.  return a NULL */
13733      }
13734      i++;
13735    }
13736  }
13737  testcase( n==sizeof(zBuf)-1 );
13738  testcase( n==sizeof(zBuf) );
13739  testcase( n==(u64)db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
13740  testcase( n==(u64)db->aLimit[SQLITE_LIMIT_LENGTH] );
13741  if( n<sizeof(zBuf) ){
13742    z = zBuf;
13743  }else if( n>(u64)db->aLimit[SQLITE_LIMIT_LENGTH] ){
13744    sqlite3_result_error_toobig(context);
13745    return;
13746  }else{
13747    z = sqlite3DbMallocRaw(db, (int)n);
13748    if( z==0 ){
13749      sqlite3_result_error_nomem(context);
13750      return;
13751    }
13752  }
13753  computeJD(&x);
13754  computeYMD_HMS(&x);
13755  for(i=j=0; zFmt[i]; i++){
13756    if( zFmt[i]!='%' ){
13757      z[j++] = zFmt[i];
13758    }else{
13759      i++;
13760      switch( zFmt[i] ){
13761        case 'd':  sqlite3_snprintf(3, &z[j],"%02d",x.D); j+=2; break;
13762        case 'f': {
13763          double s = x.s;
13764          if( s>59.999 ) s = 59.999;
13765          sqlite3_snprintf(7, &z[j],"%06.3f", s);
13766          j += sqlite3Strlen30(&z[j]);
13767          break;
13768        }
13769        case 'H':  sqlite3_snprintf(3, &z[j],"%02d",x.h); j+=2; break;
13770        case 'W': /* Fall thru */
13771        case 'j': {
13772          int nDay;             /* Number of days since 1st day of year */
13773          DateTime y = x;
13774          y.validJD = 0;
13775          y.M = 1;
13776          y.D = 1;
13777          computeJD(&y);
13778          nDay = (int)((x.iJD-y.iJD+43200000)/86400000);
13779          if( zFmt[i]=='W' ){
13780            int wd;   /* 0=Monday, 1=Tuesday, ... 6=Sunday */
13781            wd = (int)(((x.iJD+43200000)/86400000)%7);
13782            sqlite3_snprintf(3, &z[j],"%02d",(nDay+7-wd)/7);
13783            j += 2;
13784          }else{
13785            sqlite3_snprintf(4, &z[j],"%03d",nDay+1);
13786            j += 3;
13787          }
13788          break;
13789        }
13790        case 'J': {
13791          sqlite3_snprintf(20, &z[j],"%.16g",x.iJD/86400000.0);
13792          j+=sqlite3Strlen30(&z[j]);
13793          break;
13794        }
13795        case 'm':  sqlite3_snprintf(3, &z[j],"%02d",x.M); j+=2; break;
13796        case 'M':  sqlite3_snprintf(3, &z[j],"%02d",x.m); j+=2; break;
13797        case 's': {
13798          sqlite3_snprintf(30,&z[j],"%lld",
13799                           (i64)(x.iJD/1000 - 21086676*(i64)10000));
13800          j += sqlite3Strlen30(&z[j]);
13801          break;
13802        }
13803        case 'S':  sqlite3_snprintf(3,&z[j],"%02d",(int)x.s); j+=2; break;
13804        case 'w': {
13805          z[j++] = (char)(((x.iJD+129600000)/86400000) % 7) + '0';
13806          break;
13807        }
13808        case 'Y': {
13809          sqlite3_snprintf(5,&z[j],"%04d",x.Y); j+=sqlite3Strlen30(&z[j]);
13810          break;
13811        }
13812        default:   z[j++] = '%'; break;
13813      }
13814    }
13815  }
13816  z[j] = 0;
13817  sqlite3_result_text(context, z, -1,
13818                      z==zBuf ? SQLITE_TRANSIENT : SQLITE_DYNAMIC);
13819}
13820
13821/*
13822** current_time()
13823**
13824** This function returns the same value as time('now').
13825*/
13826static void ctimeFunc(
13827  sqlite3_context *context,
13828  int NotUsed,
13829  sqlite3_value **NotUsed2
13830){
13831  UNUSED_PARAMETER2(NotUsed, NotUsed2);
13832  timeFunc(context, 0, 0);
13833}
13834
13835/*
13836** current_date()
13837**
13838** This function returns the same value as date('now').
13839*/
13840static void cdateFunc(
13841  sqlite3_context *context,
13842  int NotUsed,
13843  sqlite3_value **NotUsed2
13844){
13845  UNUSED_PARAMETER2(NotUsed, NotUsed2);
13846  dateFunc(context, 0, 0);
13847}
13848
13849/*
13850** current_timestamp()
13851**
13852** This function returns the same value as datetime('now').
13853*/
13854static void ctimestampFunc(
13855  sqlite3_context *context,
13856  int NotUsed,
13857  sqlite3_value **NotUsed2
13858){
13859  UNUSED_PARAMETER2(NotUsed, NotUsed2);
13860  datetimeFunc(context, 0, 0);
13861}
13862#endif /* !defined(SQLITE_OMIT_DATETIME_FUNCS) */
13863
13864#ifdef SQLITE_OMIT_DATETIME_FUNCS
13865/*
13866** If the library is compiled to omit the full-scale date and time
13867** handling (to get a smaller binary), the following minimal version
13868** of the functions current_time(), current_date() and current_timestamp()
13869** are included instead. This is to support column declarations that
13870** include "DEFAULT CURRENT_TIME" etc.
13871**
13872** This function uses the C-library functions time(), gmtime()
13873** and strftime(). The format string to pass to strftime() is supplied
13874** as the user-data for the function.
13875*/
13876static void currentTimeFunc(
13877  sqlite3_context *context,
13878  int argc,
13879  sqlite3_value **argv
13880){
13881  time_t t;
13882  char *zFormat = (char *)sqlite3_user_data(context);
13883  sqlite3 *db;
13884  sqlite3_int64 iT;
13885  char zBuf[20];
13886
13887  UNUSED_PARAMETER(argc);
13888  UNUSED_PARAMETER(argv);
13889
13890  db = sqlite3_context_db_handle(context);
13891  sqlite3OsCurrentTimeInt64(db->pVfs, &iT);
13892  t = iT/1000 - 10000*(sqlite3_int64)21086676;
13893#ifdef HAVE_GMTIME_R
13894  {
13895    struct tm sNow;
13896    gmtime_r(&t, &sNow);
13897    strftime(zBuf, 20, zFormat, &sNow);
13898  }
13899#else
13900  {
13901    struct tm *pTm;
13902    sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
13903    pTm = gmtime(&t);
13904    strftime(zBuf, 20, zFormat, pTm);
13905    sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
13906  }
13907#endif
13908
13909  sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
13910}
13911#endif
13912
13913/*
13914** This function registered all of the above C functions as SQL
13915** functions.  This should be the only routine in this file with
13916** external linkage.
13917*/
13918SQLITE_PRIVATE void sqlite3RegisterDateTimeFunctions(void){
13919  static SQLITE_WSD FuncDef aDateTimeFuncs[] = {
13920#ifndef SQLITE_OMIT_DATETIME_FUNCS
13921    FUNCTION(julianday,        -1, 0, 0, juliandayFunc ),
13922    FUNCTION(date,             -1, 0, 0, dateFunc      ),
13923    FUNCTION(time,             -1, 0, 0, timeFunc      ),
13924    FUNCTION(datetime,         -1, 0, 0, datetimeFunc  ),
13925    FUNCTION(strftime,         -1, 0, 0, strftimeFunc  ),
13926    FUNCTION(current_time,      0, 0, 0, ctimeFunc     ),
13927    FUNCTION(current_timestamp, 0, 0, 0, ctimestampFunc),
13928    FUNCTION(current_date,      0, 0, 0, cdateFunc     ),
13929#else
13930    STR_FUNCTION(current_time,      0, "%H:%M:%S",          0, currentTimeFunc),
13931    STR_FUNCTION(current_date,      0, "%Y-%m-%d",          0, currentTimeFunc),
13932    STR_FUNCTION(current_timestamp, 0, "%Y-%m-%d %H:%M:%S", 0, currentTimeFunc),
13933#endif
13934  };
13935  int i;
13936  FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
13937  FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aDateTimeFuncs);
13938
13939  for(i=0; i<ArraySize(aDateTimeFuncs); i++){
13940    sqlite3FuncDefInsert(pHash, &aFunc[i]);
13941  }
13942}
13943
13944/************** End of date.c ************************************************/
13945/************** Begin file os.c **********************************************/
13946/*
13947** 2005 November 29
13948**
13949** The author disclaims copyright to this source code.  In place of
13950** a legal notice, here is a blessing:
13951**
13952**    May you do good and not evil.
13953**    May you find forgiveness for yourself and forgive others.
13954**    May you share freely, never taking more than you give.
13955**
13956******************************************************************************
13957**
13958** This file contains OS interface code that is common to all
13959** architectures.
13960*/
13961#define _SQLITE_OS_C_ 1
13962#undef _SQLITE_OS_C_
13963
13964/*
13965** The default SQLite sqlite3_vfs implementations do not allocate
13966** memory (actually, os_unix.c allocates a small amount of memory
13967** from within OsOpen()), but some third-party implementations may.
13968** So we test the effects of a malloc() failing and the sqlite3OsXXX()
13969** function returning SQLITE_IOERR_NOMEM using the DO_OS_MALLOC_TEST macro.
13970**
13971** The following functions are instrumented for malloc() failure
13972** testing:
13973**
13974**     sqlite3OsOpen()
13975**     sqlite3OsRead()
13976**     sqlite3OsWrite()
13977**     sqlite3OsSync()
13978**     sqlite3OsLock()
13979**
13980*/
13981#if defined(SQLITE_TEST)
13982SQLITE_API int sqlite3_memdebug_vfs_oom_test = 1;
13983  #define DO_OS_MALLOC_TEST(x)                                       \
13984  if (sqlite3_memdebug_vfs_oom_test && (!x || !sqlite3IsMemJournal(x))) {  \
13985    void *pTstAlloc = sqlite3Malloc(10);                             \
13986    if (!pTstAlloc) return SQLITE_IOERR_NOMEM;                       \
13987    sqlite3_free(pTstAlloc);                                         \
13988  }
13989#else
13990  #define DO_OS_MALLOC_TEST(x)
13991#endif
13992
13993/*
13994** The following routines are convenience wrappers around methods
13995** of the sqlite3_file object.  This is mostly just syntactic sugar. All
13996** of this would be completely automatic if SQLite were coded using
13997** C++ instead of plain old C.
13998*/
13999SQLITE_PRIVATE int sqlite3OsClose(sqlite3_file *pId){
14000  int rc = SQLITE_OK;
14001  if( pId->pMethods ){
14002    rc = pId->pMethods->xClose(pId);
14003    pId->pMethods = 0;
14004  }
14005  return rc;
14006}
14007SQLITE_PRIVATE int sqlite3OsRead(sqlite3_file *id, void *pBuf, int amt, i64 offset){
14008  DO_OS_MALLOC_TEST(id);
14009  return id->pMethods->xRead(id, pBuf, amt, offset);
14010}
14011SQLITE_PRIVATE int sqlite3OsWrite(sqlite3_file *id, const void *pBuf, int amt, i64 offset){
14012  DO_OS_MALLOC_TEST(id);
14013  return id->pMethods->xWrite(id, pBuf, amt, offset);
14014}
14015SQLITE_PRIVATE int sqlite3OsTruncate(sqlite3_file *id, i64 size){
14016  return id->pMethods->xTruncate(id, size);
14017}
14018SQLITE_PRIVATE int sqlite3OsSync(sqlite3_file *id, int flags){
14019  DO_OS_MALLOC_TEST(id);
14020  return id->pMethods->xSync(id, flags);
14021}
14022SQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file *id, i64 *pSize){
14023  DO_OS_MALLOC_TEST(id);
14024  return id->pMethods->xFileSize(id, pSize);
14025}
14026SQLITE_PRIVATE int sqlite3OsLock(sqlite3_file *id, int lockType){
14027  DO_OS_MALLOC_TEST(id);
14028  return id->pMethods->xLock(id, lockType);
14029}
14030SQLITE_PRIVATE int sqlite3OsUnlock(sqlite3_file *id, int lockType){
14031  return id->pMethods->xUnlock(id, lockType);
14032}
14033SQLITE_PRIVATE int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut){
14034  DO_OS_MALLOC_TEST(id);
14035  return id->pMethods->xCheckReservedLock(id, pResOut);
14036}
14037SQLITE_PRIVATE int sqlite3OsFileControl(sqlite3_file *id, int op, void *pArg){
14038  return id->pMethods->xFileControl(id, op, pArg);
14039}
14040SQLITE_PRIVATE int sqlite3OsSectorSize(sqlite3_file *id){
14041  int (*xSectorSize)(sqlite3_file*) = id->pMethods->xSectorSize;
14042  return (xSectorSize ? xSectorSize(id) : SQLITE_DEFAULT_SECTOR_SIZE);
14043}
14044SQLITE_PRIVATE int sqlite3OsDeviceCharacteristics(sqlite3_file *id){
14045  return id->pMethods->xDeviceCharacteristics(id);
14046}
14047SQLITE_PRIVATE int sqlite3OsShmLock(sqlite3_file *id, int offset, int n, int flags){
14048  return id->pMethods->xShmLock(id, offset, n, flags);
14049}
14050SQLITE_PRIVATE void sqlite3OsShmBarrier(sqlite3_file *id){
14051  id->pMethods->xShmBarrier(id);
14052}
14053SQLITE_PRIVATE int sqlite3OsShmUnmap(sqlite3_file *id, int deleteFlag){
14054  return id->pMethods->xShmUnmap(id, deleteFlag);
14055}
14056SQLITE_PRIVATE int sqlite3OsShmMap(
14057  sqlite3_file *id,               /* Database file handle */
14058  int iPage,
14059  int pgsz,
14060  int bExtend,                    /* True to extend file if necessary */
14061  void volatile **pp              /* OUT: Pointer to mapping */
14062){
14063  return id->pMethods->xShmMap(id, iPage, pgsz, bExtend, pp);
14064}
14065
14066/*
14067** The next group of routines are convenience wrappers around the
14068** VFS methods.
14069*/
14070SQLITE_PRIVATE int sqlite3OsOpen(
14071  sqlite3_vfs *pVfs,
14072  const char *zPath,
14073  sqlite3_file *pFile,
14074  int flags,
14075  int *pFlagsOut
14076){
14077  int rc;
14078  DO_OS_MALLOC_TEST(0);
14079  /* 0x87f3f is a mask of SQLITE_OPEN_ flags that are valid to be passed
14080  ** down into the VFS layer.  Some SQLITE_OPEN_ flags (for example,
14081  ** SQLITE_OPEN_FULLMUTEX or SQLITE_OPEN_SHAREDCACHE) are blocked before
14082  ** reaching the VFS. */
14083  rc = pVfs->xOpen(pVfs, zPath, pFile, flags & 0x87f3f, pFlagsOut);
14084  assert( rc==SQLITE_OK || pFile->pMethods==0 );
14085  return rc;
14086}
14087SQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){
14088  return pVfs->xDelete(pVfs, zPath, dirSync);
14089}
14090SQLITE_PRIVATE int sqlite3OsAccess(
14091  sqlite3_vfs *pVfs,
14092  const char *zPath,
14093  int flags,
14094  int *pResOut
14095){
14096  DO_OS_MALLOC_TEST(0);
14097  return pVfs->xAccess(pVfs, zPath, flags, pResOut);
14098}
14099SQLITE_PRIVATE int sqlite3OsFullPathname(
14100  sqlite3_vfs *pVfs,
14101  const char *zPath,
14102  int nPathOut,
14103  char *zPathOut
14104){
14105  zPathOut[0] = 0;
14106  return pVfs->xFullPathname(pVfs, zPath, nPathOut, zPathOut);
14107}
14108#ifndef SQLITE_OMIT_LOAD_EXTENSION
14109SQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *pVfs, const char *zPath){
14110  return pVfs->xDlOpen(pVfs, zPath);
14111}
14112SQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
14113  pVfs->xDlError(pVfs, nByte, zBufOut);
14114}
14115SQLITE_PRIVATE void (*sqlite3OsDlSym(sqlite3_vfs *pVfs, void *pHdle, const char *zSym))(void){
14116  return pVfs->xDlSym(pVfs, pHdle, zSym);
14117}
14118SQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *pVfs, void *pHandle){
14119  pVfs->xDlClose(pVfs, pHandle);
14120}
14121#endif /* SQLITE_OMIT_LOAD_EXTENSION */
14122SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
14123  return pVfs->xRandomness(pVfs, nByte, zBufOut);
14124}
14125SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *pVfs, int nMicro){
14126  return pVfs->xSleep(pVfs, nMicro);
14127}
14128SQLITE_PRIVATE int sqlite3OsCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *pTimeOut){
14129  int rc;
14130  /* IMPLEMENTATION-OF: R-49045-42493 SQLite will use the xCurrentTimeInt64()
14131  ** method to get the current date and time if that method is available
14132  ** (if iVersion is 2 or greater and the function pointer is not NULL) and
14133  ** will fall back to xCurrentTime() if xCurrentTimeInt64() is
14134  ** unavailable.
14135  */
14136  if( pVfs->iVersion>=2 && pVfs->xCurrentTimeInt64 ){
14137    rc = pVfs->xCurrentTimeInt64(pVfs, pTimeOut);
14138  }else{
14139    double r;
14140    rc = pVfs->xCurrentTime(pVfs, &r);
14141    *pTimeOut = (sqlite3_int64)(r*86400000.0);
14142  }
14143  return rc;
14144}
14145
14146SQLITE_PRIVATE int sqlite3OsOpenMalloc(
14147  sqlite3_vfs *pVfs,
14148  const char *zFile,
14149  sqlite3_file **ppFile,
14150  int flags,
14151  int *pOutFlags
14152){
14153  int rc = SQLITE_NOMEM;
14154  sqlite3_file *pFile;
14155  pFile = (sqlite3_file *)sqlite3Malloc(pVfs->szOsFile);
14156  if( pFile ){
14157    rc = sqlite3OsOpen(pVfs, zFile, pFile, flags, pOutFlags);
14158    if( rc!=SQLITE_OK ){
14159      sqlite3_free(pFile);
14160    }else{
14161      *ppFile = pFile;
14162    }
14163  }
14164  return rc;
14165}
14166SQLITE_PRIVATE int sqlite3OsCloseFree(sqlite3_file *pFile){
14167  int rc = SQLITE_OK;
14168  assert( pFile );
14169  rc = sqlite3OsClose(pFile);
14170  sqlite3_free(pFile);
14171  return rc;
14172}
14173
14174/*
14175** This function is a wrapper around the OS specific implementation of
14176** sqlite3_os_init(). The purpose of the wrapper is to provide the
14177** ability to simulate a malloc failure, so that the handling of an
14178** error in sqlite3_os_init() by the upper layers can be tested.
14179*/
14180SQLITE_PRIVATE int sqlite3OsInit(void){
14181  void *p = sqlite3_malloc(10);
14182  if( p==0 ) return SQLITE_NOMEM;
14183  sqlite3_free(p);
14184  return sqlite3_os_init();
14185}
14186
14187/*
14188** The list of all registered VFS implementations.
14189*/
14190static sqlite3_vfs * SQLITE_WSD vfsList = 0;
14191#define vfsList GLOBAL(sqlite3_vfs *, vfsList)
14192
14193/*
14194** Locate a VFS by name.  If no name is given, simply return the
14195** first VFS on the list.
14196*/
14197SQLITE_API sqlite3_vfs *sqlite3_vfs_find(const char *zVfs){
14198  sqlite3_vfs *pVfs = 0;
14199#if SQLITE_THREADSAFE
14200  sqlite3_mutex *mutex;
14201#endif
14202#ifndef SQLITE_OMIT_AUTOINIT
14203  int rc = sqlite3_initialize();
14204  if( rc ) return 0;
14205#endif
14206#if SQLITE_THREADSAFE
14207  mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
14208#endif
14209  sqlite3_mutex_enter(mutex);
14210  for(pVfs = vfsList; pVfs; pVfs=pVfs->pNext){
14211    if( zVfs==0 ) break;
14212    if( strcmp(zVfs, pVfs->zName)==0 ) break;
14213  }
14214  sqlite3_mutex_leave(mutex);
14215  return pVfs;
14216}
14217
14218/*
14219** Unlink a VFS from the linked list
14220*/
14221static void vfsUnlink(sqlite3_vfs *pVfs){
14222  assert( sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)) );
14223  if( pVfs==0 ){
14224    /* No-op */
14225  }else if( vfsList==pVfs ){
14226    vfsList = pVfs->pNext;
14227  }else if( vfsList ){
14228    sqlite3_vfs *p = vfsList;
14229    while( p->pNext && p->pNext!=pVfs ){
14230      p = p->pNext;
14231    }
14232    if( p->pNext==pVfs ){
14233      p->pNext = pVfs->pNext;
14234    }
14235  }
14236}
14237
14238/*
14239** Register a VFS with the system.  It is harmless to register the same
14240** VFS multiple times.  The new VFS becomes the default if makeDflt is
14241** true.
14242*/
14243SQLITE_API int sqlite3_vfs_register(sqlite3_vfs *pVfs, int makeDflt){
14244  sqlite3_mutex *mutex = 0;
14245#ifndef SQLITE_OMIT_AUTOINIT
14246  int rc = sqlite3_initialize();
14247  if( rc ) return rc;
14248#endif
14249  mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
14250  sqlite3_mutex_enter(mutex);
14251  vfsUnlink(pVfs);
14252  if( makeDflt || vfsList==0 ){
14253    pVfs->pNext = vfsList;
14254    vfsList = pVfs;
14255  }else{
14256    pVfs->pNext = vfsList->pNext;
14257    vfsList->pNext = pVfs;
14258  }
14259  assert(vfsList);
14260  sqlite3_mutex_leave(mutex);
14261  return SQLITE_OK;
14262}
14263
14264/*
14265** Unregister a VFS so that it is no longer accessible.
14266*/
14267SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs *pVfs){
14268#if SQLITE_THREADSAFE
14269  sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
14270#endif
14271  sqlite3_mutex_enter(mutex);
14272  vfsUnlink(pVfs);
14273  sqlite3_mutex_leave(mutex);
14274  return SQLITE_OK;
14275}
14276
14277/************** End of os.c **************************************************/
14278/************** Begin file fault.c *******************************************/
14279/*
14280** 2008 Jan 22
14281**
14282** The author disclaims copyright to this source code.  In place of
14283** a legal notice, here is a blessing:
14284**
14285**    May you do good and not evil.
14286**    May you find forgiveness for yourself and forgive others.
14287**    May you share freely, never taking more than you give.
14288**
14289*************************************************************************
14290**
14291** This file contains code to support the concept of "benign"
14292** malloc failures (when the xMalloc() or xRealloc() method of the
14293** sqlite3_mem_methods structure fails to allocate a block of memory
14294** and returns 0).
14295**
14296** Most malloc failures are non-benign. After they occur, SQLite
14297** abandons the current operation and returns an error code (usually
14298** SQLITE_NOMEM) to the user. However, sometimes a fault is not necessarily
14299** fatal. For example, if a malloc fails while resizing a hash table, this
14300** is completely recoverable simply by not carrying out the resize. The
14301** hash table will continue to function normally.  So a malloc failure
14302** during a hash table resize is a benign fault.
14303*/
14304
14305
14306#ifndef SQLITE_OMIT_BUILTIN_TEST
14307
14308/*
14309** Global variables.
14310*/
14311typedef struct BenignMallocHooks BenignMallocHooks;
14312static SQLITE_WSD struct BenignMallocHooks {
14313  void (*xBenignBegin)(void);
14314  void (*xBenignEnd)(void);
14315} sqlite3Hooks = { 0, 0 };
14316
14317/* The "wsdHooks" macro will resolve to the appropriate BenignMallocHooks
14318** structure.  If writable static data is unsupported on the target,
14319** we have to locate the state vector at run-time.  In the more common
14320** case where writable static data is supported, wsdHooks can refer directly
14321** to the "sqlite3Hooks" state vector declared above.
14322*/
14323#ifdef SQLITE_OMIT_WSD
14324# define wsdHooksInit \
14325  BenignMallocHooks *x = &GLOBAL(BenignMallocHooks,sqlite3Hooks)
14326# define wsdHooks x[0]
14327#else
14328# define wsdHooksInit
14329# define wsdHooks sqlite3Hooks
14330#endif
14331
14332
14333/*
14334** Register hooks to call when sqlite3BeginBenignMalloc() and
14335** sqlite3EndBenignMalloc() are called, respectively.
14336*/
14337SQLITE_PRIVATE void sqlite3BenignMallocHooks(
14338  void (*xBenignBegin)(void),
14339  void (*xBenignEnd)(void)
14340){
14341  wsdHooksInit;
14342  wsdHooks.xBenignBegin = xBenignBegin;
14343  wsdHooks.xBenignEnd = xBenignEnd;
14344}
14345
14346/*
14347** This (sqlite3EndBenignMalloc()) is called by SQLite code to indicate that
14348** subsequent malloc failures are benign. A call to sqlite3EndBenignMalloc()
14349** indicates that subsequent malloc failures are non-benign.
14350*/
14351SQLITE_PRIVATE void sqlite3BeginBenignMalloc(void){
14352  wsdHooksInit;
14353  if( wsdHooks.xBenignBegin ){
14354    wsdHooks.xBenignBegin();
14355  }
14356}
14357SQLITE_PRIVATE void sqlite3EndBenignMalloc(void){
14358  wsdHooksInit;
14359  if( wsdHooks.xBenignEnd ){
14360    wsdHooks.xBenignEnd();
14361  }
14362}
14363
14364#endif   /* #ifndef SQLITE_OMIT_BUILTIN_TEST */
14365
14366/************** End of fault.c ***********************************************/
14367/************** Begin file mem0.c ********************************************/
14368/*
14369** 2008 October 28
14370**
14371** The author disclaims copyright to this source code.  In place of
14372** a legal notice, here is a blessing:
14373**
14374**    May you do good and not evil.
14375**    May you find forgiveness for yourself and forgive others.
14376**    May you share freely, never taking more than you give.
14377**
14378*************************************************************************
14379**
14380** This file contains a no-op memory allocation drivers for use when
14381** SQLITE_ZERO_MALLOC is defined.  The allocation drivers implemented
14382** here always fail.  SQLite will not operate with these drivers.  These
14383** are merely placeholders.  Real drivers must be substituted using
14384** sqlite3_config() before SQLite will operate.
14385*/
14386
14387/*
14388** This version of the memory allocator is the default.  It is
14389** used when no other memory allocator is specified using compile-time
14390** macros.
14391*/
14392#ifdef SQLITE_ZERO_MALLOC
14393
14394/*
14395** No-op versions of all memory allocation routines
14396*/
14397static void *sqlite3MemMalloc(int nByte){ return 0; }
14398static void sqlite3MemFree(void *pPrior){ return; }
14399static void *sqlite3MemRealloc(void *pPrior, int nByte){ return 0; }
14400static int sqlite3MemSize(void *pPrior){ return 0; }
14401static int sqlite3MemRoundup(int n){ return n; }
14402static int sqlite3MemInit(void *NotUsed){ return SQLITE_OK; }
14403static void sqlite3MemShutdown(void *NotUsed){ return; }
14404
14405/*
14406** This routine is the only routine in this file with external linkage.
14407**
14408** Populate the low-level memory allocation function pointers in
14409** sqlite3GlobalConfig.m with pointers to the routines in this file.
14410*/
14411SQLITE_PRIVATE void sqlite3MemSetDefault(void){
14412  static const sqlite3_mem_methods defaultMethods = {
14413     sqlite3MemMalloc,
14414     sqlite3MemFree,
14415     sqlite3MemRealloc,
14416     sqlite3MemSize,
14417     sqlite3MemRoundup,
14418     sqlite3MemInit,
14419     sqlite3MemShutdown,
14420     0
14421  };
14422  sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
14423}
14424
14425#endif /* SQLITE_ZERO_MALLOC */
14426
14427/************** End of mem0.c ************************************************/
14428/************** Begin file mem1.c ********************************************/
14429/*
14430** 2007 August 14
14431**
14432** The author disclaims copyright to this source code.  In place of
14433** a legal notice, here is a blessing:
14434**
14435**    May you do good and not evil.
14436**    May you find forgiveness for yourself and forgive others.
14437**    May you share freely, never taking more than you give.
14438**
14439*************************************************************************
14440**
14441** This file contains low-level memory allocation drivers for when
14442** SQLite will use the standard C-library malloc/realloc/free interface
14443** to obtain the memory it needs.
14444**
14445** This file contains implementations of the low-level memory allocation
14446** routines specified in the sqlite3_mem_methods object.
14447*/
14448
14449/*
14450** This version of the memory allocator is the default.  It is
14451** used when no other memory allocator is specified using compile-time
14452** macros.
14453*/
14454#ifdef SQLITE_SYSTEM_MALLOC
14455
14456/*
14457** Like malloc(), but remember the size of the allocation
14458** so that we can find it later using sqlite3MemSize().
14459**
14460** For this low-level routine, we are guaranteed that nByte>0 because
14461** cases of nByte<=0 will be intercepted and dealt with by higher level
14462** routines.
14463*/
14464static void *sqlite3MemMalloc(int nByte){
14465  sqlite3_int64 *p;
14466  assert( nByte>0 );
14467  nByte = ROUND8(nByte);
14468  p = malloc( nByte+8 );
14469  if( p ){
14470    p[0] = nByte;
14471    p++;
14472  }else{
14473    testcase( sqlite3GlobalConfig.xLog!=0 );
14474    sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes of memory", nByte);
14475  }
14476  return (void *)p;
14477}
14478
14479/*
14480** Like free() but works for allocations obtained from sqlite3MemMalloc()
14481** or sqlite3MemRealloc().
14482**
14483** For this low-level routine, we already know that pPrior!=0 since
14484** cases where pPrior==0 will have been intecepted and dealt with
14485** by higher-level routines.
14486*/
14487static void sqlite3MemFree(void *pPrior){
14488  sqlite3_int64 *p = (sqlite3_int64*)pPrior;
14489  assert( pPrior!=0 );
14490  p--;
14491  free(p);
14492}
14493
14494/*
14495** Report the allocated size of a prior return from xMalloc()
14496** or xRealloc().
14497*/
14498static int sqlite3MemSize(void *pPrior){
14499  sqlite3_int64 *p;
14500  if( pPrior==0 ) return 0;
14501  p = (sqlite3_int64*)pPrior;
14502  p--;
14503  return (int)p[0];
14504}
14505
14506/*
14507** Like realloc().  Resize an allocation previously obtained from
14508** sqlite3MemMalloc().
14509**
14510** For this low-level interface, we know that pPrior!=0.  Cases where
14511** pPrior==0 while have been intercepted by higher-level routine and
14512** redirected to xMalloc.  Similarly, we know that nByte>0 becauses
14513** cases where nByte<=0 will have been intercepted by higher-level
14514** routines and redirected to xFree.
14515*/
14516static void *sqlite3MemRealloc(void *pPrior, int nByte){
14517  sqlite3_int64 *p = (sqlite3_int64*)pPrior;
14518  assert( pPrior!=0 && nByte>0 );
14519  assert( nByte==ROUND8(nByte) ); /* EV: R-46199-30249 */
14520  p--;
14521  p = realloc(p, nByte+8 );
14522  if( p ){
14523    p[0] = nByte;
14524    p++;
14525  }else{
14526    testcase( sqlite3GlobalConfig.xLog!=0 );
14527    sqlite3_log(SQLITE_NOMEM,
14528      "failed memory resize %u to %u bytes",
14529      sqlite3MemSize(pPrior), nByte);
14530  }
14531  return (void*)p;
14532}
14533
14534/*
14535** Round up a request size to the next valid allocation size.
14536*/
14537static int sqlite3MemRoundup(int n){
14538  return ROUND8(n);
14539}
14540
14541/*
14542** Initialize this module.
14543*/
14544static int sqlite3MemInit(void *NotUsed){
14545  UNUSED_PARAMETER(NotUsed);
14546  return SQLITE_OK;
14547}
14548
14549/*
14550** Deinitialize this module.
14551*/
14552static void sqlite3MemShutdown(void *NotUsed){
14553  UNUSED_PARAMETER(NotUsed);
14554  return;
14555}
14556
14557/*
14558** This routine is the only routine in this file with external linkage.
14559**
14560** Populate the low-level memory allocation function pointers in
14561** sqlite3GlobalConfig.m with pointers to the routines in this file.
14562*/
14563SQLITE_PRIVATE void sqlite3MemSetDefault(void){
14564  static const sqlite3_mem_methods defaultMethods = {
14565     sqlite3MemMalloc,
14566     sqlite3MemFree,
14567     sqlite3MemRealloc,
14568     sqlite3MemSize,
14569     sqlite3MemRoundup,
14570     sqlite3MemInit,
14571     sqlite3MemShutdown,
14572     0
14573  };
14574  sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
14575}
14576
14577#endif /* SQLITE_SYSTEM_MALLOC */
14578
14579/************** End of mem1.c ************************************************/
14580/************** Begin file mem2.c ********************************************/
14581/*
14582** 2007 August 15
14583**
14584** The author disclaims copyright to this source code.  In place of
14585** a legal notice, here is a blessing:
14586**
14587**    May you do good and not evil.
14588**    May you find forgiveness for yourself and forgive others.
14589**    May you share freely, never taking more than you give.
14590**
14591*************************************************************************
14592**
14593** This file contains low-level memory allocation drivers for when
14594** SQLite will use the standard C-library malloc/realloc/free interface
14595** to obtain the memory it needs while adding lots of additional debugging
14596** information to each allocation in order to help detect and fix memory
14597** leaks and memory usage errors.
14598**
14599** This file contains implementations of the low-level memory allocation
14600** routines specified in the sqlite3_mem_methods object.
14601*/
14602
14603/*
14604** This version of the memory allocator is used only if the
14605** SQLITE_MEMDEBUG macro is defined
14606*/
14607#ifdef SQLITE_MEMDEBUG
14608
14609/*
14610** The backtrace functionality is only available with GLIBC
14611*/
14612#ifdef __GLIBC__
14613  extern int backtrace(void**,int);
14614  extern void backtrace_symbols_fd(void*const*,int,int);
14615#else
14616# define backtrace(A,B) 1
14617# define backtrace_symbols_fd(A,B,C)
14618#endif
14619
14620/*
14621** Each memory allocation looks like this:
14622**
14623**  ------------------------------------------------------------------------
14624**  | Title |  backtrace pointers |  MemBlockHdr |  allocation |  EndGuard |
14625**  ------------------------------------------------------------------------
14626**
14627** The application code sees only a pointer to the allocation.  We have
14628** to back up from the allocation pointer to find the MemBlockHdr.  The
14629** MemBlockHdr tells us the size of the allocation and the number of
14630** backtrace pointers.  There is also a guard word at the end of the
14631** MemBlockHdr.
14632*/
14633struct MemBlockHdr {
14634  i64 iSize;                          /* Size of this allocation */
14635  struct MemBlockHdr *pNext, *pPrev;  /* Linked list of all unfreed memory */
14636  char nBacktrace;                    /* Number of backtraces on this alloc */
14637  char nBacktraceSlots;               /* Available backtrace slots */
14638  u8 nTitle;                          /* Bytes of title; includes '\0' */
14639  u8 eType;                           /* Allocation type code */
14640  int iForeGuard;                     /* Guard word for sanity */
14641};
14642
14643/*
14644** Guard words
14645*/
14646#define FOREGUARD 0x80F5E153
14647#define REARGUARD 0xE4676B53
14648
14649/*
14650** Number of malloc size increments to track.
14651*/
14652#define NCSIZE  1000
14653
14654/*
14655** All of the static variables used by this module are collected
14656** into a single structure named "mem".  This is to keep the
14657** static variables organized and to reduce namespace pollution
14658** when this module is combined with other in the amalgamation.
14659*/
14660static struct {
14661
14662  /*
14663  ** Mutex to control access to the memory allocation subsystem.
14664  */
14665  sqlite3_mutex *mutex;
14666
14667  /*
14668  ** Head and tail of a linked list of all outstanding allocations
14669  */
14670  struct MemBlockHdr *pFirst;
14671  struct MemBlockHdr *pLast;
14672
14673  /*
14674  ** The number of levels of backtrace to save in new allocations.
14675  */
14676  int nBacktrace;
14677  void (*xBacktrace)(int, int, void **);
14678
14679  /*
14680  ** Title text to insert in front of each block
14681  */
14682  int nTitle;        /* Bytes of zTitle to save.  Includes '\0' and padding */
14683  char zTitle[100];  /* The title text */
14684
14685  /*
14686  ** sqlite3MallocDisallow() increments the following counter.
14687  ** sqlite3MallocAllow() decrements it.
14688  */
14689  int disallow; /* Do not allow memory allocation */
14690
14691  /*
14692  ** Gather statistics on the sizes of memory allocations.
14693  ** nAlloc[i] is the number of allocation attempts of i*8
14694  ** bytes.  i==NCSIZE is the number of allocation attempts for
14695  ** sizes more than NCSIZE*8 bytes.
14696  */
14697  int nAlloc[NCSIZE];      /* Total number of allocations */
14698  int nCurrent[NCSIZE];    /* Current number of allocations */
14699  int mxCurrent[NCSIZE];   /* Highwater mark for nCurrent */
14700
14701} mem;
14702
14703
14704/*
14705** Adjust memory usage statistics
14706*/
14707static void adjustStats(int iSize, int increment){
14708  int i = ROUND8(iSize)/8;
14709  if( i>NCSIZE-1 ){
14710    i = NCSIZE - 1;
14711  }
14712  if( increment>0 ){
14713    mem.nAlloc[i]++;
14714    mem.nCurrent[i]++;
14715    if( mem.nCurrent[i]>mem.mxCurrent[i] ){
14716      mem.mxCurrent[i] = mem.nCurrent[i];
14717    }
14718  }else{
14719    mem.nCurrent[i]--;
14720    assert( mem.nCurrent[i]>=0 );
14721  }
14722}
14723
14724/*
14725** Given an allocation, find the MemBlockHdr for that allocation.
14726**
14727** This routine checks the guards at either end of the allocation and
14728** if they are incorrect it asserts.
14729*/
14730static struct MemBlockHdr *sqlite3MemsysGetHeader(void *pAllocation){
14731  struct MemBlockHdr *p;
14732  int *pInt;
14733  u8 *pU8;
14734  int nReserve;
14735
14736  p = (struct MemBlockHdr*)pAllocation;
14737  p--;
14738  assert( p->iForeGuard==(int)FOREGUARD );
14739  nReserve = ROUND8(p->iSize);
14740  pInt = (int*)pAllocation;
14741  pU8 = (u8*)pAllocation;
14742  assert( pInt[nReserve/sizeof(int)]==(int)REARGUARD );
14743  /* This checks any of the "extra" bytes allocated due
14744  ** to rounding up to an 8 byte boundary to ensure
14745  ** they haven't been overwritten.
14746  */
14747  while( nReserve-- > p->iSize ) assert( pU8[nReserve]==0x65 );
14748  return p;
14749}
14750
14751/*
14752** Return the number of bytes currently allocated at address p.
14753*/
14754static int sqlite3MemSize(void *p){
14755  struct MemBlockHdr *pHdr;
14756  if( !p ){
14757    return 0;
14758  }
14759  pHdr = sqlite3MemsysGetHeader(p);
14760  return pHdr->iSize;
14761}
14762
14763/*
14764** Initialize the memory allocation subsystem.
14765*/
14766static int sqlite3MemInit(void *NotUsed){
14767  UNUSED_PARAMETER(NotUsed);
14768  assert( (sizeof(struct MemBlockHdr)&7) == 0 );
14769  if( !sqlite3GlobalConfig.bMemstat ){
14770    /* If memory status is enabled, then the malloc.c wrapper will already
14771    ** hold the STATIC_MEM mutex when the routines here are invoked. */
14772    mem.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
14773  }
14774  return SQLITE_OK;
14775}
14776
14777/*
14778** Deinitialize the memory allocation subsystem.
14779*/
14780static void sqlite3MemShutdown(void *NotUsed){
14781  UNUSED_PARAMETER(NotUsed);
14782  mem.mutex = 0;
14783}
14784
14785/*
14786** Round up a request size to the next valid allocation size.
14787*/
14788static int sqlite3MemRoundup(int n){
14789  return ROUND8(n);
14790}
14791
14792/*
14793** Fill a buffer with pseudo-random bytes.  This is used to preset
14794** the content of a new memory allocation to unpredictable values and
14795** to clear the content of a freed allocation to unpredictable values.
14796*/
14797static void randomFill(char *pBuf, int nByte){
14798  unsigned int x, y, r;
14799  x = SQLITE_PTR_TO_INT(pBuf);
14800  y = nByte | 1;
14801  while( nByte >= 4 ){
14802    x = (x>>1) ^ (-(x&1) & 0xd0000001);
14803    y = y*1103515245 + 12345;
14804    r = x ^ y;
14805    *(int*)pBuf = r;
14806    pBuf += 4;
14807    nByte -= 4;
14808  }
14809  while( nByte-- > 0 ){
14810    x = (x>>1) ^ (-(x&1) & 0xd0000001);
14811    y = y*1103515245 + 12345;
14812    r = x ^ y;
14813    *(pBuf++) = r & 0xff;
14814  }
14815}
14816
14817/*
14818** Allocate nByte bytes of memory.
14819*/
14820static void *sqlite3MemMalloc(int nByte){
14821  struct MemBlockHdr *pHdr;
14822  void **pBt;
14823  char *z;
14824  int *pInt;
14825  void *p = 0;
14826  int totalSize;
14827  int nReserve;
14828  sqlite3_mutex_enter(mem.mutex);
14829  assert( mem.disallow==0 );
14830  nReserve = ROUND8(nByte);
14831  totalSize = nReserve + sizeof(*pHdr) + sizeof(int) +
14832               mem.nBacktrace*sizeof(void*) + mem.nTitle;
14833  p = malloc(totalSize);
14834  if( p ){
14835    z = p;
14836    pBt = (void**)&z[mem.nTitle];
14837    pHdr = (struct MemBlockHdr*)&pBt[mem.nBacktrace];
14838    pHdr->pNext = 0;
14839    pHdr->pPrev = mem.pLast;
14840    if( mem.pLast ){
14841      mem.pLast->pNext = pHdr;
14842    }else{
14843      mem.pFirst = pHdr;
14844    }
14845    mem.pLast = pHdr;
14846    pHdr->iForeGuard = FOREGUARD;
14847    pHdr->eType = MEMTYPE_HEAP;
14848    pHdr->nBacktraceSlots = mem.nBacktrace;
14849    pHdr->nTitle = mem.nTitle;
14850    if( mem.nBacktrace ){
14851      void *aAddr[40];
14852      pHdr->nBacktrace = backtrace(aAddr, mem.nBacktrace+1)-1;
14853      memcpy(pBt, &aAddr[1], pHdr->nBacktrace*sizeof(void*));
14854      assert(pBt[0]);
14855      if( mem.xBacktrace ){
14856        mem.xBacktrace(nByte, pHdr->nBacktrace-1, &aAddr[1]);
14857      }
14858    }else{
14859      pHdr->nBacktrace = 0;
14860    }
14861    if( mem.nTitle ){
14862      memcpy(z, mem.zTitle, mem.nTitle);
14863    }
14864    pHdr->iSize = nByte;
14865    adjustStats(nByte, +1);
14866    pInt = (int*)&pHdr[1];
14867    pInt[nReserve/sizeof(int)] = REARGUARD;
14868    randomFill((char*)pInt, nByte);
14869    memset(((char*)pInt)+nByte, 0x65, nReserve-nByte);
14870    p = (void*)pInt;
14871  }
14872  sqlite3_mutex_leave(mem.mutex);
14873  return p;
14874}
14875
14876/*
14877** Free memory.
14878*/
14879static void sqlite3MemFree(void *pPrior){
14880  struct MemBlockHdr *pHdr;
14881  void **pBt;
14882  char *z;
14883  assert( sqlite3GlobalConfig.bMemstat || sqlite3GlobalConfig.bCoreMutex==0
14884       || mem.mutex!=0 );
14885  pHdr = sqlite3MemsysGetHeader(pPrior);
14886  pBt = (void**)pHdr;
14887  pBt -= pHdr->nBacktraceSlots;
14888  sqlite3_mutex_enter(mem.mutex);
14889  if( pHdr->pPrev ){
14890    assert( pHdr->pPrev->pNext==pHdr );
14891    pHdr->pPrev->pNext = pHdr->pNext;
14892  }else{
14893    assert( mem.pFirst==pHdr );
14894    mem.pFirst = pHdr->pNext;
14895  }
14896  if( pHdr->pNext ){
14897    assert( pHdr->pNext->pPrev==pHdr );
14898    pHdr->pNext->pPrev = pHdr->pPrev;
14899  }else{
14900    assert( mem.pLast==pHdr );
14901    mem.pLast = pHdr->pPrev;
14902  }
14903  z = (char*)pBt;
14904  z -= pHdr->nTitle;
14905  adjustStats(pHdr->iSize, -1);
14906  randomFill(z, sizeof(void*)*pHdr->nBacktraceSlots + sizeof(*pHdr) +
14907                pHdr->iSize + sizeof(int) + pHdr->nTitle);
14908  free(z);
14909  sqlite3_mutex_leave(mem.mutex);
14910}
14911
14912/*
14913** Change the size of an existing memory allocation.
14914**
14915** For this debugging implementation, we *always* make a copy of the
14916** allocation into a new place in memory.  In this way, if the
14917** higher level code is using pointer to the old allocation, it is
14918** much more likely to break and we are much more liking to find
14919** the error.
14920*/
14921static void *sqlite3MemRealloc(void *pPrior, int nByte){
14922  struct MemBlockHdr *pOldHdr;
14923  void *pNew;
14924  assert( mem.disallow==0 );
14925  assert( (nByte & 7)==0 );     /* EV: R-46199-30249 */
14926  pOldHdr = sqlite3MemsysGetHeader(pPrior);
14927  pNew = sqlite3MemMalloc(nByte);
14928  if( pNew ){
14929    memcpy(pNew, pPrior, nByte<pOldHdr->iSize ? nByte : pOldHdr->iSize);
14930    if( nByte>pOldHdr->iSize ){
14931      randomFill(&((char*)pNew)[pOldHdr->iSize], nByte - pOldHdr->iSize);
14932    }
14933    sqlite3MemFree(pPrior);
14934  }
14935  return pNew;
14936}
14937
14938/*
14939** Populate the low-level memory allocation function pointers in
14940** sqlite3GlobalConfig.m with pointers to the routines in this file.
14941*/
14942SQLITE_PRIVATE void sqlite3MemSetDefault(void){
14943  static const sqlite3_mem_methods defaultMethods = {
14944     sqlite3MemMalloc,
14945     sqlite3MemFree,
14946     sqlite3MemRealloc,
14947     sqlite3MemSize,
14948     sqlite3MemRoundup,
14949     sqlite3MemInit,
14950     sqlite3MemShutdown,
14951     0
14952  };
14953  sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
14954}
14955
14956/*
14957** Set the "type" of an allocation.
14958*/
14959SQLITE_PRIVATE void sqlite3MemdebugSetType(void *p, u8 eType){
14960  if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){
14961    struct MemBlockHdr *pHdr;
14962    pHdr = sqlite3MemsysGetHeader(p);
14963    assert( pHdr->iForeGuard==FOREGUARD );
14964    pHdr->eType = eType;
14965  }
14966}
14967
14968/*
14969** Return TRUE if the mask of type in eType matches the type of the
14970** allocation p.  Also return true if p==NULL.
14971**
14972** This routine is designed for use within an assert() statement, to
14973** verify the type of an allocation.  For example:
14974**
14975**     assert( sqlite3MemdebugHasType(p, MEMTYPE_DB) );
14976*/
14977SQLITE_PRIVATE int sqlite3MemdebugHasType(void *p, u8 eType){
14978  int rc = 1;
14979  if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){
14980    struct MemBlockHdr *pHdr;
14981    pHdr = sqlite3MemsysGetHeader(p);
14982    assert( pHdr->iForeGuard==FOREGUARD );         /* Allocation is valid */
14983    if( (pHdr->eType&eType)==0 ){
14984      rc = 0;
14985    }
14986  }
14987  return rc;
14988}
14989
14990/*
14991** Return TRUE if the mask of type in eType matches no bits of the type of the
14992** allocation p.  Also return true if p==NULL.
14993**
14994** This routine is designed for use within an assert() statement, to
14995** verify the type of an allocation.  For example:
14996**
14997**     assert( sqlite3MemdebugNoType(p, MEMTYPE_DB) );
14998*/
14999SQLITE_PRIVATE int sqlite3MemdebugNoType(void *p, u8 eType){
15000  int rc = 1;
15001  if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){
15002    struct MemBlockHdr *pHdr;
15003    pHdr = sqlite3MemsysGetHeader(p);
15004    assert( pHdr->iForeGuard==FOREGUARD );         /* Allocation is valid */
15005    if( (pHdr->eType&eType)!=0 ){
15006      rc = 0;
15007    }
15008  }
15009  return rc;
15010}
15011
15012/*
15013** Set the number of backtrace levels kept for each allocation.
15014** A value of zero turns off backtracing.  The number is always rounded
15015** up to a multiple of 2.
15016*/
15017SQLITE_PRIVATE void sqlite3MemdebugBacktrace(int depth){
15018  if( depth<0 ){ depth = 0; }
15019  if( depth>20 ){ depth = 20; }
15020  depth = (depth+1)&0xfe;
15021  mem.nBacktrace = depth;
15022}
15023
15024SQLITE_PRIVATE void sqlite3MemdebugBacktraceCallback(void (*xBacktrace)(int, int, void **)){
15025  mem.xBacktrace = xBacktrace;
15026}
15027
15028/*
15029** Set the title string for subsequent allocations.
15030*/
15031SQLITE_PRIVATE void sqlite3MemdebugSettitle(const char *zTitle){
15032  unsigned int n = sqlite3Strlen30(zTitle) + 1;
15033  sqlite3_mutex_enter(mem.mutex);
15034  if( n>=sizeof(mem.zTitle) ) n = sizeof(mem.zTitle)-1;
15035  memcpy(mem.zTitle, zTitle, n);
15036  mem.zTitle[n] = 0;
15037  mem.nTitle = ROUND8(n);
15038  sqlite3_mutex_leave(mem.mutex);
15039}
15040
15041SQLITE_PRIVATE void sqlite3MemdebugSync(){
15042  struct MemBlockHdr *pHdr;
15043  for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){
15044    void **pBt = (void**)pHdr;
15045    pBt -= pHdr->nBacktraceSlots;
15046    mem.xBacktrace(pHdr->iSize, pHdr->nBacktrace-1, &pBt[1]);
15047  }
15048}
15049
15050/*
15051** Open the file indicated and write a log of all unfreed memory
15052** allocations into that log.
15053*/
15054SQLITE_PRIVATE void sqlite3MemdebugDump(const char *zFilename){
15055  FILE *out;
15056  struct MemBlockHdr *pHdr;
15057  void **pBt;
15058  int i;
15059  out = fopen(zFilename, "w");
15060  if( out==0 ){
15061    fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
15062                    zFilename);
15063    return;
15064  }
15065  for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){
15066    char *z = (char*)pHdr;
15067    z -= pHdr->nBacktraceSlots*sizeof(void*) + pHdr->nTitle;
15068    fprintf(out, "**** %lld bytes at %p from %s ****\n",
15069            pHdr->iSize, &pHdr[1], pHdr->nTitle ? z : "???");
15070    if( pHdr->nBacktrace ){
15071      fflush(out);
15072      pBt = (void**)pHdr;
15073      pBt -= pHdr->nBacktraceSlots;
15074      backtrace_symbols_fd(pBt, pHdr->nBacktrace, fileno(out));
15075      fprintf(out, "\n");
15076    }
15077  }
15078  fprintf(out, "COUNTS:\n");
15079  for(i=0; i<NCSIZE-1; i++){
15080    if( mem.nAlloc[i] ){
15081      fprintf(out, "   %5d: %10d %10d %10d\n",
15082            i*8, mem.nAlloc[i], mem.nCurrent[i], mem.mxCurrent[i]);
15083    }
15084  }
15085  if( mem.nAlloc[NCSIZE-1] ){
15086    fprintf(out, "   %5d: %10d %10d %10d\n",
15087             NCSIZE*8-8, mem.nAlloc[NCSIZE-1],
15088             mem.nCurrent[NCSIZE-1], mem.mxCurrent[NCSIZE-1]);
15089  }
15090  fclose(out);
15091}
15092
15093/*
15094** Return the number of times sqlite3MemMalloc() has been called.
15095*/
15096SQLITE_PRIVATE int sqlite3MemdebugMallocCount(){
15097  int i;
15098  int nTotal = 0;
15099  for(i=0; i<NCSIZE; i++){
15100    nTotal += mem.nAlloc[i];
15101  }
15102  return nTotal;
15103}
15104
15105
15106#endif /* SQLITE_MEMDEBUG */
15107
15108/************** End of mem2.c ************************************************/
15109/************** Begin file mem3.c ********************************************/
15110/*
15111** 2007 October 14
15112**
15113** The author disclaims copyright to this source code.  In place of
15114** a legal notice, here is a blessing:
15115**
15116**    May you do good and not evil.
15117**    May you find forgiveness for yourself and forgive others.
15118**    May you share freely, never taking more than you give.
15119**
15120*************************************************************************
15121** This file contains the C functions that implement a memory
15122** allocation subsystem for use by SQLite.
15123**
15124** This version of the memory allocation subsystem omits all
15125** use of malloc(). The SQLite user supplies a block of memory
15126** before calling sqlite3_initialize() from which allocations
15127** are made and returned by the xMalloc() and xRealloc()
15128** implementations. Once sqlite3_initialize() has been called,
15129** the amount of memory available to SQLite is fixed and cannot
15130** be changed.
15131**
15132** This version of the memory allocation subsystem is included
15133** in the build only if SQLITE_ENABLE_MEMSYS3 is defined.
15134*/
15135
15136/*
15137** This version of the memory allocator is only built into the library
15138** SQLITE_ENABLE_MEMSYS3 is defined. Defining this symbol does not
15139** mean that the library will use a memory-pool by default, just that
15140** it is available. The mempool allocator is activated by calling
15141** sqlite3_config().
15142*/
15143#ifdef SQLITE_ENABLE_MEMSYS3
15144
15145/*
15146** Maximum size (in Mem3Blocks) of a "small" chunk.
15147*/
15148#define MX_SMALL 10
15149
15150
15151/*
15152** Number of freelist hash slots
15153*/
15154#define N_HASH  61
15155
15156/*
15157** A memory allocation (also called a "chunk") consists of two or
15158** more blocks where each block is 8 bytes.  The first 8 bytes are
15159** a header that is not returned to the user.
15160**
15161** A chunk is two or more blocks that is either checked out or
15162** free.  The first block has format u.hdr.  u.hdr.size4x is 4 times the
15163** size of the allocation in blocks if the allocation is free.
15164** The u.hdr.size4x&1 bit is true if the chunk is checked out and
15165** false if the chunk is on the freelist.  The u.hdr.size4x&2 bit
15166** is true if the previous chunk is checked out and false if the
15167** previous chunk is free.  The u.hdr.prevSize field is the size of
15168** the previous chunk in blocks if the previous chunk is on the
15169** freelist. If the previous chunk is checked out, then
15170** u.hdr.prevSize can be part of the data for that chunk and should
15171** not be read or written.
15172**
15173** We often identify a chunk by its index in mem3.aPool[].  When
15174** this is done, the chunk index refers to the second block of
15175** the chunk.  In this way, the first chunk has an index of 1.
15176** A chunk index of 0 means "no such chunk" and is the equivalent
15177** of a NULL pointer.
15178**
15179** The second block of free chunks is of the form u.list.  The
15180** two fields form a double-linked list of chunks of related sizes.
15181** Pointers to the head of the list are stored in mem3.aiSmall[]
15182** for smaller chunks and mem3.aiHash[] for larger chunks.
15183**
15184** The second block of a chunk is user data if the chunk is checked
15185** out.  If a chunk is checked out, the user data may extend into
15186** the u.hdr.prevSize value of the following chunk.
15187*/
15188typedef struct Mem3Block Mem3Block;
15189struct Mem3Block {
15190  union {
15191    struct {
15192      u32 prevSize;   /* Size of previous chunk in Mem3Block elements */
15193      u32 size4x;     /* 4x the size of current chunk in Mem3Block elements */
15194    } hdr;
15195    struct {
15196      u32 next;       /* Index in mem3.aPool[] of next free chunk */
15197      u32 prev;       /* Index in mem3.aPool[] of previous free chunk */
15198    } list;
15199  } u;
15200};
15201
15202/*
15203** All of the static variables used by this module are collected
15204** into a single structure named "mem3".  This is to keep the
15205** static variables organized and to reduce namespace pollution
15206** when this module is combined with other in the amalgamation.
15207*/
15208static SQLITE_WSD struct Mem3Global {
15209  /*
15210  ** Memory available for allocation. nPool is the size of the array
15211  ** (in Mem3Blocks) pointed to by aPool less 2.
15212  */
15213  u32 nPool;
15214  Mem3Block *aPool;
15215
15216  /*
15217  ** True if we are evaluating an out-of-memory callback.
15218  */
15219  int alarmBusy;
15220
15221  /*
15222  ** Mutex to control access to the memory allocation subsystem.
15223  */
15224  sqlite3_mutex *mutex;
15225
15226  /*
15227  ** The minimum amount of free space that we have seen.
15228  */
15229  u32 mnMaster;
15230
15231  /*
15232  ** iMaster is the index of the master chunk.  Most new allocations
15233  ** occur off of this chunk.  szMaster is the size (in Mem3Blocks)
15234  ** of the current master.  iMaster is 0 if there is not master chunk.
15235  ** The master chunk is not in either the aiHash[] or aiSmall[].
15236  */
15237  u32 iMaster;
15238  u32 szMaster;
15239
15240  /*
15241  ** Array of lists of free blocks according to the block size
15242  ** for smaller chunks, or a hash on the block size for larger
15243  ** chunks.
15244  */
15245  u32 aiSmall[MX_SMALL-1];   /* For sizes 2 through MX_SMALL, inclusive */
15246  u32 aiHash[N_HASH];        /* For sizes MX_SMALL+1 and larger */
15247} mem3 = { 97535575 };
15248
15249#define mem3 GLOBAL(struct Mem3Global, mem3)
15250
15251/*
15252** Unlink the chunk at mem3.aPool[i] from list it is currently
15253** on.  *pRoot is the list that i is a member of.
15254*/
15255static void memsys3UnlinkFromList(u32 i, u32 *pRoot){
15256  u32 next = mem3.aPool[i].u.list.next;
15257  u32 prev = mem3.aPool[i].u.list.prev;
15258  assert( sqlite3_mutex_held(mem3.mutex) );
15259  if( prev==0 ){
15260    *pRoot = next;
15261  }else{
15262    mem3.aPool[prev].u.list.next = next;
15263  }
15264  if( next ){
15265    mem3.aPool[next].u.list.prev = prev;
15266  }
15267  mem3.aPool[i].u.list.next = 0;
15268  mem3.aPool[i].u.list.prev = 0;
15269}
15270
15271/*
15272** Unlink the chunk at index i from
15273** whatever list is currently a member of.
15274*/
15275static void memsys3Unlink(u32 i){
15276  u32 size, hash;
15277  assert( sqlite3_mutex_held(mem3.mutex) );
15278  assert( (mem3.aPool[i-1].u.hdr.size4x & 1)==0 );
15279  assert( i>=1 );
15280  size = mem3.aPool[i-1].u.hdr.size4x/4;
15281  assert( size==mem3.aPool[i+size-1].u.hdr.prevSize );
15282  assert( size>=2 );
15283  if( size <= MX_SMALL ){
15284    memsys3UnlinkFromList(i, &mem3.aiSmall[size-2]);
15285  }else{
15286    hash = size % N_HASH;
15287    memsys3UnlinkFromList(i, &mem3.aiHash[hash]);
15288  }
15289}
15290
15291/*
15292** Link the chunk at mem3.aPool[i] so that is on the list rooted
15293** at *pRoot.
15294*/
15295static void memsys3LinkIntoList(u32 i, u32 *pRoot){
15296  assert( sqlite3_mutex_held(mem3.mutex) );
15297  mem3.aPool[i].u.list.next = *pRoot;
15298  mem3.aPool[i].u.list.prev = 0;
15299  if( *pRoot ){
15300    mem3.aPool[*pRoot].u.list.prev = i;
15301  }
15302  *pRoot = i;
15303}
15304
15305/*
15306** Link the chunk at index i into either the appropriate
15307** small chunk list, or into the large chunk hash table.
15308*/
15309static void memsys3Link(u32 i){
15310  u32 size, hash;
15311  assert( sqlite3_mutex_held(mem3.mutex) );
15312  assert( i>=1 );
15313  assert( (mem3.aPool[i-1].u.hdr.size4x & 1)==0 );
15314  size = mem3.aPool[i-1].u.hdr.size4x/4;
15315  assert( size==mem3.aPool[i+size-1].u.hdr.prevSize );
15316  assert( size>=2 );
15317  if( size <= MX_SMALL ){
15318    memsys3LinkIntoList(i, &mem3.aiSmall[size-2]);
15319  }else{
15320    hash = size % N_HASH;
15321    memsys3LinkIntoList(i, &mem3.aiHash[hash]);
15322  }
15323}
15324
15325/*
15326** If the STATIC_MEM mutex is not already held, obtain it now. The mutex
15327** will already be held (obtained by code in malloc.c) if
15328** sqlite3GlobalConfig.bMemStat is true.
15329*/
15330static void memsys3Enter(void){
15331  if( sqlite3GlobalConfig.bMemstat==0 && mem3.mutex==0 ){
15332    mem3.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
15333  }
15334  sqlite3_mutex_enter(mem3.mutex);
15335}
15336static void memsys3Leave(void){
15337  sqlite3_mutex_leave(mem3.mutex);
15338}
15339
15340/*
15341** Called when we are unable to satisfy an allocation of nBytes.
15342*/
15343static void memsys3OutOfMemory(int nByte){
15344  if( !mem3.alarmBusy ){
15345    mem3.alarmBusy = 1;
15346    assert( sqlite3_mutex_held(mem3.mutex) );
15347    sqlite3_mutex_leave(mem3.mutex);
15348    sqlite3_release_memory(nByte);
15349    sqlite3_mutex_enter(mem3.mutex);
15350    mem3.alarmBusy = 0;
15351  }
15352}
15353
15354
15355/*
15356** Chunk i is a free chunk that has been unlinked.  Adjust its
15357** size parameters for check-out and return a pointer to the
15358** user portion of the chunk.
15359*/
15360static void *memsys3Checkout(u32 i, u32 nBlock){
15361  u32 x;
15362  assert( sqlite3_mutex_held(mem3.mutex) );
15363  assert( i>=1 );
15364  assert( mem3.aPool[i-1].u.hdr.size4x/4==nBlock );
15365  assert( mem3.aPool[i+nBlock-1].u.hdr.prevSize==nBlock );
15366  x = mem3.aPool[i-1].u.hdr.size4x;
15367  mem3.aPool[i-1].u.hdr.size4x = nBlock*4 | 1 | (x&2);
15368  mem3.aPool[i+nBlock-1].u.hdr.prevSize = nBlock;
15369  mem3.aPool[i+nBlock-1].u.hdr.size4x |= 2;
15370  return &mem3.aPool[i];
15371}
15372
15373/*
15374** Carve a piece off of the end of the mem3.iMaster free chunk.
15375** Return a pointer to the new allocation.  Or, if the master chunk
15376** is not large enough, return 0.
15377*/
15378static void *memsys3FromMaster(u32 nBlock){
15379  assert( sqlite3_mutex_held(mem3.mutex) );
15380  assert( mem3.szMaster>=nBlock );
15381  if( nBlock>=mem3.szMaster-1 ){
15382    /* Use the entire master */
15383    void *p = memsys3Checkout(mem3.iMaster, mem3.szMaster);
15384    mem3.iMaster = 0;
15385    mem3.szMaster = 0;
15386    mem3.mnMaster = 0;
15387    return p;
15388  }else{
15389    /* Split the master block.  Return the tail. */
15390    u32 newi, x;
15391    newi = mem3.iMaster + mem3.szMaster - nBlock;
15392    assert( newi > mem3.iMaster+1 );
15393    mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = nBlock;
15394    mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x |= 2;
15395    mem3.aPool[newi-1].u.hdr.size4x = nBlock*4 + 1;
15396    mem3.szMaster -= nBlock;
15397    mem3.aPool[newi-1].u.hdr.prevSize = mem3.szMaster;
15398    x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
15399    mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
15400    if( mem3.szMaster < mem3.mnMaster ){
15401      mem3.mnMaster = mem3.szMaster;
15402    }
15403    return (void*)&mem3.aPool[newi];
15404  }
15405}
15406
15407/*
15408** *pRoot is the head of a list of free chunks of the same size
15409** or same size hash.  In other words, *pRoot is an entry in either
15410** mem3.aiSmall[] or mem3.aiHash[].
15411**
15412** This routine examines all entries on the given list and tries
15413** to coalesce each entries with adjacent free chunks.
15414**
15415** If it sees a chunk that is larger than mem3.iMaster, it replaces
15416** the current mem3.iMaster with the new larger chunk.  In order for
15417** this mem3.iMaster replacement to work, the master chunk must be
15418** linked into the hash tables.  That is not the normal state of
15419** affairs, of course.  The calling routine must link the master
15420** chunk before invoking this routine, then must unlink the (possibly
15421** changed) master chunk once this routine has finished.
15422*/
15423static void memsys3Merge(u32 *pRoot){
15424  u32 iNext, prev, size, i, x;
15425
15426  assert( sqlite3_mutex_held(mem3.mutex) );
15427  for(i=*pRoot; i>0; i=iNext){
15428    iNext = mem3.aPool[i].u.list.next;
15429    size = mem3.aPool[i-1].u.hdr.size4x;
15430    assert( (size&1)==0 );
15431    if( (size&2)==0 ){
15432      memsys3UnlinkFromList(i, pRoot);
15433      assert( i > mem3.aPool[i-1].u.hdr.prevSize );
15434      prev = i - mem3.aPool[i-1].u.hdr.prevSize;
15435      if( prev==iNext ){
15436        iNext = mem3.aPool[prev].u.list.next;
15437      }
15438      memsys3Unlink(prev);
15439      size = i + size/4 - prev;
15440      x = mem3.aPool[prev-1].u.hdr.size4x & 2;
15441      mem3.aPool[prev-1].u.hdr.size4x = size*4 | x;
15442      mem3.aPool[prev+size-1].u.hdr.prevSize = size;
15443      memsys3Link(prev);
15444      i = prev;
15445    }else{
15446      size /= 4;
15447    }
15448    if( size>mem3.szMaster ){
15449      mem3.iMaster = i;
15450      mem3.szMaster = size;
15451    }
15452  }
15453}
15454
15455/*
15456** Return a block of memory of at least nBytes in size.
15457** Return NULL if unable.
15458**
15459** This function assumes that the necessary mutexes, if any, are
15460** already held by the caller. Hence "Unsafe".
15461*/
15462static void *memsys3MallocUnsafe(int nByte){
15463  u32 i;
15464  u32 nBlock;
15465  u32 toFree;
15466
15467  assert( sqlite3_mutex_held(mem3.mutex) );
15468  assert( sizeof(Mem3Block)==8 );
15469  if( nByte<=12 ){
15470    nBlock = 2;
15471  }else{
15472    nBlock = (nByte + 11)/8;
15473  }
15474  assert( nBlock>=2 );
15475
15476  /* STEP 1:
15477  ** Look for an entry of the correct size in either the small
15478  ** chunk table or in the large chunk hash table.  This is
15479  ** successful most of the time (about 9 times out of 10).
15480  */
15481  if( nBlock <= MX_SMALL ){
15482    i = mem3.aiSmall[nBlock-2];
15483    if( i>0 ){
15484      memsys3UnlinkFromList(i, &mem3.aiSmall[nBlock-2]);
15485      return memsys3Checkout(i, nBlock);
15486    }
15487  }else{
15488    int hash = nBlock % N_HASH;
15489    for(i=mem3.aiHash[hash]; i>0; i=mem3.aPool[i].u.list.next){
15490      if( mem3.aPool[i-1].u.hdr.size4x/4==nBlock ){
15491        memsys3UnlinkFromList(i, &mem3.aiHash[hash]);
15492        return memsys3Checkout(i, nBlock);
15493      }
15494    }
15495  }
15496
15497  /* STEP 2:
15498  ** Try to satisfy the allocation by carving a piece off of the end
15499  ** of the master chunk.  This step usually works if step 1 fails.
15500  */
15501  if( mem3.szMaster>=nBlock ){
15502    return memsys3FromMaster(nBlock);
15503  }
15504
15505
15506  /* STEP 3:
15507  ** Loop through the entire memory pool.  Coalesce adjacent free
15508  ** chunks.  Recompute the master chunk as the largest free chunk.
15509  ** Then try again to satisfy the allocation by carving a piece off
15510  ** of the end of the master chunk.  This step happens very
15511  ** rarely (we hope!)
15512  */
15513  for(toFree=nBlock*16; toFree<(mem3.nPool*16); toFree *= 2){
15514    memsys3OutOfMemory(toFree);
15515    if( mem3.iMaster ){
15516      memsys3Link(mem3.iMaster);
15517      mem3.iMaster = 0;
15518      mem3.szMaster = 0;
15519    }
15520    for(i=0; i<N_HASH; i++){
15521      memsys3Merge(&mem3.aiHash[i]);
15522    }
15523    for(i=0; i<MX_SMALL-1; i++){
15524      memsys3Merge(&mem3.aiSmall[i]);
15525    }
15526    if( mem3.szMaster ){
15527      memsys3Unlink(mem3.iMaster);
15528      if( mem3.szMaster>=nBlock ){
15529        return memsys3FromMaster(nBlock);
15530      }
15531    }
15532  }
15533
15534  /* If none of the above worked, then we fail. */
15535  return 0;
15536}
15537
15538/*
15539** Free an outstanding memory allocation.
15540**
15541** This function assumes that the necessary mutexes, if any, are
15542** already held by the caller. Hence "Unsafe".
15543*/
15544void memsys3FreeUnsafe(void *pOld){
15545  Mem3Block *p = (Mem3Block*)pOld;
15546  int i;
15547  u32 size, x;
15548  assert( sqlite3_mutex_held(mem3.mutex) );
15549  assert( p>mem3.aPool && p<&mem3.aPool[mem3.nPool] );
15550  i = p - mem3.aPool;
15551  assert( (mem3.aPool[i-1].u.hdr.size4x&1)==1 );
15552  size = mem3.aPool[i-1].u.hdr.size4x/4;
15553  assert( i+size<=mem3.nPool+1 );
15554  mem3.aPool[i-1].u.hdr.size4x &= ~1;
15555  mem3.aPool[i+size-1].u.hdr.prevSize = size;
15556  mem3.aPool[i+size-1].u.hdr.size4x &= ~2;
15557  memsys3Link(i);
15558
15559  /* Try to expand the master using the newly freed chunk */
15560  if( mem3.iMaster ){
15561    while( (mem3.aPool[mem3.iMaster-1].u.hdr.size4x&2)==0 ){
15562      size = mem3.aPool[mem3.iMaster-1].u.hdr.prevSize;
15563      mem3.iMaster -= size;
15564      mem3.szMaster += size;
15565      memsys3Unlink(mem3.iMaster);
15566      x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
15567      mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
15568      mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = mem3.szMaster;
15569    }
15570    x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
15571    while( (mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x&1)==0 ){
15572      memsys3Unlink(mem3.iMaster+mem3.szMaster);
15573      mem3.szMaster += mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x/4;
15574      mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
15575      mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = mem3.szMaster;
15576    }
15577  }
15578}
15579
15580/*
15581** Return the size of an outstanding allocation, in bytes.  The
15582** size returned omits the 8-byte header overhead.  This only
15583** works for chunks that are currently checked out.
15584*/
15585static int memsys3Size(void *p){
15586  Mem3Block *pBlock;
15587  if( p==0 ) return 0;
15588  pBlock = (Mem3Block*)p;
15589  assert( (pBlock[-1].u.hdr.size4x&1)!=0 );
15590  return (pBlock[-1].u.hdr.size4x&~3)*2 - 4;
15591}
15592
15593/*
15594** Round up a request size to the next valid allocation size.
15595*/
15596static int memsys3Roundup(int n){
15597  if( n<=12 ){
15598    return 12;
15599  }else{
15600    return ((n+11)&~7) - 4;
15601  }
15602}
15603
15604/*
15605** Allocate nBytes of memory.
15606*/
15607static void *memsys3Malloc(int nBytes){
15608  sqlite3_int64 *p;
15609  assert( nBytes>0 );          /* malloc.c filters out 0 byte requests */
15610  memsys3Enter();
15611  p = memsys3MallocUnsafe(nBytes);
15612  memsys3Leave();
15613  return (void*)p;
15614}
15615
15616/*
15617** Free memory.
15618*/
15619void memsys3Free(void *pPrior){
15620  assert( pPrior );
15621  memsys3Enter();
15622  memsys3FreeUnsafe(pPrior);
15623  memsys3Leave();
15624}
15625
15626/*
15627** Change the size of an existing memory allocation
15628*/
15629void *memsys3Realloc(void *pPrior, int nBytes){
15630  int nOld;
15631  void *p;
15632  if( pPrior==0 ){
15633    return sqlite3_malloc(nBytes);
15634  }
15635  if( nBytes<=0 ){
15636    sqlite3_free(pPrior);
15637    return 0;
15638  }
15639  nOld = memsys3Size(pPrior);
15640  if( nBytes<=nOld && nBytes>=nOld-128 ){
15641    return pPrior;
15642  }
15643  memsys3Enter();
15644  p = memsys3MallocUnsafe(nBytes);
15645  if( p ){
15646    if( nOld<nBytes ){
15647      memcpy(p, pPrior, nOld);
15648    }else{
15649      memcpy(p, pPrior, nBytes);
15650    }
15651    memsys3FreeUnsafe(pPrior);
15652  }
15653  memsys3Leave();
15654  return p;
15655}
15656
15657/*
15658** Initialize this module.
15659*/
15660static int memsys3Init(void *NotUsed){
15661  UNUSED_PARAMETER(NotUsed);
15662  if( !sqlite3GlobalConfig.pHeap ){
15663    return SQLITE_ERROR;
15664  }
15665
15666  /* Store a pointer to the memory block in global structure mem3. */
15667  assert( sizeof(Mem3Block)==8 );
15668  mem3.aPool = (Mem3Block *)sqlite3GlobalConfig.pHeap;
15669  mem3.nPool = (sqlite3GlobalConfig.nHeap / sizeof(Mem3Block)) - 2;
15670
15671  /* Initialize the master block. */
15672  mem3.szMaster = mem3.nPool;
15673  mem3.mnMaster = mem3.szMaster;
15674  mem3.iMaster = 1;
15675  mem3.aPool[0].u.hdr.size4x = (mem3.szMaster<<2) + 2;
15676  mem3.aPool[mem3.nPool].u.hdr.prevSize = mem3.nPool;
15677  mem3.aPool[mem3.nPool].u.hdr.size4x = 1;
15678
15679  return SQLITE_OK;
15680}
15681
15682/*
15683** Deinitialize this module.
15684*/
15685static void memsys3Shutdown(void *NotUsed){
15686  UNUSED_PARAMETER(NotUsed);
15687  mem3.mutex = 0;
15688  return;
15689}
15690
15691
15692
15693/*
15694** Open the file indicated and write a log of all unfreed memory
15695** allocations into that log.
15696*/
15697SQLITE_PRIVATE void sqlite3Memsys3Dump(const char *zFilename){
15698#ifdef SQLITE_DEBUG
15699  FILE *out;
15700  u32 i, j;
15701  u32 size;
15702  if( zFilename==0 || zFilename[0]==0 ){
15703    out = stdout;
15704  }else{
15705    out = fopen(zFilename, "w");
15706    if( out==0 ){
15707      fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
15708                      zFilename);
15709      return;
15710    }
15711  }
15712  memsys3Enter();
15713  fprintf(out, "CHUNKS:\n");
15714  for(i=1; i<=mem3.nPool; i+=size/4){
15715    size = mem3.aPool[i-1].u.hdr.size4x;
15716    if( size/4<=1 ){
15717      fprintf(out, "%p size error\n", &mem3.aPool[i]);
15718      assert( 0 );
15719      break;
15720    }
15721    if( (size&1)==0 && mem3.aPool[i+size/4-1].u.hdr.prevSize!=size/4 ){
15722      fprintf(out, "%p tail size does not match\n", &mem3.aPool[i]);
15723      assert( 0 );
15724      break;
15725    }
15726    if( ((mem3.aPool[i+size/4-1].u.hdr.size4x&2)>>1)!=(size&1) ){
15727      fprintf(out, "%p tail checkout bit is incorrect\n", &mem3.aPool[i]);
15728      assert( 0 );
15729      break;
15730    }
15731    if( size&1 ){
15732      fprintf(out, "%p %6d bytes checked out\n", &mem3.aPool[i], (size/4)*8-8);
15733    }else{
15734      fprintf(out, "%p %6d bytes free%s\n", &mem3.aPool[i], (size/4)*8-8,
15735                  i==mem3.iMaster ? " **master**" : "");
15736    }
15737  }
15738  for(i=0; i<MX_SMALL-1; i++){
15739    if( mem3.aiSmall[i]==0 ) continue;
15740    fprintf(out, "small(%2d):", i);
15741    for(j = mem3.aiSmall[i]; j>0; j=mem3.aPool[j].u.list.next){
15742      fprintf(out, " %p(%d)", &mem3.aPool[j],
15743              (mem3.aPool[j-1].u.hdr.size4x/4)*8-8);
15744    }
15745    fprintf(out, "\n");
15746  }
15747  for(i=0; i<N_HASH; i++){
15748    if( mem3.aiHash[i]==0 ) continue;
15749    fprintf(out, "hash(%2d):", i);
15750    for(j = mem3.aiHash[i]; j>0; j=mem3.aPool[j].u.list.next){
15751      fprintf(out, " %p(%d)", &mem3.aPool[j],
15752              (mem3.aPool[j-1].u.hdr.size4x/4)*8-8);
15753    }
15754    fprintf(out, "\n");
15755  }
15756  fprintf(out, "master=%d\n", mem3.iMaster);
15757  fprintf(out, "nowUsed=%d\n", mem3.nPool*8 - mem3.szMaster*8);
15758  fprintf(out, "mxUsed=%d\n", mem3.nPool*8 - mem3.mnMaster*8);
15759  sqlite3_mutex_leave(mem3.mutex);
15760  if( out==stdout ){
15761    fflush(stdout);
15762  }else{
15763    fclose(out);
15764  }
15765#else
15766  UNUSED_PARAMETER(zFilename);
15767#endif
15768}
15769
15770/*
15771** This routine is the only routine in this file with external
15772** linkage.
15773**
15774** Populate the low-level memory allocation function pointers in
15775** sqlite3GlobalConfig.m with pointers to the routines in this file. The
15776** arguments specify the block of memory to manage.
15777**
15778** This routine is only called by sqlite3_config(), and therefore
15779** is not required to be threadsafe (it is not).
15780*/
15781SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys3(void){
15782  static const sqlite3_mem_methods mempoolMethods = {
15783     memsys3Malloc,
15784     memsys3Free,
15785     memsys3Realloc,
15786     memsys3Size,
15787     memsys3Roundup,
15788     memsys3Init,
15789     memsys3Shutdown,
15790     0
15791  };
15792  return &mempoolMethods;
15793}
15794
15795#endif /* SQLITE_ENABLE_MEMSYS3 */
15796
15797/************** End of mem3.c ************************************************/
15798/************** Begin file mem5.c ********************************************/
15799/*
15800** 2007 October 14
15801**
15802** The author disclaims copyright to this source code.  In place of
15803** a legal notice, here is a blessing:
15804**
15805**    May you do good and not evil.
15806**    May you find forgiveness for yourself and forgive others.
15807**    May you share freely, never taking more than you give.
15808**
15809*************************************************************************
15810** This file contains the C functions that implement a memory
15811** allocation subsystem for use by SQLite.
15812**
15813** This version of the memory allocation subsystem omits all
15814** use of malloc(). The application gives SQLite a block of memory
15815** before calling sqlite3_initialize() from which allocations
15816** are made and returned by the xMalloc() and xRealloc()
15817** implementations. Once sqlite3_initialize() has been called,
15818** the amount of memory available to SQLite is fixed and cannot
15819** be changed.
15820**
15821** This version of the memory allocation subsystem is included
15822** in the build only if SQLITE_ENABLE_MEMSYS5 is defined.
15823**
15824** This memory allocator uses the following algorithm:
15825**
15826**   1.  All memory allocations sizes are rounded up to a power of 2.
15827**
15828**   2.  If two adjacent free blocks are the halves of a larger block,
15829**       then the two blocks are coalesed into the single larger block.
15830**
15831**   3.  New memory is allocated from the first available free block.
15832**
15833** This algorithm is described in: J. M. Robson. "Bounds for Some Functions
15834** Concerning Dynamic Storage Allocation". Journal of the Association for
15835** Computing Machinery, Volume 21, Number 8, July 1974, pages 491-499.
15836**
15837** Let n be the size of the largest allocation divided by the minimum
15838** allocation size (after rounding all sizes up to a power of 2.)  Let M
15839** be the maximum amount of memory ever outstanding at one time.  Let
15840** N be the total amount of memory available for allocation.  Robson
15841** proved that this memory allocator will never breakdown due to
15842** fragmentation as long as the following constraint holds:
15843**
15844**      N >=  M*(1 + log2(n)/2) - n + 1
15845**
15846** The sqlite3_status() logic tracks the maximum values of n and M so
15847** that an application can, at any time, verify this constraint.
15848*/
15849
15850/*
15851** This version of the memory allocator is used only when
15852** SQLITE_ENABLE_MEMSYS5 is defined.
15853*/
15854#ifdef SQLITE_ENABLE_MEMSYS5
15855
15856/*
15857** A minimum allocation is an instance of the following structure.
15858** Larger allocations are an array of these structures where the
15859** size of the array is a power of 2.
15860**
15861** The size of this object must be a power of two.  That fact is
15862** verified in memsys5Init().
15863*/
15864typedef struct Mem5Link Mem5Link;
15865struct Mem5Link {
15866  int next;       /* Index of next free chunk */
15867  int prev;       /* Index of previous free chunk */
15868};
15869
15870/*
15871** Maximum size of any allocation is ((1<<LOGMAX)*mem5.szAtom). Since
15872** mem5.szAtom is always at least 8 and 32-bit integers are used,
15873** it is not actually possible to reach this limit.
15874*/
15875#define LOGMAX 30
15876
15877/*
15878** Masks used for mem5.aCtrl[] elements.
15879*/
15880#define CTRL_LOGSIZE  0x1f    /* Log2 Size of this block */
15881#define CTRL_FREE     0x20    /* True if not checked out */
15882
15883/*
15884** All of the static variables used by this module are collected
15885** into a single structure named "mem5".  This is to keep the
15886** static variables organized and to reduce namespace pollution
15887** when this module is combined with other in the amalgamation.
15888*/
15889static SQLITE_WSD struct Mem5Global {
15890  /*
15891  ** Memory available for allocation
15892  */
15893  int szAtom;      /* Smallest possible allocation in bytes */
15894  int nBlock;      /* Number of szAtom sized blocks in zPool */
15895  u8 *zPool;       /* Memory available to be allocated */
15896
15897  /*
15898  ** Mutex to control access to the memory allocation subsystem.
15899  */
15900  sqlite3_mutex *mutex;
15901
15902  /*
15903  ** Performance statistics
15904  */
15905  u64 nAlloc;         /* Total number of calls to malloc */
15906  u64 totalAlloc;     /* Total of all malloc calls - includes internal frag */
15907  u64 totalExcess;    /* Total internal fragmentation */
15908  u32 currentOut;     /* Current checkout, including internal fragmentation */
15909  u32 currentCount;   /* Current number of distinct checkouts */
15910  u32 maxOut;         /* Maximum instantaneous currentOut */
15911  u32 maxCount;       /* Maximum instantaneous currentCount */
15912  u32 maxRequest;     /* Largest allocation (exclusive of internal frag) */
15913
15914  /*
15915  ** Lists of free blocks.  aiFreelist[0] is a list of free blocks of
15916  ** size mem5.szAtom.  aiFreelist[1] holds blocks of size szAtom*2.
15917  ** and so forth.
15918  */
15919  int aiFreelist[LOGMAX+1];
15920
15921  /*
15922  ** Space for tracking which blocks are checked out and the size
15923  ** of each block.  One byte per block.
15924  */
15925  u8 *aCtrl;
15926
15927} mem5;
15928
15929/*
15930** Access the static variable through a macro for SQLITE_OMIT_WSD
15931*/
15932#define mem5 GLOBAL(struct Mem5Global, mem5)
15933
15934/*
15935** Assuming mem5.zPool is divided up into an array of Mem5Link
15936** structures, return a pointer to the idx-th such lik.
15937*/
15938#define MEM5LINK(idx) ((Mem5Link *)(&mem5.zPool[(idx)*mem5.szAtom]))
15939
15940/*
15941** Unlink the chunk at mem5.aPool[i] from list it is currently
15942** on.  It should be found on mem5.aiFreelist[iLogsize].
15943*/
15944static void memsys5Unlink(int i, int iLogsize){
15945  int next, prev;
15946  assert( i>=0 && i<mem5.nBlock );
15947  assert( iLogsize>=0 && iLogsize<=LOGMAX );
15948  assert( (mem5.aCtrl[i] & CTRL_LOGSIZE)==iLogsize );
15949
15950  next = MEM5LINK(i)->next;
15951  prev = MEM5LINK(i)->prev;
15952  if( prev<0 ){
15953    mem5.aiFreelist[iLogsize] = next;
15954  }else{
15955    MEM5LINK(prev)->next = next;
15956  }
15957  if( next>=0 ){
15958    MEM5LINK(next)->prev = prev;
15959  }
15960}
15961
15962/*
15963** Link the chunk at mem5.aPool[i] so that is on the iLogsize
15964** free list.
15965*/
15966static void memsys5Link(int i, int iLogsize){
15967  int x;
15968  assert( sqlite3_mutex_held(mem5.mutex) );
15969  assert( i>=0 && i<mem5.nBlock );
15970  assert( iLogsize>=0 && iLogsize<=LOGMAX );
15971  assert( (mem5.aCtrl[i] & CTRL_LOGSIZE)==iLogsize );
15972
15973  x = MEM5LINK(i)->next = mem5.aiFreelist[iLogsize];
15974  MEM5LINK(i)->prev = -1;
15975  if( x>=0 ){
15976    assert( x<mem5.nBlock );
15977    MEM5LINK(x)->prev = i;
15978  }
15979  mem5.aiFreelist[iLogsize] = i;
15980}
15981
15982/*
15983** If the STATIC_MEM mutex is not already held, obtain it now. The mutex
15984** will already be held (obtained by code in malloc.c) if
15985** sqlite3GlobalConfig.bMemStat is true.
15986*/
15987static void memsys5Enter(void){
15988  sqlite3_mutex_enter(mem5.mutex);
15989}
15990static void memsys5Leave(void){
15991  sqlite3_mutex_leave(mem5.mutex);
15992}
15993
15994/*
15995** Return the size of an outstanding allocation, in bytes.  The
15996** size returned omits the 8-byte header overhead.  This only
15997** works for chunks that are currently checked out.
15998*/
15999static int memsys5Size(void *p){
16000  int iSize = 0;
16001  if( p ){
16002    int i = ((u8 *)p-mem5.zPool)/mem5.szAtom;
16003    assert( i>=0 && i<mem5.nBlock );
16004    iSize = mem5.szAtom * (1 << (mem5.aCtrl[i]&CTRL_LOGSIZE));
16005  }
16006  return iSize;
16007}
16008
16009/*
16010** Find the first entry on the freelist iLogsize.  Unlink that
16011** entry and return its index.
16012*/
16013static int memsys5UnlinkFirst(int iLogsize){
16014  int i;
16015  int iFirst;
16016
16017  assert( iLogsize>=0 && iLogsize<=LOGMAX );
16018  i = iFirst = mem5.aiFreelist[iLogsize];
16019  assert( iFirst>=0 );
16020  while( i>0 ){
16021    if( i<iFirst ) iFirst = i;
16022    i = MEM5LINK(i)->next;
16023  }
16024  memsys5Unlink(iFirst, iLogsize);
16025  return iFirst;
16026}
16027
16028/*
16029** Return a block of memory of at least nBytes in size.
16030** Return NULL if unable.  Return NULL if nBytes==0.
16031**
16032** The caller guarantees that nByte positive.
16033**
16034** The caller has obtained a mutex prior to invoking this
16035** routine so there is never any chance that two or more
16036** threads can be in this routine at the same time.
16037*/
16038static void *memsys5MallocUnsafe(int nByte){
16039  int i;           /* Index of a mem5.aPool[] slot */
16040  int iBin;        /* Index into mem5.aiFreelist[] */
16041  int iFullSz;     /* Size of allocation rounded up to power of 2 */
16042  int iLogsize;    /* Log2 of iFullSz/POW2_MIN */
16043
16044  /* nByte must be a positive */
16045  assert( nByte>0 );
16046
16047  /* Keep track of the maximum allocation request.  Even unfulfilled
16048  ** requests are counted */
16049  if( (u32)nByte>mem5.maxRequest ){
16050    mem5.maxRequest = nByte;
16051  }
16052
16053  /* Abort if the requested allocation size is larger than the largest
16054  ** power of two that we can represent using 32-bit signed integers.
16055  */
16056  if( nByte > 0x40000000 ){
16057    return 0;
16058  }
16059
16060  /* Round nByte up to the next valid power of two */
16061  for(iFullSz=mem5.szAtom, iLogsize=0; iFullSz<nByte; iFullSz *= 2, iLogsize++){}
16062
16063  /* Make sure mem5.aiFreelist[iLogsize] contains at least one free
16064  ** block.  If not, then split a block of the next larger power of
16065  ** two in order to create a new free block of size iLogsize.
16066  */
16067  for(iBin=iLogsize; mem5.aiFreelist[iBin]<0 && iBin<=LOGMAX; iBin++){}
16068  if( iBin>LOGMAX ){
16069    testcase( sqlite3GlobalConfig.xLog!=0 );
16070    sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes", nByte);
16071    return 0;
16072  }
16073  i = memsys5UnlinkFirst(iBin);
16074  while( iBin>iLogsize ){
16075    int newSize;
16076
16077    iBin--;
16078    newSize = 1 << iBin;
16079    mem5.aCtrl[i+newSize] = CTRL_FREE | iBin;
16080    memsys5Link(i+newSize, iBin);
16081  }
16082  mem5.aCtrl[i] = iLogsize;
16083
16084  /* Update allocator performance statistics. */
16085  mem5.nAlloc++;
16086  mem5.totalAlloc += iFullSz;
16087  mem5.totalExcess += iFullSz - nByte;
16088  mem5.currentCount++;
16089  mem5.currentOut += iFullSz;
16090  if( mem5.maxCount<mem5.currentCount ) mem5.maxCount = mem5.currentCount;
16091  if( mem5.maxOut<mem5.currentOut ) mem5.maxOut = mem5.currentOut;
16092
16093  /* Return a pointer to the allocated memory. */
16094  return (void*)&mem5.zPool[i*mem5.szAtom];
16095}
16096
16097/*
16098** Free an outstanding memory allocation.
16099*/
16100static void memsys5FreeUnsafe(void *pOld){
16101  u32 size, iLogsize;
16102  int iBlock;
16103
16104  /* Set iBlock to the index of the block pointed to by pOld in
16105  ** the array of mem5.szAtom byte blocks pointed to by mem5.zPool.
16106  */
16107  iBlock = ((u8 *)pOld-mem5.zPool)/mem5.szAtom;
16108
16109  /* Check that the pointer pOld points to a valid, non-free block. */
16110  assert( iBlock>=0 && iBlock<mem5.nBlock );
16111  assert( ((u8 *)pOld-mem5.zPool)%mem5.szAtom==0 );
16112  assert( (mem5.aCtrl[iBlock] & CTRL_FREE)==0 );
16113
16114  iLogsize = mem5.aCtrl[iBlock] & CTRL_LOGSIZE;
16115  size = 1<<iLogsize;
16116  assert( iBlock+size-1<(u32)mem5.nBlock );
16117
16118  mem5.aCtrl[iBlock] |= CTRL_FREE;
16119  mem5.aCtrl[iBlock+size-1] |= CTRL_FREE;
16120  assert( mem5.currentCount>0 );
16121  assert( mem5.currentOut>=(size*mem5.szAtom) );
16122  mem5.currentCount--;
16123  mem5.currentOut -= size*mem5.szAtom;
16124  assert( mem5.currentOut>0 || mem5.currentCount==0 );
16125  assert( mem5.currentCount>0 || mem5.currentOut==0 );
16126
16127  mem5.aCtrl[iBlock] = CTRL_FREE | iLogsize;
16128  while( ALWAYS(iLogsize<LOGMAX) ){
16129    int iBuddy;
16130    if( (iBlock>>iLogsize) & 1 ){
16131      iBuddy = iBlock - size;
16132    }else{
16133      iBuddy = iBlock + size;
16134    }
16135    assert( iBuddy>=0 );
16136    if( (iBuddy+(1<<iLogsize))>mem5.nBlock ) break;
16137    if( mem5.aCtrl[iBuddy]!=(CTRL_FREE | iLogsize) ) break;
16138    memsys5Unlink(iBuddy, iLogsize);
16139    iLogsize++;
16140    if( iBuddy<iBlock ){
16141      mem5.aCtrl[iBuddy] = CTRL_FREE | iLogsize;
16142      mem5.aCtrl[iBlock] = 0;
16143      iBlock = iBuddy;
16144    }else{
16145      mem5.aCtrl[iBlock] = CTRL_FREE | iLogsize;
16146      mem5.aCtrl[iBuddy] = 0;
16147    }
16148    size *= 2;
16149  }
16150  memsys5Link(iBlock, iLogsize);
16151}
16152
16153/*
16154** Allocate nBytes of memory
16155*/
16156static void *memsys5Malloc(int nBytes){
16157  sqlite3_int64 *p = 0;
16158  if( nBytes>0 ){
16159    memsys5Enter();
16160    p = memsys5MallocUnsafe(nBytes);
16161    memsys5Leave();
16162  }
16163  return (void*)p;
16164}
16165
16166/*
16167** Free memory.
16168**
16169** The outer layer memory allocator prevents this routine from
16170** being called with pPrior==0.
16171*/
16172static void memsys5Free(void *pPrior){
16173  assert( pPrior!=0 );
16174  memsys5Enter();
16175  memsys5FreeUnsafe(pPrior);
16176  memsys5Leave();
16177}
16178
16179/*
16180** Change the size of an existing memory allocation.
16181**
16182** The outer layer memory allocator prevents this routine from
16183** being called with pPrior==0.
16184**
16185** nBytes is always a value obtained from a prior call to
16186** memsys5Round().  Hence nBytes is always a non-negative power
16187** of two.  If nBytes==0 that means that an oversize allocation
16188** (an allocation larger than 0x40000000) was requested and this
16189** routine should return 0 without freeing pPrior.
16190*/
16191static void *memsys5Realloc(void *pPrior, int nBytes){
16192  int nOld;
16193  void *p;
16194  assert( pPrior!=0 );
16195  assert( (nBytes&(nBytes-1))==0 );  /* EV: R-46199-30249 */
16196  assert( nBytes>=0 );
16197  if( nBytes==0 ){
16198    return 0;
16199  }
16200  nOld = memsys5Size(pPrior);
16201  if( nBytes<=nOld ){
16202    return pPrior;
16203  }
16204  memsys5Enter();
16205  p = memsys5MallocUnsafe(nBytes);
16206  if( p ){
16207    memcpy(p, pPrior, nOld);
16208    memsys5FreeUnsafe(pPrior);
16209  }
16210  memsys5Leave();
16211  return p;
16212}
16213
16214/*
16215** Round up a request size to the next valid allocation size.  If
16216** the allocation is too large to be handled by this allocation system,
16217** return 0.
16218**
16219** All allocations must be a power of two and must be expressed by a
16220** 32-bit signed integer.  Hence the largest allocation is 0x40000000
16221** or 1073741824 bytes.
16222*/
16223static int memsys5Roundup(int n){
16224  int iFullSz;
16225  if( n > 0x40000000 ) return 0;
16226  for(iFullSz=mem5.szAtom; iFullSz<n; iFullSz *= 2);
16227  return iFullSz;
16228}
16229
16230/*
16231** Return the ceiling of the logarithm base 2 of iValue.
16232**
16233** Examples:   memsys5Log(1) -> 0
16234**             memsys5Log(2) -> 1
16235**             memsys5Log(4) -> 2
16236**             memsys5Log(5) -> 3
16237**             memsys5Log(8) -> 3
16238**             memsys5Log(9) -> 4
16239*/
16240static int memsys5Log(int iValue){
16241  int iLog;
16242  for(iLog=0; (iLog<(int)((sizeof(int)*8)-1)) && (1<<iLog)<iValue; iLog++);
16243  return iLog;
16244}
16245
16246/*
16247** Initialize the memory allocator.
16248**
16249** This routine is not threadsafe.  The caller must be holding a mutex
16250** to prevent multiple threads from entering at the same time.
16251*/
16252static int memsys5Init(void *NotUsed){
16253  int ii;            /* Loop counter */
16254  int nByte;         /* Number of bytes of memory available to this allocator */
16255  u8 *zByte;         /* Memory usable by this allocator */
16256  int nMinLog;       /* Log base 2 of minimum allocation size in bytes */
16257  int iOffset;       /* An offset into mem5.aCtrl[] */
16258
16259  UNUSED_PARAMETER(NotUsed);
16260
16261  /* For the purposes of this routine, disable the mutex */
16262  mem5.mutex = 0;
16263
16264  /* The size of a Mem5Link object must be a power of two.  Verify that
16265  ** this is case.
16266  */
16267  assert( (sizeof(Mem5Link)&(sizeof(Mem5Link)-1))==0 );
16268
16269  nByte = sqlite3GlobalConfig.nHeap;
16270  zByte = (u8*)sqlite3GlobalConfig.pHeap;
16271  assert( zByte!=0 );  /* sqlite3_config() does not allow otherwise */
16272
16273  /* boundaries on sqlite3GlobalConfig.mnReq are enforced in sqlite3_config() */
16274  nMinLog = memsys5Log(sqlite3GlobalConfig.mnReq);
16275  mem5.szAtom = (1<<nMinLog);
16276  while( (int)sizeof(Mem5Link)>mem5.szAtom ){
16277    mem5.szAtom = mem5.szAtom << 1;
16278  }
16279
16280  mem5.nBlock = (nByte / (mem5.szAtom+sizeof(u8)));
16281  mem5.zPool = zByte;
16282  mem5.aCtrl = (u8 *)&mem5.zPool[mem5.nBlock*mem5.szAtom];
16283
16284  for(ii=0; ii<=LOGMAX; ii++){
16285    mem5.aiFreelist[ii] = -1;
16286  }
16287
16288  iOffset = 0;
16289  for(ii=LOGMAX; ii>=0; ii--){
16290    int nAlloc = (1<<ii);
16291    if( (iOffset+nAlloc)<=mem5.nBlock ){
16292      mem5.aCtrl[iOffset] = ii | CTRL_FREE;
16293      memsys5Link(iOffset, ii);
16294      iOffset += nAlloc;
16295    }
16296    assert((iOffset+nAlloc)>mem5.nBlock);
16297  }
16298
16299  /* If a mutex is required for normal operation, allocate one */
16300  if( sqlite3GlobalConfig.bMemstat==0 ){
16301    mem5.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
16302  }
16303
16304  return SQLITE_OK;
16305}
16306
16307/*
16308** Deinitialize this module.
16309*/
16310static void memsys5Shutdown(void *NotUsed){
16311  UNUSED_PARAMETER(NotUsed);
16312  mem5.mutex = 0;
16313  return;
16314}
16315
16316#ifdef SQLITE_TEST
16317/*
16318** Open the file indicated and write a log of all unfreed memory
16319** allocations into that log.
16320*/
16321SQLITE_PRIVATE void sqlite3Memsys5Dump(const char *zFilename){
16322  FILE *out;
16323  int i, j, n;
16324  int nMinLog;
16325
16326  if( zFilename==0 || zFilename[0]==0 ){
16327    out = stdout;
16328  }else{
16329    out = fopen(zFilename, "w");
16330    if( out==0 ){
16331      fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
16332                      zFilename);
16333      return;
16334    }
16335  }
16336  memsys5Enter();
16337  nMinLog = memsys5Log(mem5.szAtom);
16338  for(i=0; i<=LOGMAX && i+nMinLog<32; i++){
16339    for(n=0, j=mem5.aiFreelist[i]; j>=0; j = MEM5LINK(j)->next, n++){}
16340    fprintf(out, "freelist items of size %d: %d\n", mem5.szAtom << i, n);
16341  }
16342  fprintf(out, "mem5.nAlloc       = %llu\n", mem5.nAlloc);
16343  fprintf(out, "mem5.totalAlloc   = %llu\n", mem5.totalAlloc);
16344  fprintf(out, "mem5.totalExcess  = %llu\n", mem5.totalExcess);
16345  fprintf(out, "mem5.currentOut   = %u\n", mem5.currentOut);
16346  fprintf(out, "mem5.currentCount = %u\n", mem5.currentCount);
16347  fprintf(out, "mem5.maxOut       = %u\n", mem5.maxOut);
16348  fprintf(out, "mem5.maxCount     = %u\n", mem5.maxCount);
16349  fprintf(out, "mem5.maxRequest   = %u\n", mem5.maxRequest);
16350  memsys5Leave();
16351  if( out==stdout ){
16352    fflush(stdout);
16353  }else{
16354    fclose(out);
16355  }
16356}
16357#endif
16358
16359/*
16360** This routine is the only routine in this file with external
16361** linkage. It returns a pointer to a static sqlite3_mem_methods
16362** struct populated with the memsys5 methods.
16363*/
16364SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys5(void){
16365  static const sqlite3_mem_methods memsys5Methods = {
16366     memsys5Malloc,
16367     memsys5Free,
16368     memsys5Realloc,
16369     memsys5Size,
16370     memsys5Roundup,
16371     memsys5Init,
16372     memsys5Shutdown,
16373     0
16374  };
16375  return &memsys5Methods;
16376}
16377
16378#endif /* SQLITE_ENABLE_MEMSYS5 */
16379
16380/************** End of mem5.c ************************************************/
16381/************** Begin file mutex.c *******************************************/
16382/*
16383** 2007 August 14
16384**
16385** The author disclaims copyright to this source code.  In place of
16386** a legal notice, here is a blessing:
16387**
16388**    May you do good and not evil.
16389**    May you find forgiveness for yourself and forgive others.
16390**    May you share freely, never taking more than you give.
16391**
16392*************************************************************************
16393** This file contains the C functions that implement mutexes.
16394**
16395** This file contains code that is common across all mutex implementations.
16396*/
16397
16398#if defined(SQLITE_DEBUG) && !defined(SQLITE_MUTEX_OMIT)
16399/*
16400** For debugging purposes, record when the mutex subsystem is initialized
16401** and uninitialized so that we can assert() if there is an attempt to
16402** allocate a mutex while the system is uninitialized.
16403*/
16404static SQLITE_WSD int mutexIsInit = 0;
16405#endif /* SQLITE_DEBUG */
16406
16407
16408#ifndef SQLITE_MUTEX_OMIT
16409/*
16410** Initialize the mutex system.
16411*/
16412SQLITE_PRIVATE int sqlite3MutexInit(void){
16413  int rc = SQLITE_OK;
16414  if( !sqlite3GlobalConfig.mutex.xMutexAlloc ){
16415    /* If the xMutexAlloc method has not been set, then the user did not
16416    ** install a mutex implementation via sqlite3_config() prior to
16417    ** sqlite3_initialize() being called. This block copies pointers to
16418    ** the default implementation into the sqlite3GlobalConfig structure.
16419    */
16420    sqlite3_mutex_methods const *pFrom;
16421    sqlite3_mutex_methods *pTo = &sqlite3GlobalConfig.mutex;
16422
16423    if( sqlite3GlobalConfig.bCoreMutex ){
16424      pFrom = sqlite3DefaultMutex();
16425    }else{
16426      pFrom = sqlite3NoopMutex();
16427    }
16428    memcpy(pTo, pFrom, offsetof(sqlite3_mutex_methods, xMutexAlloc));
16429    memcpy(&pTo->xMutexFree, &pFrom->xMutexFree,
16430           sizeof(*pTo) - offsetof(sqlite3_mutex_methods, xMutexFree));
16431    pTo->xMutexAlloc = pFrom->xMutexAlloc;
16432  }
16433  rc = sqlite3GlobalConfig.mutex.xMutexInit();
16434
16435#ifdef SQLITE_DEBUG
16436  GLOBAL(int, mutexIsInit) = 1;
16437#endif
16438
16439  return rc;
16440}
16441
16442/*
16443** Shutdown the mutex system. This call frees resources allocated by
16444** sqlite3MutexInit().
16445*/
16446SQLITE_PRIVATE int sqlite3MutexEnd(void){
16447  int rc = SQLITE_OK;
16448  if( sqlite3GlobalConfig.mutex.xMutexEnd ){
16449    rc = sqlite3GlobalConfig.mutex.xMutexEnd();
16450  }
16451
16452#ifdef SQLITE_DEBUG
16453  GLOBAL(int, mutexIsInit) = 0;
16454#endif
16455
16456  return rc;
16457}
16458
16459/*
16460** Retrieve a pointer to a static mutex or allocate a new dynamic one.
16461*/
16462SQLITE_API sqlite3_mutex *sqlite3_mutex_alloc(int id){
16463#ifndef SQLITE_OMIT_AUTOINIT
16464  if( sqlite3_initialize() ) return 0;
16465#endif
16466  return sqlite3GlobalConfig.mutex.xMutexAlloc(id);
16467}
16468
16469SQLITE_PRIVATE sqlite3_mutex *sqlite3MutexAlloc(int id){
16470  if( !sqlite3GlobalConfig.bCoreMutex ){
16471    return 0;
16472  }
16473  assert( GLOBAL(int, mutexIsInit) );
16474  return sqlite3GlobalConfig.mutex.xMutexAlloc(id);
16475}
16476
16477/*
16478** Free a dynamic mutex.
16479*/
16480SQLITE_API void sqlite3_mutex_free(sqlite3_mutex *p){
16481  if( p ){
16482    sqlite3GlobalConfig.mutex.xMutexFree(p);
16483  }
16484}
16485
16486/*
16487** Obtain the mutex p. If some other thread already has the mutex, block
16488** until it can be obtained.
16489*/
16490SQLITE_API void sqlite3_mutex_enter(sqlite3_mutex *p){
16491  if( p ){
16492    sqlite3GlobalConfig.mutex.xMutexEnter(p);
16493  }
16494}
16495
16496/*
16497** Obtain the mutex p. If successful, return SQLITE_OK. Otherwise, if another
16498** thread holds the mutex and it cannot be obtained, return SQLITE_BUSY.
16499*/
16500SQLITE_API int sqlite3_mutex_try(sqlite3_mutex *p){
16501  int rc = SQLITE_OK;
16502  if( p ){
16503    return sqlite3GlobalConfig.mutex.xMutexTry(p);
16504  }
16505  return rc;
16506}
16507
16508/*
16509** The sqlite3_mutex_leave() routine exits a mutex that was previously
16510** entered by the same thread.  The behavior is undefined if the mutex
16511** is not currently entered. If a NULL pointer is passed as an argument
16512** this function is a no-op.
16513*/
16514SQLITE_API void sqlite3_mutex_leave(sqlite3_mutex *p){
16515  if( p ){
16516    sqlite3GlobalConfig.mutex.xMutexLeave(p);
16517  }
16518}
16519
16520#ifndef NDEBUG
16521/*
16522** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
16523** intended for use inside assert() statements.
16524*/
16525SQLITE_API int sqlite3_mutex_held(sqlite3_mutex *p){
16526  return p==0 || sqlite3GlobalConfig.mutex.xMutexHeld(p);
16527}
16528SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex *p){
16529  return p==0 || sqlite3GlobalConfig.mutex.xMutexNotheld(p);
16530}
16531#endif
16532
16533#endif /* SQLITE_MUTEX_OMIT */
16534
16535/************** End of mutex.c ***********************************************/
16536/************** Begin file mutex_noop.c **************************************/
16537/*
16538** 2008 October 07
16539**
16540** The author disclaims copyright to this source code.  In place of
16541** a legal notice, here is a blessing:
16542**
16543**    May you do good and not evil.
16544**    May you find forgiveness for yourself and forgive others.
16545**    May you share freely, never taking more than you give.
16546**
16547*************************************************************************
16548** This file contains the C functions that implement mutexes.
16549**
16550** This implementation in this file does not provide any mutual
16551** exclusion and is thus suitable for use only in applications
16552** that use SQLite in a single thread.  The routines defined
16553** here are place-holders.  Applications can substitute working
16554** mutex routines at start-time using the
16555**
16556**     sqlite3_config(SQLITE_CONFIG_MUTEX,...)
16557**
16558** interface.
16559**
16560** If compiled with SQLITE_DEBUG, then additional logic is inserted
16561** that does error checking on mutexes to make sure they are being
16562** called correctly.
16563*/
16564
16565#ifndef SQLITE_MUTEX_OMIT
16566
16567#ifndef SQLITE_DEBUG
16568/*
16569** Stub routines for all mutex methods.
16570**
16571** This routines provide no mutual exclusion or error checking.
16572*/
16573static int noopMutexInit(void){ return SQLITE_OK; }
16574static int noopMutexEnd(void){ return SQLITE_OK; }
16575static sqlite3_mutex *noopMutexAlloc(int id){
16576  UNUSED_PARAMETER(id);
16577  return (sqlite3_mutex*)8;
16578}
16579static void noopMutexFree(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
16580static void noopMutexEnter(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
16581static int noopMutexTry(sqlite3_mutex *p){
16582  UNUSED_PARAMETER(p);
16583  return SQLITE_OK;
16584}
16585static void noopMutexLeave(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
16586
16587SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3NoopMutex(void){
16588  static const sqlite3_mutex_methods sMutex = {
16589    noopMutexInit,
16590    noopMutexEnd,
16591    noopMutexAlloc,
16592    noopMutexFree,
16593    noopMutexEnter,
16594    noopMutexTry,
16595    noopMutexLeave,
16596
16597    0,
16598    0,
16599  };
16600
16601  return &sMutex;
16602}
16603#endif /* !SQLITE_DEBUG */
16604
16605#ifdef SQLITE_DEBUG
16606/*
16607** In this implementation, error checking is provided for testing
16608** and debugging purposes.  The mutexes still do not provide any
16609** mutual exclusion.
16610*/
16611
16612/*
16613** The mutex object
16614*/
16615typedef struct sqlite3_debug_mutex {
16616  int id;     /* The mutex type */
16617  int cnt;    /* Number of entries without a matching leave */
16618} sqlite3_debug_mutex;
16619
16620/*
16621** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
16622** intended for use inside assert() statements.
16623*/
16624static int debugMutexHeld(sqlite3_mutex *pX){
16625  sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
16626  return p==0 || p->cnt>0;
16627}
16628static int debugMutexNotheld(sqlite3_mutex *pX){
16629  sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
16630  return p==0 || p->cnt==0;
16631}
16632
16633/*
16634** Initialize and deinitialize the mutex subsystem.
16635*/
16636static int debugMutexInit(void){ return SQLITE_OK; }
16637static int debugMutexEnd(void){ return SQLITE_OK; }
16638
16639/*
16640** The sqlite3_mutex_alloc() routine allocates a new
16641** mutex and returns a pointer to it.  If it returns NULL
16642** that means that a mutex could not be allocated.
16643*/
16644static sqlite3_mutex *debugMutexAlloc(int id){
16645  static sqlite3_debug_mutex aStatic[6];
16646  sqlite3_debug_mutex *pNew = 0;
16647  switch( id ){
16648    case SQLITE_MUTEX_FAST:
16649    case SQLITE_MUTEX_RECURSIVE: {
16650      pNew = sqlite3Malloc(sizeof(*pNew));
16651      if( pNew ){
16652        pNew->id = id;
16653        pNew->cnt = 0;
16654      }
16655      break;
16656    }
16657    default: {
16658      assert( id-2 >= 0 );
16659      assert( id-2 < (int)(sizeof(aStatic)/sizeof(aStatic[0])) );
16660      pNew = &aStatic[id-2];
16661      pNew->id = id;
16662      break;
16663    }
16664  }
16665  return (sqlite3_mutex*)pNew;
16666}
16667
16668/*
16669** This routine deallocates a previously allocated mutex.
16670*/
16671static void debugMutexFree(sqlite3_mutex *pX){
16672  sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
16673  assert( p->cnt==0 );
16674  assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
16675  sqlite3_free(p);
16676}
16677
16678/*
16679** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
16680** to enter a mutex.  If another thread is already within the mutex,
16681** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
16682** SQLITE_BUSY.  The sqlite3_mutex_try() interface returns SQLITE_OK
16683** upon successful entry.  Mutexes created using SQLITE_MUTEX_RECURSIVE can
16684** be entered multiple times by the same thread.  In such cases the,
16685** mutex must be exited an equal number of times before another thread
16686** can enter.  If the same thread tries to enter any other kind of mutex
16687** more than once, the behavior is undefined.
16688*/
16689static void debugMutexEnter(sqlite3_mutex *pX){
16690  sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
16691  assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
16692  p->cnt++;
16693}
16694static int debugMutexTry(sqlite3_mutex *pX){
16695  sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
16696  assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
16697  p->cnt++;
16698  return SQLITE_OK;
16699}
16700
16701/*
16702** The sqlite3_mutex_leave() routine exits a mutex that was
16703** previously entered by the same thread.  The behavior
16704** is undefined if the mutex is not currently entered or
16705** is not currently allocated.  SQLite will never do either.
16706*/
16707static void debugMutexLeave(sqlite3_mutex *pX){
16708  sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
16709  assert( debugMutexHeld(pX) );
16710  p->cnt--;
16711  assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
16712}
16713
16714SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3NoopMutex(void){
16715  static const sqlite3_mutex_methods sMutex = {
16716    debugMutexInit,
16717    debugMutexEnd,
16718    debugMutexAlloc,
16719    debugMutexFree,
16720    debugMutexEnter,
16721    debugMutexTry,
16722    debugMutexLeave,
16723
16724    debugMutexHeld,
16725    debugMutexNotheld
16726  };
16727
16728  return &sMutex;
16729}
16730#endif /* SQLITE_DEBUG */
16731
16732/*
16733** If compiled with SQLITE_MUTEX_NOOP, then the no-op mutex implementation
16734** is used regardless of the run-time threadsafety setting.
16735*/
16736#ifdef SQLITE_MUTEX_NOOP
16737SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
16738  return sqlite3NoopMutex();
16739}
16740#endif /* SQLITE_MUTEX_NOOP */
16741#endif /* SQLITE_MUTEX_OMIT */
16742
16743/************** End of mutex_noop.c ******************************************/
16744/************** Begin file mutex_os2.c ***************************************/
16745/*
16746** 2007 August 28
16747**
16748** The author disclaims copyright to this source code.  In place of
16749** a legal notice, here is a blessing:
16750**
16751**    May you do good and not evil.
16752**    May you find forgiveness for yourself and forgive others.
16753**    May you share freely, never taking more than you give.
16754**
16755*************************************************************************
16756** This file contains the C functions that implement mutexes for OS/2
16757*/
16758
16759/*
16760** The code in this file is only used if SQLITE_MUTEX_OS2 is defined.
16761** See the mutex.h file for details.
16762*/
16763#ifdef SQLITE_MUTEX_OS2
16764
16765/********************** OS/2 Mutex Implementation **********************
16766**
16767** This implementation of mutexes is built using the OS/2 API.
16768*/
16769
16770/*
16771** The mutex object
16772** Each recursive mutex is an instance of the following structure.
16773*/
16774struct sqlite3_mutex {
16775  HMTX mutex;       /* Mutex controlling the lock */
16776  int  id;          /* Mutex type */
16777#ifdef SQLITE_DEBUG
16778 int   trace;       /* True to trace changes */
16779#endif
16780};
16781
16782#ifdef SQLITE_DEBUG
16783#define SQLITE3_MUTEX_INITIALIZER { 0, 0, 0 }
16784#else
16785#define SQLITE3_MUTEX_INITIALIZER { 0, 0 }
16786#endif
16787
16788/*
16789** Initialize and deinitialize the mutex subsystem.
16790*/
16791static int os2MutexInit(void){ return SQLITE_OK; }
16792static int os2MutexEnd(void){ return SQLITE_OK; }
16793
16794/*
16795** The sqlite3_mutex_alloc() routine allocates a new
16796** mutex and returns a pointer to it.  If it returns NULL
16797** that means that a mutex could not be allocated.
16798** SQLite will unwind its stack and return an error.  The argument
16799** to sqlite3_mutex_alloc() is one of these integer constants:
16800**
16801** <ul>
16802** <li>  SQLITE_MUTEX_FAST
16803** <li>  SQLITE_MUTEX_RECURSIVE
16804** <li>  SQLITE_MUTEX_STATIC_MASTER
16805** <li>  SQLITE_MUTEX_STATIC_MEM
16806** <li>  SQLITE_MUTEX_STATIC_MEM2
16807** <li>  SQLITE_MUTEX_STATIC_PRNG
16808** <li>  SQLITE_MUTEX_STATIC_LRU
16809** <li>  SQLITE_MUTEX_STATIC_LRU2
16810** </ul>
16811**
16812** The first two constants cause sqlite3_mutex_alloc() to create
16813** a new mutex.  The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
16814** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
16815** The mutex implementation does not need to make a distinction
16816** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
16817** not want to.  But SQLite will only request a recursive mutex in
16818** cases where it really needs one.  If a faster non-recursive mutex
16819** implementation is available on the host platform, the mutex subsystem
16820** might return such a mutex in response to SQLITE_MUTEX_FAST.
16821**
16822** The other allowed parameters to sqlite3_mutex_alloc() each return
16823** a pointer to a static preexisting mutex.  Six static mutexes are
16824** used by the current version of SQLite.  Future versions of SQLite
16825** may add additional static mutexes.  Static mutexes are for internal
16826** use by SQLite only.  Applications that use SQLite mutexes should
16827** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
16828** SQLITE_MUTEX_RECURSIVE.
16829**
16830** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
16831** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
16832** returns a different mutex on every call.  But for the static
16833** mutex types, the same mutex is returned on every call that has
16834** the same type number.
16835*/
16836static sqlite3_mutex *os2MutexAlloc(int iType){
16837  sqlite3_mutex *p = NULL;
16838  switch( iType ){
16839    case SQLITE_MUTEX_FAST:
16840    case SQLITE_MUTEX_RECURSIVE: {
16841      p = sqlite3MallocZero( sizeof(*p) );
16842      if( p ){
16843        p->id = iType;
16844        if( DosCreateMutexSem( 0, &p->mutex, 0, FALSE ) != NO_ERROR ){
16845          sqlite3_free( p );
16846          p = NULL;
16847        }
16848      }
16849      break;
16850    }
16851    default: {
16852      static volatile int isInit = 0;
16853      static sqlite3_mutex staticMutexes[6] = {
16854        SQLITE3_MUTEX_INITIALIZER,
16855        SQLITE3_MUTEX_INITIALIZER,
16856        SQLITE3_MUTEX_INITIALIZER,
16857        SQLITE3_MUTEX_INITIALIZER,
16858        SQLITE3_MUTEX_INITIALIZER,
16859        SQLITE3_MUTEX_INITIALIZER,
16860      };
16861      if ( !isInit ){
16862        APIRET rc;
16863        PTIB ptib;
16864        PPIB ppib;
16865        HMTX mutex;
16866        char name[32];
16867        DosGetInfoBlocks( &ptib, &ppib );
16868        sqlite3_snprintf( sizeof(name), name, "\\SEM32\\SQLITE%04x",
16869                          ppib->pib_ulpid );
16870        while( !isInit ){
16871          mutex = 0;
16872          rc = DosCreateMutexSem( name, &mutex, 0, FALSE);
16873          if( rc == NO_ERROR ){
16874            unsigned int i;
16875            if( !isInit ){
16876              for( i = 0; i < sizeof(staticMutexes)/sizeof(staticMutexes[0]); i++ ){
16877                DosCreateMutexSem( 0, &staticMutexes[i].mutex, 0, FALSE );
16878              }
16879              isInit = 1;
16880            }
16881            DosCloseMutexSem( mutex );
16882          }else if( rc == ERROR_DUPLICATE_NAME ){
16883            DosSleep( 1 );
16884          }else{
16885            return p;
16886          }
16887        }
16888      }
16889      assert( iType-2 >= 0 );
16890      assert( iType-2 < sizeof(staticMutexes)/sizeof(staticMutexes[0]) );
16891      p = &staticMutexes[iType-2];
16892      p->id = iType;
16893      break;
16894    }
16895  }
16896  return p;
16897}
16898
16899
16900/*
16901** This routine deallocates a previously allocated mutex.
16902** SQLite is careful to deallocate every mutex that it allocates.
16903*/
16904static void os2MutexFree(sqlite3_mutex *p){
16905#ifdef SQLITE_DEBUG
16906  TID tid;
16907  PID pid;
16908  ULONG ulCount;
16909  DosQueryMutexSem(p->mutex, &pid, &tid, &ulCount);
16910  assert( ulCount==0 );
16911  assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
16912#endif
16913  DosCloseMutexSem( p->mutex );
16914  sqlite3_free( p );
16915}
16916
16917#ifdef SQLITE_DEBUG
16918/*
16919** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
16920** intended for use inside assert() statements.
16921*/
16922static int os2MutexHeld(sqlite3_mutex *p){
16923  TID tid;
16924  PID pid;
16925  ULONG ulCount;
16926  PTIB ptib;
16927  DosQueryMutexSem(p->mutex, &pid, &tid, &ulCount);
16928  if( ulCount==0 || ( ulCount>1 && p->id!=SQLITE_MUTEX_RECURSIVE ) )
16929    return 0;
16930  DosGetInfoBlocks(&ptib, NULL);
16931  return tid==ptib->tib_ptib2->tib2_ultid;
16932}
16933static int os2MutexNotheld(sqlite3_mutex *p){
16934  TID tid;
16935  PID pid;
16936  ULONG ulCount;
16937  PTIB ptib;
16938  DosQueryMutexSem(p->mutex, &pid, &tid, &ulCount);
16939  if( ulCount==0 )
16940    return 1;
16941  DosGetInfoBlocks(&ptib, NULL);
16942  return tid!=ptib->tib_ptib2->tib2_ultid;
16943}
16944static void os2MutexTrace(sqlite3_mutex *p, char *pAction){
16945  TID   tid;
16946  PID   pid;
16947  ULONG ulCount;
16948  DosQueryMutexSem(p->mutex, &pid, &tid, &ulCount);
16949  printf("%s mutex %p (%d) with nRef=%ld\n", pAction, (void*)p, p->trace, ulCount);
16950}
16951#endif
16952
16953/*
16954** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
16955** to enter a mutex.  If another thread is already within the mutex,
16956** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
16957** SQLITE_BUSY.  The sqlite3_mutex_try() interface returns SQLITE_OK
16958** upon successful entry.  Mutexes created using SQLITE_MUTEX_RECURSIVE can
16959** be entered multiple times by the same thread.  In such cases the,
16960** mutex must be exited an equal number of times before another thread
16961** can enter.  If the same thread tries to enter any other kind of mutex
16962** more than once, the behavior is undefined.
16963*/
16964static void os2MutexEnter(sqlite3_mutex *p){
16965  assert( p->id==SQLITE_MUTEX_RECURSIVE || os2MutexNotheld(p) );
16966  DosRequestMutexSem(p->mutex, SEM_INDEFINITE_WAIT);
16967#ifdef SQLITE_DEBUG
16968  if( p->trace ) os2MutexTrace(p, "enter");
16969#endif
16970}
16971static int os2MutexTry(sqlite3_mutex *p){
16972  int rc = SQLITE_BUSY;
16973  assert( p->id==SQLITE_MUTEX_RECURSIVE || os2MutexNotheld(p) );
16974  if( DosRequestMutexSem(p->mutex, SEM_IMMEDIATE_RETURN) == NO_ERROR ) {
16975    rc = SQLITE_OK;
16976#ifdef SQLITE_DEBUG
16977    if( p->trace ) os2MutexTrace(p, "try");
16978#endif
16979  }
16980  return rc;
16981}
16982
16983/*
16984** The sqlite3_mutex_leave() routine exits a mutex that was
16985** previously entered by the same thread.  The behavior
16986** is undefined if the mutex is not currently entered or
16987** is not currently allocated.  SQLite will never do either.
16988*/
16989static void os2MutexLeave(sqlite3_mutex *p){
16990  assert( os2MutexHeld(p) );
16991  DosReleaseMutexSem(p->mutex);
16992#ifdef SQLITE_DEBUG
16993  if( p->trace ) os2MutexTrace(p, "leave");
16994#endif
16995}
16996
16997SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
16998  static const sqlite3_mutex_methods sMutex = {
16999    os2MutexInit,
17000    os2MutexEnd,
17001    os2MutexAlloc,
17002    os2MutexFree,
17003    os2MutexEnter,
17004    os2MutexTry,
17005    os2MutexLeave,
17006#ifdef SQLITE_DEBUG
17007    os2MutexHeld,
17008    os2MutexNotheld
17009#else
17010    0,
17011    0
17012#endif
17013  };
17014
17015  return &sMutex;
17016}
17017#endif /* SQLITE_MUTEX_OS2 */
17018
17019/************** End of mutex_os2.c *******************************************/
17020/************** Begin file mutex_unix.c **************************************/
17021/*
17022** 2007 August 28
17023**
17024** The author disclaims copyright to this source code.  In place of
17025** a legal notice, here is a blessing:
17026**
17027**    May you do good and not evil.
17028**    May you find forgiveness for yourself and forgive others.
17029**    May you share freely, never taking more than you give.
17030**
17031*************************************************************************
17032** This file contains the C functions that implement mutexes for pthreads
17033*/
17034
17035/*
17036** The code in this file is only used if we are compiling threadsafe
17037** under unix with pthreads.
17038**
17039** Note that this implementation requires a version of pthreads that
17040** supports recursive mutexes.
17041*/
17042#ifdef SQLITE_MUTEX_PTHREADS
17043
17044#include <pthread.h>
17045
17046/*
17047** The sqlite3_mutex.id, sqlite3_mutex.nRef, and sqlite3_mutex.owner fields
17048** are necessary under two condidtions:  (1) Debug builds and (2) using
17049** home-grown mutexes.  Encapsulate these conditions into a single #define.
17050*/
17051#if defined(SQLITE_DEBUG) || defined(SQLITE_HOMEGROWN_RECURSIVE_MUTEX)
17052# define SQLITE_MUTEX_NREF 1
17053#else
17054# define SQLITE_MUTEX_NREF 0
17055#endif
17056
17057/*
17058** Each recursive mutex is an instance of the following structure.
17059*/
17060struct sqlite3_mutex {
17061  pthread_mutex_t mutex;     /* Mutex controlling the lock */
17062#if SQLITE_MUTEX_NREF
17063  int id;                    /* Mutex type */
17064  volatile int nRef;         /* Number of entrances */
17065  volatile pthread_t owner;  /* Thread that is within this mutex */
17066  int trace;                 /* True to trace changes */
17067#endif
17068};
17069#if SQLITE_MUTEX_NREF
17070#define SQLITE3_MUTEX_INITIALIZER { PTHREAD_MUTEX_INITIALIZER, 0, 0, (pthread_t)0, 0 }
17071#else
17072#define SQLITE3_MUTEX_INITIALIZER { PTHREAD_MUTEX_INITIALIZER }
17073#endif
17074
17075/*
17076** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
17077** intended for use only inside assert() statements.  On some platforms,
17078** there might be race conditions that can cause these routines to
17079** deliver incorrect results.  In particular, if pthread_equal() is
17080** not an atomic operation, then these routines might delivery
17081** incorrect results.  On most platforms, pthread_equal() is a
17082** comparison of two integers and is therefore atomic.  But we are
17083** told that HPUX is not such a platform.  If so, then these routines
17084** will not always work correctly on HPUX.
17085**
17086** On those platforms where pthread_equal() is not atomic, SQLite
17087** should be compiled without -DSQLITE_DEBUG and with -DNDEBUG to
17088** make sure no assert() statements are evaluated and hence these
17089** routines are never called.
17090*/
17091#if !defined(NDEBUG) || defined(SQLITE_DEBUG)
17092static int pthreadMutexHeld(sqlite3_mutex *p){
17093  return (p->nRef!=0 && pthread_equal(p->owner, pthread_self()));
17094}
17095static int pthreadMutexNotheld(sqlite3_mutex *p){
17096  return p->nRef==0 || pthread_equal(p->owner, pthread_self())==0;
17097}
17098#endif
17099
17100/*
17101** Initialize and deinitialize the mutex subsystem.
17102*/
17103static int pthreadMutexInit(void){ return SQLITE_OK; }
17104static int pthreadMutexEnd(void){ return SQLITE_OK; }
17105
17106/*
17107** The sqlite3_mutex_alloc() routine allocates a new
17108** mutex and returns a pointer to it.  If it returns NULL
17109** that means that a mutex could not be allocated.  SQLite
17110** will unwind its stack and return an error.  The argument
17111** to sqlite3_mutex_alloc() is one of these integer constants:
17112**
17113** <ul>
17114** <li>  SQLITE_MUTEX_FAST
17115** <li>  SQLITE_MUTEX_RECURSIVE
17116** <li>  SQLITE_MUTEX_STATIC_MASTER
17117** <li>  SQLITE_MUTEX_STATIC_MEM
17118** <li>  SQLITE_MUTEX_STATIC_MEM2
17119** <li>  SQLITE_MUTEX_STATIC_PRNG
17120** <li>  SQLITE_MUTEX_STATIC_LRU
17121** <li>  SQLITE_MUTEX_STATIC_PMEM
17122** </ul>
17123**
17124** The first two constants cause sqlite3_mutex_alloc() to create
17125** a new mutex.  The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
17126** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
17127** The mutex implementation does not need to make a distinction
17128** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
17129** not want to.  But SQLite will only request a recursive mutex in
17130** cases where it really needs one.  If a faster non-recursive mutex
17131** implementation is available on the host platform, the mutex subsystem
17132** might return such a mutex in response to SQLITE_MUTEX_FAST.
17133**
17134** The other allowed parameters to sqlite3_mutex_alloc() each return
17135** a pointer to a static preexisting mutex.  Six static mutexes are
17136** used by the current version of SQLite.  Future versions of SQLite
17137** may add additional static mutexes.  Static mutexes are for internal
17138** use by SQLite only.  Applications that use SQLite mutexes should
17139** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
17140** SQLITE_MUTEX_RECURSIVE.
17141**
17142** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
17143** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
17144** returns a different mutex on every call.  But for the static
17145** mutex types, the same mutex is returned on every call that has
17146** the same type number.
17147*/
17148static sqlite3_mutex *pthreadMutexAlloc(int iType){
17149  static sqlite3_mutex staticMutexes[] = {
17150    SQLITE3_MUTEX_INITIALIZER,
17151    SQLITE3_MUTEX_INITIALIZER,
17152    SQLITE3_MUTEX_INITIALIZER,
17153    SQLITE3_MUTEX_INITIALIZER,
17154    SQLITE3_MUTEX_INITIALIZER,
17155    SQLITE3_MUTEX_INITIALIZER
17156  };
17157  sqlite3_mutex *p;
17158  switch( iType ){
17159    case SQLITE_MUTEX_RECURSIVE: {
17160      p = sqlite3MallocZero( sizeof(*p) );
17161      if( p ){
17162#ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
17163        /* If recursive mutexes are not available, we will have to
17164        ** build our own.  See below. */
17165        pthread_mutex_init(&p->mutex, 0);
17166#else
17167        /* Use a recursive mutex if it is available */
17168        pthread_mutexattr_t recursiveAttr;
17169        pthread_mutexattr_init(&recursiveAttr);
17170        pthread_mutexattr_settype(&recursiveAttr, PTHREAD_MUTEX_RECURSIVE);
17171        pthread_mutex_init(&p->mutex, &recursiveAttr);
17172        pthread_mutexattr_destroy(&recursiveAttr);
17173#endif
17174#if SQLITE_MUTEX_NREF
17175        p->id = iType;
17176#endif
17177      }
17178      break;
17179    }
17180    case SQLITE_MUTEX_FAST: {
17181      p = sqlite3MallocZero( sizeof(*p) );
17182      if( p ){
17183#if SQLITE_MUTEX_NREF
17184        p->id = iType;
17185#endif
17186        pthread_mutex_init(&p->mutex, 0);
17187      }
17188      break;
17189    }
17190    default: {
17191      assert( iType-2 >= 0 );
17192      assert( iType-2 < ArraySize(staticMutexes) );
17193      p = &staticMutexes[iType-2];
17194#if SQLITE_MUTEX_NREF
17195      p->id = iType;
17196#endif
17197      break;
17198    }
17199  }
17200  return p;
17201}
17202
17203
17204/*
17205** This routine deallocates a previously
17206** allocated mutex.  SQLite is careful to deallocate every
17207** mutex that it allocates.
17208*/
17209static void pthreadMutexFree(sqlite3_mutex *p){
17210  assert( p->nRef==0 );
17211  assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
17212  pthread_mutex_destroy(&p->mutex);
17213  sqlite3_free(p);
17214}
17215
17216/*
17217** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
17218** to enter a mutex.  If another thread is already within the mutex,
17219** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
17220** SQLITE_BUSY.  The sqlite3_mutex_try() interface returns SQLITE_OK
17221** upon successful entry.  Mutexes created using SQLITE_MUTEX_RECURSIVE can
17222** be entered multiple times by the same thread.  In such cases the,
17223** mutex must be exited an equal number of times before another thread
17224** can enter.  If the same thread tries to enter any other kind of mutex
17225** more than once, the behavior is undefined.
17226*/
17227static void pthreadMutexEnter(sqlite3_mutex *p){
17228  assert( p->id==SQLITE_MUTEX_RECURSIVE || pthreadMutexNotheld(p) );
17229
17230#ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
17231  /* If recursive mutexes are not available, then we have to grow
17232  ** our own.  This implementation assumes that pthread_equal()
17233  ** is atomic - that it cannot be deceived into thinking self
17234  ** and p->owner are equal if p->owner changes between two values
17235  ** that are not equal to self while the comparison is taking place.
17236  ** This implementation also assumes a coherent cache - that
17237  ** separate processes cannot read different values from the same
17238  ** address at the same time.  If either of these two conditions
17239  ** are not met, then the mutexes will fail and problems will result.
17240  */
17241  {
17242    pthread_t self = pthread_self();
17243    if( p->nRef>0 && pthread_equal(p->owner, self) ){
17244      p->nRef++;
17245    }else{
17246      pthread_mutex_lock(&p->mutex);
17247      assert( p->nRef==0 );
17248      p->owner = self;
17249      p->nRef = 1;
17250    }
17251  }
17252#else
17253  /* Use the built-in recursive mutexes if they are available.
17254  */
17255  pthread_mutex_lock(&p->mutex);
17256#if SQLITE_MUTEX_NREF
17257  assert( p->nRef>0 || p->owner==0 );
17258  p->owner = pthread_self();
17259  p->nRef++;
17260#endif
17261#endif
17262
17263#ifdef SQLITE_DEBUG
17264  if( p->trace ){
17265    printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
17266  }
17267#endif
17268}
17269static int pthreadMutexTry(sqlite3_mutex *p){
17270  int rc;
17271  assert( p->id==SQLITE_MUTEX_RECURSIVE || pthreadMutexNotheld(p) );
17272
17273#ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
17274  /* If recursive mutexes are not available, then we have to grow
17275  ** our own.  This implementation assumes that pthread_equal()
17276  ** is atomic - that it cannot be deceived into thinking self
17277  ** and p->owner are equal if p->owner changes between two values
17278  ** that are not equal to self while the comparison is taking place.
17279  ** This implementation also assumes a coherent cache - that
17280  ** separate processes cannot read different values from the same
17281  ** address at the same time.  If either of these two conditions
17282  ** are not met, then the mutexes will fail and problems will result.
17283  */
17284  {
17285    pthread_t self = pthread_self();
17286    if( p->nRef>0 && pthread_equal(p->owner, self) ){
17287      p->nRef++;
17288      rc = SQLITE_OK;
17289    }else if( pthread_mutex_trylock(&p->mutex)==0 ){
17290      assert( p->nRef==0 );
17291      p->owner = self;
17292      p->nRef = 1;
17293      rc = SQLITE_OK;
17294    }else{
17295      rc = SQLITE_BUSY;
17296    }
17297  }
17298#else
17299  /* Use the built-in recursive mutexes if they are available.
17300  */
17301  if( pthread_mutex_trylock(&p->mutex)==0 ){
17302#if SQLITE_MUTEX_NREF
17303    p->owner = pthread_self();
17304    p->nRef++;
17305#endif
17306    rc = SQLITE_OK;
17307  }else{
17308    rc = SQLITE_BUSY;
17309  }
17310#endif
17311
17312#ifdef SQLITE_DEBUG
17313  if( rc==SQLITE_OK && p->trace ){
17314    printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
17315  }
17316#endif
17317  return rc;
17318}
17319
17320/*
17321** The sqlite3_mutex_leave() routine exits a mutex that was
17322** previously entered by the same thread.  The behavior
17323** is undefined if the mutex is not currently entered or
17324** is not currently allocated.  SQLite will never do either.
17325*/
17326static void pthreadMutexLeave(sqlite3_mutex *p){
17327  assert( pthreadMutexHeld(p) );
17328#if SQLITE_MUTEX_NREF
17329  p->nRef--;
17330  if( p->nRef==0 ) p->owner = 0;
17331#endif
17332  assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
17333
17334#ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
17335  if( p->nRef==0 ){
17336    pthread_mutex_unlock(&p->mutex);
17337  }
17338#else
17339  pthread_mutex_unlock(&p->mutex);
17340#endif
17341
17342#ifdef SQLITE_DEBUG
17343  if( p->trace ){
17344    printf("leave mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
17345  }
17346#endif
17347}
17348
17349SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
17350  static const sqlite3_mutex_methods sMutex = {
17351    pthreadMutexInit,
17352    pthreadMutexEnd,
17353    pthreadMutexAlloc,
17354    pthreadMutexFree,
17355    pthreadMutexEnter,
17356    pthreadMutexTry,
17357    pthreadMutexLeave,
17358#ifdef SQLITE_DEBUG
17359    pthreadMutexHeld,
17360    pthreadMutexNotheld
17361#else
17362    0,
17363    0
17364#endif
17365  };
17366
17367  return &sMutex;
17368}
17369
17370#endif /* SQLITE_MUTEX_PTHREAD */
17371
17372/************** End of mutex_unix.c ******************************************/
17373/************** Begin file mutex_w32.c ***************************************/
17374/*
17375** 2007 August 14
17376**
17377** The author disclaims copyright to this source code.  In place of
17378** a legal notice, here is a blessing:
17379**
17380**    May you do good and not evil.
17381**    May you find forgiveness for yourself and forgive others.
17382**    May you share freely, never taking more than you give.
17383**
17384*************************************************************************
17385** This file contains the C functions that implement mutexes for win32
17386*/
17387
17388/*
17389** The code in this file is only used if we are compiling multithreaded
17390** on a win32 system.
17391*/
17392#ifdef SQLITE_MUTEX_W32
17393
17394/*
17395** Each recursive mutex is an instance of the following structure.
17396*/
17397struct sqlite3_mutex {
17398  CRITICAL_SECTION mutex;    /* Mutex controlling the lock */
17399  int id;                    /* Mutex type */
17400#ifdef SQLITE_DEBUG
17401  volatile int nRef;         /* Number of enterances */
17402  volatile DWORD owner;      /* Thread holding this mutex */
17403  int trace;                 /* True to trace changes */
17404#endif
17405};
17406#define SQLITE_W32_MUTEX_INITIALIZER { 0 }
17407#ifdef SQLITE_DEBUG
17408#define SQLITE3_MUTEX_INITIALIZER { SQLITE_W32_MUTEX_INITIALIZER, 0, 0L, (DWORD)0, 0 }
17409#else
17410#define SQLITE3_MUTEX_INITIALIZER { SQLITE_W32_MUTEX_INITIALIZER, 0 }
17411#endif
17412
17413/*
17414** Return true (non-zero) if we are running under WinNT, Win2K, WinXP,
17415** or WinCE.  Return false (zero) for Win95, Win98, or WinME.
17416**
17417** Here is an interesting observation:  Win95, Win98, and WinME lack
17418** the LockFileEx() API.  But we can still statically link against that
17419** API as long as we don't call it win running Win95/98/ME.  A call to
17420** this routine is used to determine if the host is Win95/98/ME or
17421** WinNT/2K/XP so that we will know whether or not we can safely call
17422** the LockFileEx() API.
17423**
17424** mutexIsNT() is only used for the TryEnterCriticalSection() API call,
17425** which is only available if your application was compiled with
17426** _WIN32_WINNT defined to a value >= 0x0400.  Currently, the only
17427** call to TryEnterCriticalSection() is #ifdef'ed out, so #ifdef
17428** this out as well.
17429*/
17430#if 0
17431#if SQLITE_OS_WINCE
17432# define mutexIsNT()  (1)
17433#else
17434  static int mutexIsNT(void){
17435    static int osType = 0;
17436    if( osType==0 ){
17437      OSVERSIONINFO sInfo;
17438      sInfo.dwOSVersionInfoSize = sizeof(sInfo);
17439      GetVersionEx(&sInfo);
17440      osType = sInfo.dwPlatformId==VER_PLATFORM_WIN32_NT ? 2 : 1;
17441    }
17442    return osType==2;
17443  }
17444#endif /* SQLITE_OS_WINCE */
17445#endif
17446
17447#ifdef SQLITE_DEBUG
17448/*
17449** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
17450** intended for use only inside assert() statements.
17451*/
17452static int winMutexHeld(sqlite3_mutex *p){
17453  return p->nRef!=0 && p->owner==GetCurrentThreadId();
17454}
17455static int winMutexNotheld2(sqlite3_mutex *p, DWORD tid){
17456  return p->nRef==0 || p->owner!=tid;
17457}
17458static int winMutexNotheld(sqlite3_mutex *p){
17459  DWORD tid = GetCurrentThreadId();
17460  return winMutexNotheld2(p, tid);
17461}
17462#endif
17463
17464
17465/*
17466** Initialize and deinitialize the mutex subsystem.
17467*/
17468static sqlite3_mutex winMutex_staticMutexes[6] = {
17469  SQLITE3_MUTEX_INITIALIZER,
17470  SQLITE3_MUTEX_INITIALIZER,
17471  SQLITE3_MUTEX_INITIALIZER,
17472  SQLITE3_MUTEX_INITIALIZER,
17473  SQLITE3_MUTEX_INITIALIZER,
17474  SQLITE3_MUTEX_INITIALIZER
17475};
17476static int winMutex_isInit = 0;
17477/* As winMutexInit() and winMutexEnd() are called as part
17478** of the sqlite3_initialize and sqlite3_shutdown()
17479** processing, the "interlocked" magic is probably not
17480** strictly necessary.
17481*/
17482static long winMutex_lock = 0;
17483
17484static int winMutexInit(void){
17485  /* The first to increment to 1 does actual initialization */
17486  if( InterlockedCompareExchange(&winMutex_lock, 1, 0)==0 ){
17487    int i;
17488    for(i=0; i<ArraySize(winMutex_staticMutexes); i++){
17489      InitializeCriticalSection(&winMutex_staticMutexes[i].mutex);
17490    }
17491    winMutex_isInit = 1;
17492  }else{
17493    /* Someone else is in the process of initing the static mutexes */
17494    while( !winMutex_isInit ){
17495      Sleep(1);
17496    }
17497  }
17498  return SQLITE_OK;
17499}
17500
17501static int winMutexEnd(void){
17502  /* The first to decrement to 0 does actual shutdown
17503  ** (which should be the last to shutdown.) */
17504  if( InterlockedCompareExchange(&winMutex_lock, 0, 1)==1 ){
17505    if( winMutex_isInit==1 ){
17506      int i;
17507      for(i=0; i<ArraySize(winMutex_staticMutexes); i++){
17508        DeleteCriticalSection(&winMutex_staticMutexes[i].mutex);
17509      }
17510      winMutex_isInit = 0;
17511    }
17512  }
17513  return SQLITE_OK;
17514}
17515
17516/*
17517** The sqlite3_mutex_alloc() routine allocates a new
17518** mutex and returns a pointer to it.  If it returns NULL
17519** that means that a mutex could not be allocated.  SQLite
17520** will unwind its stack and return an error.  The argument
17521** to sqlite3_mutex_alloc() is one of these integer constants:
17522**
17523** <ul>
17524** <li>  SQLITE_MUTEX_FAST
17525** <li>  SQLITE_MUTEX_RECURSIVE
17526** <li>  SQLITE_MUTEX_STATIC_MASTER
17527** <li>  SQLITE_MUTEX_STATIC_MEM
17528** <li>  SQLITE_MUTEX_STATIC_MEM2
17529** <li>  SQLITE_MUTEX_STATIC_PRNG
17530** <li>  SQLITE_MUTEX_STATIC_LRU
17531** <li>  SQLITE_MUTEX_STATIC_PMEM
17532** </ul>
17533**
17534** The first two constants cause sqlite3_mutex_alloc() to create
17535** a new mutex.  The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
17536** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
17537** The mutex implementation does not need to make a distinction
17538** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
17539** not want to.  But SQLite will only request a recursive mutex in
17540** cases where it really needs one.  If a faster non-recursive mutex
17541** implementation is available on the host platform, the mutex subsystem
17542** might return such a mutex in response to SQLITE_MUTEX_FAST.
17543**
17544** The other allowed parameters to sqlite3_mutex_alloc() each return
17545** a pointer to a static preexisting mutex.  Six static mutexes are
17546** used by the current version of SQLite.  Future versions of SQLite
17547** may add additional static mutexes.  Static mutexes are for internal
17548** use by SQLite only.  Applications that use SQLite mutexes should
17549** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
17550** SQLITE_MUTEX_RECURSIVE.
17551**
17552** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
17553** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
17554** returns a different mutex on every call.  But for the static
17555** mutex types, the same mutex is returned on every call that has
17556** the same type number.
17557*/
17558static sqlite3_mutex *winMutexAlloc(int iType){
17559  sqlite3_mutex *p;
17560
17561  switch( iType ){
17562    case SQLITE_MUTEX_FAST:
17563    case SQLITE_MUTEX_RECURSIVE: {
17564      p = sqlite3MallocZero( sizeof(*p) );
17565      if( p ){
17566#ifdef SQLITE_DEBUG
17567        p->id = iType;
17568#endif
17569        InitializeCriticalSection(&p->mutex);
17570      }
17571      break;
17572    }
17573    default: {
17574      assert( winMutex_isInit==1 );
17575      assert( iType-2 >= 0 );
17576      assert( iType-2 < ArraySize(winMutex_staticMutexes) );
17577      p = &winMutex_staticMutexes[iType-2];
17578#ifdef SQLITE_DEBUG
17579      p->id = iType;
17580#endif
17581      break;
17582    }
17583  }
17584  return p;
17585}
17586
17587
17588/*
17589** This routine deallocates a previously
17590** allocated mutex.  SQLite is careful to deallocate every
17591** mutex that it allocates.
17592*/
17593static void winMutexFree(sqlite3_mutex *p){
17594  assert( p );
17595  assert( p->nRef==0 && p->owner==0 );
17596  assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
17597  DeleteCriticalSection(&p->mutex);
17598  sqlite3_free(p);
17599}
17600
17601/*
17602** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
17603** to enter a mutex.  If another thread is already within the mutex,
17604** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
17605** SQLITE_BUSY.  The sqlite3_mutex_try() interface returns SQLITE_OK
17606** upon successful entry.  Mutexes created using SQLITE_MUTEX_RECURSIVE can
17607** be entered multiple times by the same thread.  In such cases the,
17608** mutex must be exited an equal number of times before another thread
17609** can enter.  If the same thread tries to enter any other kind of mutex
17610** more than once, the behavior is undefined.
17611*/
17612static void winMutexEnter(sqlite3_mutex *p){
17613#ifdef SQLITE_DEBUG
17614  DWORD tid = GetCurrentThreadId();
17615  assert( p->id==SQLITE_MUTEX_RECURSIVE || winMutexNotheld2(p, tid) );
17616#endif
17617  EnterCriticalSection(&p->mutex);
17618#ifdef SQLITE_DEBUG
17619  assert( p->nRef>0 || p->owner==0 );
17620  p->owner = tid;
17621  p->nRef++;
17622  if( p->trace ){
17623    printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
17624  }
17625#endif
17626}
17627static int winMutexTry(sqlite3_mutex *p){
17628#ifndef NDEBUG
17629  DWORD tid = GetCurrentThreadId();
17630#endif
17631  int rc = SQLITE_BUSY;
17632  assert( p->id==SQLITE_MUTEX_RECURSIVE || winMutexNotheld2(p, tid) );
17633  /*
17634  ** The sqlite3_mutex_try() routine is very rarely used, and when it
17635  ** is used it is merely an optimization.  So it is OK for it to always
17636  ** fail.
17637  **
17638  ** The TryEnterCriticalSection() interface is only available on WinNT.
17639  ** And some windows compilers complain if you try to use it without
17640  ** first doing some #defines that prevent SQLite from building on Win98.
17641  ** For that reason, we will omit this optimization for now.  See
17642  ** ticket #2685.
17643  */
17644#if 0
17645  if( mutexIsNT() && TryEnterCriticalSection(&p->mutex) ){
17646    p->owner = tid;
17647    p->nRef++;
17648    rc = SQLITE_OK;
17649  }
17650#else
17651  UNUSED_PARAMETER(p);
17652#endif
17653#ifdef SQLITE_DEBUG
17654  if( rc==SQLITE_OK && p->trace ){
17655    printf("try mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
17656  }
17657#endif
17658  return rc;
17659}
17660
17661/*
17662** The sqlite3_mutex_leave() routine exits a mutex that was
17663** previously entered by the same thread.  The behavior
17664** is undefined if the mutex is not currently entered or
17665** is not currently allocated.  SQLite will never do either.
17666*/
17667static void winMutexLeave(sqlite3_mutex *p){
17668#ifndef NDEBUG
17669  DWORD tid = GetCurrentThreadId();
17670  assert( p->nRef>0 );
17671  assert( p->owner==tid );
17672  p->nRef--;
17673  if( p->nRef==0 ) p->owner = 0;
17674  assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
17675#endif
17676  LeaveCriticalSection(&p->mutex);
17677#ifdef SQLITE_DEBUG
17678  if( p->trace ){
17679    printf("leave mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
17680  }
17681#endif
17682}
17683
17684SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
17685  static const sqlite3_mutex_methods sMutex = {
17686    winMutexInit,
17687    winMutexEnd,
17688    winMutexAlloc,
17689    winMutexFree,
17690    winMutexEnter,
17691    winMutexTry,
17692    winMutexLeave,
17693#ifdef SQLITE_DEBUG
17694    winMutexHeld,
17695    winMutexNotheld
17696#else
17697    0,
17698    0
17699#endif
17700  };
17701
17702  return &sMutex;
17703}
17704#endif /* SQLITE_MUTEX_W32 */
17705
17706/************** End of mutex_w32.c *******************************************/
17707/************** Begin file malloc.c ******************************************/
17708/*
17709** 2001 September 15
17710**
17711** The author disclaims copyright to this source code.  In place of
17712** a legal notice, here is a blessing:
17713**
17714**    May you do good and not evil.
17715**    May you find forgiveness for yourself and forgive others.
17716**    May you share freely, never taking more than you give.
17717**
17718*************************************************************************
17719**
17720** Memory allocation functions used throughout sqlite.
17721*/
17722
17723/*
17724** Attempt to release up to n bytes of non-essential memory currently
17725** held by SQLite. An example of non-essential memory is memory used to
17726** cache database pages that are not currently in use.
17727*/
17728SQLITE_API int sqlite3_release_memory(int n){
17729#ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
17730  return sqlite3PcacheReleaseMemory(n);
17731#else
17732  /* IMPLEMENTATION-OF: R-34391-24921 The sqlite3_release_memory() routine
17733  ** is a no-op returning zero if SQLite is not compiled with
17734  ** SQLITE_ENABLE_MEMORY_MANAGEMENT. */
17735  UNUSED_PARAMETER(n);
17736  return 0;
17737#endif
17738}
17739
17740/*
17741** An instance of the following object records the location of
17742** each unused scratch buffer.
17743*/
17744typedef struct ScratchFreeslot {
17745  struct ScratchFreeslot *pNext;   /* Next unused scratch buffer */
17746} ScratchFreeslot;
17747
17748/*
17749** State information local to the memory allocation subsystem.
17750*/
17751static SQLITE_WSD struct Mem0Global {
17752  sqlite3_mutex *mutex;         /* Mutex to serialize access */
17753
17754  /*
17755  ** The alarm callback and its arguments.  The mem0.mutex lock will
17756  ** be held while the callback is running.  Recursive calls into
17757  ** the memory subsystem are allowed, but no new callbacks will be
17758  ** issued.
17759  */
17760  sqlite3_int64 alarmThreshold;
17761  void (*alarmCallback)(void*, sqlite3_int64,int);
17762  void *alarmArg;
17763
17764  /*
17765  ** Pointers to the end of sqlite3GlobalConfig.pScratch memory
17766  ** (so that a range test can be used to determine if an allocation
17767  ** being freed came from pScratch) and a pointer to the list of
17768  ** unused scratch allocations.
17769  */
17770  void *pScratchEnd;
17771  ScratchFreeslot *pScratchFree;
17772  u32 nScratchFree;
17773
17774  /*
17775  ** True if heap is nearly "full" where "full" is defined by the
17776  ** sqlite3_soft_heap_limit() setting.
17777  */
17778  int nearlyFull;
17779} mem0 = { 0, 0, 0, 0, 0, 0, 0, 0 };
17780
17781#define mem0 GLOBAL(struct Mem0Global, mem0)
17782
17783/*
17784** This routine runs when the memory allocator sees that the
17785** total memory allocation is about to exceed the soft heap
17786** limit.
17787*/
17788static void softHeapLimitEnforcer(
17789  void *NotUsed,
17790  sqlite3_int64 NotUsed2,
17791  int allocSize
17792){
17793  UNUSED_PARAMETER2(NotUsed, NotUsed2);
17794  sqlite3_release_memory(allocSize);
17795}
17796
17797/*
17798** Change the alarm callback
17799*/
17800static int sqlite3MemoryAlarm(
17801  void(*xCallback)(void *pArg, sqlite3_int64 used,int N),
17802  void *pArg,
17803  sqlite3_int64 iThreshold
17804){
17805  int nUsed;
17806  sqlite3_mutex_enter(mem0.mutex);
17807  mem0.alarmCallback = xCallback;
17808  mem0.alarmArg = pArg;
17809  mem0.alarmThreshold = iThreshold;
17810  nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
17811  mem0.nearlyFull = (iThreshold>0 && iThreshold<=nUsed);
17812  sqlite3_mutex_leave(mem0.mutex);
17813  return SQLITE_OK;
17814}
17815
17816#ifndef SQLITE_OMIT_DEPRECATED
17817/*
17818** Deprecated external interface.  Internal/core SQLite code
17819** should call sqlite3MemoryAlarm.
17820*/
17821SQLITE_API int sqlite3_memory_alarm(
17822  void(*xCallback)(void *pArg, sqlite3_int64 used,int N),
17823  void *pArg,
17824  sqlite3_int64 iThreshold
17825){
17826  return sqlite3MemoryAlarm(xCallback, pArg, iThreshold);
17827}
17828#endif
17829
17830/*
17831** Set the soft heap-size limit for the library. Passing a zero or
17832** negative value indicates no limit.
17833*/
17834SQLITE_API sqlite3_int64 sqlite3_soft_heap_limit64(sqlite3_int64 n){
17835  sqlite3_int64 priorLimit;
17836  sqlite3_int64 excess;
17837#ifndef SQLITE_OMIT_AUTOINIT
17838  sqlite3_initialize();
17839#endif
17840  sqlite3_mutex_enter(mem0.mutex);
17841  priorLimit = mem0.alarmThreshold;
17842  sqlite3_mutex_leave(mem0.mutex);
17843  if( n<0 ) return priorLimit;
17844  if( n>0 ){
17845    sqlite3MemoryAlarm(softHeapLimitEnforcer, 0, n);
17846  }else{
17847    sqlite3MemoryAlarm(0, 0, 0);
17848  }
17849  excess = sqlite3_memory_used() - n;
17850  if( excess>0 ) sqlite3_release_memory((int)(excess & 0x7fffffff));
17851  return priorLimit;
17852}
17853SQLITE_API void sqlite3_soft_heap_limit(int n){
17854  if( n<0 ) n = 0;
17855  sqlite3_soft_heap_limit64(n);
17856}
17857
17858/*
17859** Initialize the memory allocation subsystem.
17860*/
17861SQLITE_PRIVATE int sqlite3MallocInit(void){
17862  if( sqlite3GlobalConfig.m.xMalloc==0 ){
17863    sqlite3MemSetDefault();
17864  }
17865  memset(&mem0, 0, sizeof(mem0));
17866  if( sqlite3GlobalConfig.bCoreMutex ){
17867    mem0.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
17868  }
17869  if( sqlite3GlobalConfig.pScratch && sqlite3GlobalConfig.szScratch>=100
17870      && sqlite3GlobalConfig.nScratch>0 ){
17871    int i, n, sz;
17872    ScratchFreeslot *pSlot;
17873    sz = ROUNDDOWN8(sqlite3GlobalConfig.szScratch);
17874    sqlite3GlobalConfig.szScratch = sz;
17875    pSlot = (ScratchFreeslot*)sqlite3GlobalConfig.pScratch;
17876    n = sqlite3GlobalConfig.nScratch;
17877    mem0.pScratchFree = pSlot;
17878    mem0.nScratchFree = n;
17879    for(i=0; i<n-1; i++){
17880      pSlot->pNext = (ScratchFreeslot*)(sz+(char*)pSlot);
17881      pSlot = pSlot->pNext;
17882    }
17883    pSlot->pNext = 0;
17884    mem0.pScratchEnd = (void*)&pSlot[1];
17885  }else{
17886    mem0.pScratchEnd = 0;
17887    sqlite3GlobalConfig.pScratch = 0;
17888    sqlite3GlobalConfig.szScratch = 0;
17889    sqlite3GlobalConfig.nScratch = 0;
17890  }
17891  if( sqlite3GlobalConfig.pPage==0 || sqlite3GlobalConfig.szPage<512
17892      || sqlite3GlobalConfig.nPage<1 ){
17893    sqlite3GlobalConfig.pPage = 0;
17894    sqlite3GlobalConfig.szPage = 0;
17895    sqlite3GlobalConfig.nPage = 0;
17896  }
17897  return sqlite3GlobalConfig.m.xInit(sqlite3GlobalConfig.m.pAppData);
17898}
17899
17900/*
17901** Return true if the heap is currently under memory pressure - in other
17902** words if the amount of heap used is close to the limit set by
17903** sqlite3_soft_heap_limit().
17904*/
17905SQLITE_PRIVATE int sqlite3HeapNearlyFull(void){
17906  return mem0.nearlyFull;
17907}
17908
17909/*
17910** Deinitialize the memory allocation subsystem.
17911*/
17912SQLITE_PRIVATE void sqlite3MallocEnd(void){
17913  if( sqlite3GlobalConfig.m.xShutdown ){
17914    sqlite3GlobalConfig.m.xShutdown(sqlite3GlobalConfig.m.pAppData);
17915  }
17916  memset(&mem0, 0, sizeof(mem0));
17917}
17918
17919/*
17920** Return the amount of memory currently checked out.
17921*/
17922SQLITE_API sqlite3_int64 sqlite3_memory_used(void){
17923  int n, mx;
17924  sqlite3_int64 res;
17925  sqlite3_status(SQLITE_STATUS_MEMORY_USED, &n, &mx, 0);
17926  res = (sqlite3_int64)n;  /* Work around bug in Borland C. Ticket #3216 */
17927  return res;
17928}
17929
17930/*
17931** Return the maximum amount of memory that has ever been
17932** checked out since either the beginning of this process
17933** or since the most recent reset.
17934*/
17935SQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag){
17936  int n, mx;
17937  sqlite3_int64 res;
17938  sqlite3_status(SQLITE_STATUS_MEMORY_USED, &n, &mx, resetFlag);
17939  res = (sqlite3_int64)mx;  /* Work around bug in Borland C. Ticket #3216 */
17940  return res;
17941}
17942
17943/*
17944** Trigger the alarm
17945*/
17946static void sqlite3MallocAlarm(int nByte){
17947  void (*xCallback)(void*,sqlite3_int64,int);
17948  sqlite3_int64 nowUsed;
17949  void *pArg;
17950  if( mem0.alarmCallback==0 ) return;
17951  xCallback = mem0.alarmCallback;
17952  nowUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
17953  pArg = mem0.alarmArg;
17954  mem0.alarmCallback = 0;
17955  sqlite3_mutex_leave(mem0.mutex);
17956  xCallback(pArg, nowUsed, nByte);
17957  sqlite3_mutex_enter(mem0.mutex);
17958  mem0.alarmCallback = xCallback;
17959  mem0.alarmArg = pArg;
17960}
17961
17962/*
17963** Do a memory allocation with statistics and alarms.  Assume the
17964** lock is already held.
17965*/
17966static int mallocWithAlarm(int n, void **pp){
17967  int nFull;
17968  void *p;
17969  assert( sqlite3_mutex_held(mem0.mutex) );
17970  nFull = sqlite3GlobalConfig.m.xRoundup(n);
17971  sqlite3StatusSet(SQLITE_STATUS_MALLOC_SIZE, n);
17972  if( mem0.alarmCallback!=0 ){
17973    int nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
17974    if( nUsed+nFull >= mem0.alarmThreshold ){
17975      mem0.nearlyFull = 1;
17976      sqlite3MallocAlarm(nFull);
17977    }else{
17978      mem0.nearlyFull = 0;
17979    }
17980  }
17981  p = sqlite3GlobalConfig.m.xMalloc(nFull);
17982#ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
17983  if( p==0 && mem0.alarmCallback ){
17984    sqlite3MallocAlarm(nFull);
17985    p = sqlite3GlobalConfig.m.xMalloc(nFull);
17986  }
17987#endif
17988  if( p ){
17989    nFull = sqlite3MallocSize(p);
17990    sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, nFull);
17991    sqlite3StatusAdd(SQLITE_STATUS_MALLOC_COUNT, 1);
17992  }
17993  *pp = p;
17994  return nFull;
17995}
17996
17997/*
17998** Allocate memory.  This routine is like sqlite3_malloc() except that it
17999** assumes the memory subsystem has already been initialized.
18000*/
18001SQLITE_PRIVATE void *sqlite3Malloc(int n){
18002  void *p;
18003  if( n<=0               /* IMP: R-65312-04917 */
18004   || n>=0x7fffff00
18005  ){
18006    /* A memory allocation of a number of bytes which is near the maximum
18007    ** signed integer value might cause an integer overflow inside of the
18008    ** xMalloc().  Hence we limit the maximum size to 0x7fffff00, giving
18009    ** 255 bytes of overhead.  SQLite itself will never use anything near
18010    ** this amount.  The only way to reach the limit is with sqlite3_malloc() */
18011    p = 0;
18012  }else if( sqlite3GlobalConfig.bMemstat ){
18013    sqlite3_mutex_enter(mem0.mutex);
18014    mallocWithAlarm(n, &p);
18015    sqlite3_mutex_leave(mem0.mutex);
18016  }else{
18017    p = sqlite3GlobalConfig.m.xMalloc(n);
18018  }
18019  assert( EIGHT_BYTE_ALIGNMENT(p) );  /* IMP: R-04675-44850 */
18020  return p;
18021}
18022
18023/*
18024** This version of the memory allocation is for use by the application.
18025** First make sure the memory subsystem is initialized, then do the
18026** allocation.
18027*/
18028SQLITE_API void *sqlite3_malloc(int n){
18029#ifndef SQLITE_OMIT_AUTOINIT
18030  if( sqlite3_initialize() ) return 0;
18031#endif
18032  return sqlite3Malloc(n);
18033}
18034
18035/*
18036** Each thread may only have a single outstanding allocation from
18037** xScratchMalloc().  We verify this constraint in the single-threaded
18038** case by setting scratchAllocOut to 1 when an allocation
18039** is outstanding clearing it when the allocation is freed.
18040*/
18041#if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
18042static int scratchAllocOut = 0;
18043#endif
18044
18045
18046/*
18047** Allocate memory that is to be used and released right away.
18048** This routine is similar to alloca() in that it is not intended
18049** for situations where the memory might be held long-term.  This
18050** routine is intended to get memory to old large transient data
18051** structures that would not normally fit on the stack of an
18052** embedded processor.
18053*/
18054SQLITE_PRIVATE void *sqlite3ScratchMalloc(int n){
18055  void *p;
18056  assert( n>0 );
18057
18058  sqlite3_mutex_enter(mem0.mutex);
18059  if( mem0.nScratchFree && sqlite3GlobalConfig.szScratch>=n ){
18060    p = mem0.pScratchFree;
18061    mem0.pScratchFree = mem0.pScratchFree->pNext;
18062    mem0.nScratchFree--;
18063    sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_USED, 1);
18064    sqlite3StatusSet(SQLITE_STATUS_SCRATCH_SIZE, n);
18065    sqlite3_mutex_leave(mem0.mutex);
18066  }else{
18067    if( sqlite3GlobalConfig.bMemstat ){
18068      sqlite3StatusSet(SQLITE_STATUS_SCRATCH_SIZE, n);
18069      n = mallocWithAlarm(n, &p);
18070      if( p ) sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_OVERFLOW, n);
18071      sqlite3_mutex_leave(mem0.mutex);
18072    }else{
18073      sqlite3_mutex_leave(mem0.mutex);
18074      p = sqlite3GlobalConfig.m.xMalloc(n);
18075    }
18076    sqlite3MemdebugSetType(p, MEMTYPE_SCRATCH);
18077  }
18078  assert( sqlite3_mutex_notheld(mem0.mutex) );
18079
18080
18081#if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
18082  /* Verify that no more than two scratch allocations per thread
18083  ** are outstanding at one time.  (This is only checked in the
18084  ** single-threaded case since checking in the multi-threaded case
18085  ** would be much more complicated.) */
18086  assert( scratchAllocOut<=1 );
18087  if( p ) scratchAllocOut++;
18088#endif
18089
18090  return p;
18091}
18092SQLITE_PRIVATE void sqlite3ScratchFree(void *p){
18093  if( p ){
18094
18095#if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
18096    /* Verify that no more than two scratch allocation per thread
18097    ** is outstanding at one time.  (This is only checked in the
18098    ** single-threaded case since checking in the multi-threaded case
18099    ** would be much more complicated.) */
18100    assert( scratchAllocOut>=1 && scratchAllocOut<=2 );
18101    scratchAllocOut--;
18102#endif
18103
18104    if( p>=sqlite3GlobalConfig.pScratch && p<mem0.pScratchEnd ){
18105      /* Release memory from the SQLITE_CONFIG_SCRATCH allocation */
18106      ScratchFreeslot *pSlot;
18107      pSlot = (ScratchFreeslot*)p;
18108      sqlite3_mutex_enter(mem0.mutex);
18109      pSlot->pNext = mem0.pScratchFree;
18110      mem0.pScratchFree = pSlot;
18111      mem0.nScratchFree++;
18112      assert( mem0.nScratchFree <= (u32)sqlite3GlobalConfig.nScratch );
18113      sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_USED, -1);
18114      sqlite3_mutex_leave(mem0.mutex);
18115    }else{
18116      /* Release memory back to the heap */
18117      assert( sqlite3MemdebugHasType(p, MEMTYPE_SCRATCH) );
18118      assert( sqlite3MemdebugNoType(p, ~MEMTYPE_SCRATCH) );
18119      sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
18120      if( sqlite3GlobalConfig.bMemstat ){
18121        int iSize = sqlite3MallocSize(p);
18122        sqlite3_mutex_enter(mem0.mutex);
18123        sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_OVERFLOW, -iSize);
18124        sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, -iSize);
18125        sqlite3StatusAdd(SQLITE_STATUS_MALLOC_COUNT, -1);
18126        sqlite3GlobalConfig.m.xFree(p);
18127        sqlite3_mutex_leave(mem0.mutex);
18128      }else{
18129        sqlite3GlobalConfig.m.xFree(p);
18130      }
18131    }
18132  }
18133}
18134
18135/*
18136** TRUE if p is a lookaside memory allocation from db
18137*/
18138#ifndef SQLITE_OMIT_LOOKASIDE
18139static int isLookaside(sqlite3 *db, void *p){
18140  return p && p>=db->lookaside.pStart && p<db->lookaside.pEnd;
18141}
18142#else
18143#define isLookaside(A,B) 0
18144#endif
18145
18146/*
18147** Return the size of a memory allocation previously obtained from
18148** sqlite3Malloc() or sqlite3_malloc().
18149*/
18150SQLITE_PRIVATE int sqlite3MallocSize(void *p){
18151  assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
18152  assert( sqlite3MemdebugNoType(p, MEMTYPE_DB) );
18153  return sqlite3GlobalConfig.m.xSize(p);
18154}
18155SQLITE_PRIVATE int sqlite3DbMallocSize(sqlite3 *db, void *p){
18156  assert( db==0 || sqlite3_mutex_held(db->mutex) );
18157  if( db && isLookaside(db, p) ){
18158    return db->lookaside.sz;
18159  }else{
18160    assert( sqlite3MemdebugHasType(p, MEMTYPE_DB) );
18161    assert( sqlite3MemdebugHasType(p, MEMTYPE_LOOKASIDE|MEMTYPE_HEAP) );
18162    assert( db!=0 || sqlite3MemdebugNoType(p, MEMTYPE_LOOKASIDE) );
18163    return sqlite3GlobalConfig.m.xSize(p);
18164  }
18165}
18166
18167/*
18168** Free memory previously obtained from sqlite3Malloc().
18169*/
18170SQLITE_API void sqlite3_free(void *p){
18171  if( p==0 ) return;  /* IMP: R-49053-54554 */
18172  assert( sqlite3MemdebugNoType(p, MEMTYPE_DB) );
18173  assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
18174  if( sqlite3GlobalConfig.bMemstat ){
18175    sqlite3_mutex_enter(mem0.mutex);
18176    sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, -sqlite3MallocSize(p));
18177    sqlite3StatusAdd(SQLITE_STATUS_MALLOC_COUNT, -1);
18178    sqlite3GlobalConfig.m.xFree(p);
18179    sqlite3_mutex_leave(mem0.mutex);
18180  }else{
18181    sqlite3GlobalConfig.m.xFree(p);
18182  }
18183}
18184
18185/*
18186** Free memory that might be associated with a particular database
18187** connection.
18188*/
18189SQLITE_PRIVATE void sqlite3DbFree(sqlite3 *db, void *p){
18190  assert( db==0 || sqlite3_mutex_held(db->mutex) );
18191  if( db ){
18192    if( db->pnBytesFreed ){
18193      *db->pnBytesFreed += sqlite3DbMallocSize(db, p);
18194      return;
18195    }
18196    if( isLookaside(db, p) ){
18197      LookasideSlot *pBuf = (LookasideSlot*)p;
18198      pBuf->pNext = db->lookaside.pFree;
18199      db->lookaside.pFree = pBuf;
18200      db->lookaside.nOut--;
18201      return;
18202    }
18203  }
18204  assert( sqlite3MemdebugHasType(p, MEMTYPE_DB) );
18205  assert( sqlite3MemdebugHasType(p, MEMTYPE_LOOKASIDE|MEMTYPE_HEAP) );
18206  assert( db!=0 || sqlite3MemdebugNoType(p, MEMTYPE_LOOKASIDE) );
18207  sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
18208  sqlite3_free(p);
18209}
18210
18211/*
18212** Change the size of an existing memory allocation
18213*/
18214SQLITE_PRIVATE void *sqlite3Realloc(void *pOld, int nBytes){
18215  int nOld, nNew;
18216  void *pNew;
18217  if( pOld==0 ){
18218    return sqlite3Malloc(nBytes); /* IMP: R-28354-25769 */
18219  }
18220  if( nBytes<=0 ){
18221    sqlite3_free(pOld); /* IMP: R-31593-10574 */
18222    return 0;
18223  }
18224  if( nBytes>=0x7fffff00 ){
18225    /* The 0x7ffff00 limit term is explained in comments on sqlite3Malloc() */
18226    return 0;
18227  }
18228  nOld = sqlite3MallocSize(pOld);
18229  /* IMPLEMENTATION-OF: R-46199-30249 SQLite guarantees that the second
18230  ** argument to xRealloc is always a value returned by a prior call to
18231  ** xRoundup. */
18232  nNew = sqlite3GlobalConfig.m.xRoundup(nBytes);
18233  if( nOld==nNew ){
18234    pNew = pOld;
18235  }else if( sqlite3GlobalConfig.bMemstat ){
18236    sqlite3_mutex_enter(mem0.mutex);
18237    sqlite3StatusSet(SQLITE_STATUS_MALLOC_SIZE, nBytes);
18238    if( sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED)+nNew-nOld >=
18239          mem0.alarmThreshold ){
18240      sqlite3MallocAlarm(nNew-nOld);
18241    }
18242    assert( sqlite3MemdebugHasType(pOld, MEMTYPE_HEAP) );
18243    assert( sqlite3MemdebugNoType(pOld, ~MEMTYPE_HEAP) );
18244    pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
18245    if( pNew==0 && mem0.alarmCallback ){
18246      sqlite3MallocAlarm(nBytes);
18247      pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
18248    }
18249    if( pNew ){
18250      nNew = sqlite3MallocSize(pNew);
18251      sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, nNew-nOld);
18252    }
18253    sqlite3_mutex_leave(mem0.mutex);
18254  }else{
18255    pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
18256  }
18257  assert( EIGHT_BYTE_ALIGNMENT(pNew) ); /* IMP: R-04675-44850 */
18258  return pNew;
18259}
18260
18261/*
18262** The public interface to sqlite3Realloc.  Make sure that the memory
18263** subsystem is initialized prior to invoking sqliteRealloc.
18264*/
18265SQLITE_API void *sqlite3_realloc(void *pOld, int n){
18266#ifndef SQLITE_OMIT_AUTOINIT
18267  if( sqlite3_initialize() ) return 0;
18268#endif
18269  return sqlite3Realloc(pOld, n);
18270}
18271
18272
18273/*
18274** Allocate and zero memory.
18275*/
18276SQLITE_PRIVATE void *sqlite3MallocZero(int n){
18277  void *p = sqlite3Malloc(n);
18278  if( p ){
18279    memset(p, 0, n);
18280  }
18281  return p;
18282}
18283
18284/*
18285** Allocate and zero memory.  If the allocation fails, make
18286** the mallocFailed flag in the connection pointer.
18287*/
18288SQLITE_PRIVATE void *sqlite3DbMallocZero(sqlite3 *db, int n){
18289  void *p = sqlite3DbMallocRaw(db, n);
18290  if( p ){
18291    memset(p, 0, n);
18292  }
18293  return p;
18294}
18295
18296/*
18297** Allocate and zero memory.  If the allocation fails, make
18298** the mallocFailed flag in the connection pointer.
18299**
18300** If db!=0 and db->mallocFailed is true (indicating a prior malloc
18301** failure on the same database connection) then always return 0.
18302** Hence for a particular database connection, once malloc starts
18303** failing, it fails consistently until mallocFailed is reset.
18304** This is an important assumption.  There are many places in the
18305** code that do things like this:
18306**
18307**         int *a = (int*)sqlite3DbMallocRaw(db, 100);
18308**         int *b = (int*)sqlite3DbMallocRaw(db, 200);
18309**         if( b ) a[10] = 9;
18310**
18311** In other words, if a subsequent malloc (ex: "b") worked, it is assumed
18312** that all prior mallocs (ex: "a") worked too.
18313*/
18314SQLITE_PRIVATE void *sqlite3DbMallocRaw(sqlite3 *db, int n){
18315  void *p;
18316  assert( db==0 || sqlite3_mutex_held(db->mutex) );
18317  assert( db==0 || db->pnBytesFreed==0 );
18318#ifndef SQLITE_OMIT_LOOKASIDE
18319  if( db ){
18320    LookasideSlot *pBuf;
18321    if( db->mallocFailed ){
18322      return 0;
18323    }
18324    if( db->lookaside.bEnabled ){
18325      if( n>db->lookaside.sz ){
18326        db->lookaside.anStat[1]++;
18327      }else if( (pBuf = db->lookaside.pFree)==0 ){
18328        db->lookaside.anStat[2]++;
18329      }else{
18330        db->lookaside.pFree = pBuf->pNext;
18331        db->lookaside.nOut++;
18332        db->lookaside.anStat[0]++;
18333        if( db->lookaside.nOut>db->lookaside.mxOut ){
18334          db->lookaside.mxOut = db->lookaside.nOut;
18335        }
18336        return (void*)pBuf;
18337      }
18338    }
18339  }
18340#else
18341  if( db && db->mallocFailed ){
18342    return 0;
18343  }
18344#endif
18345  p = sqlite3Malloc(n);
18346  if( !p && db ){
18347    db->mallocFailed = 1;
18348  }
18349  sqlite3MemdebugSetType(p, MEMTYPE_DB |
18350         ((db && db->lookaside.bEnabled) ? MEMTYPE_LOOKASIDE : MEMTYPE_HEAP));
18351  return p;
18352}
18353
18354/*
18355** Resize the block of memory pointed to by p to n bytes. If the
18356** resize fails, set the mallocFailed flag in the connection object.
18357*/
18358SQLITE_PRIVATE void *sqlite3DbRealloc(sqlite3 *db, void *p, int n){
18359  void *pNew = 0;
18360  assert( db!=0 );
18361  assert( sqlite3_mutex_held(db->mutex) );
18362  if( db->mallocFailed==0 ){
18363    if( p==0 ){
18364      return sqlite3DbMallocRaw(db, n);
18365    }
18366    if( isLookaside(db, p) ){
18367      if( n<=db->lookaside.sz ){
18368        return p;
18369      }
18370      pNew = sqlite3DbMallocRaw(db, n);
18371      if( pNew ){
18372        memcpy(pNew, p, db->lookaside.sz);
18373        sqlite3DbFree(db, p);
18374      }
18375    }else{
18376      assert( sqlite3MemdebugHasType(p, MEMTYPE_DB) );
18377      assert( sqlite3MemdebugHasType(p, MEMTYPE_LOOKASIDE|MEMTYPE_HEAP) );
18378      sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
18379      pNew = sqlite3_realloc(p, n);
18380      if( !pNew ){
18381        sqlite3MemdebugSetType(p, MEMTYPE_DB|MEMTYPE_HEAP);
18382        db->mallocFailed = 1;
18383      }
18384      sqlite3MemdebugSetType(pNew, MEMTYPE_DB |
18385            (db->lookaside.bEnabled ? MEMTYPE_LOOKASIDE : MEMTYPE_HEAP));
18386    }
18387  }
18388  return pNew;
18389}
18390
18391/*
18392** Attempt to reallocate p.  If the reallocation fails, then free p
18393** and set the mallocFailed flag in the database connection.
18394*/
18395SQLITE_PRIVATE void *sqlite3DbReallocOrFree(sqlite3 *db, void *p, int n){
18396  void *pNew;
18397  pNew = sqlite3DbRealloc(db, p, n);
18398  if( !pNew ){
18399    sqlite3DbFree(db, p);
18400  }
18401  return pNew;
18402}
18403
18404/*
18405** Make a copy of a string in memory obtained from sqliteMalloc(). These
18406** functions call sqlite3MallocRaw() directly instead of sqliteMalloc(). This
18407** is because when memory debugging is turned on, these two functions are
18408** called via macros that record the current file and line number in the
18409** ThreadData structure.
18410*/
18411SQLITE_PRIVATE char *sqlite3DbStrDup(sqlite3 *db, const char *z){
18412  char *zNew;
18413  size_t n;
18414  if( z==0 ){
18415    return 0;
18416  }
18417  n = sqlite3Strlen30(z) + 1;
18418  assert( (n&0x7fffffff)==n );
18419  zNew = sqlite3DbMallocRaw(db, (int)n);
18420  if( zNew ){
18421    memcpy(zNew, z, n);
18422  }
18423  return zNew;
18424}
18425SQLITE_PRIVATE char *sqlite3DbStrNDup(sqlite3 *db, const char *z, int n){
18426  char *zNew;
18427  if( z==0 ){
18428    return 0;
18429  }
18430  assert( (n&0x7fffffff)==n );
18431  zNew = sqlite3DbMallocRaw(db, n+1);
18432  if( zNew ){
18433    memcpy(zNew, z, n);
18434    zNew[n] = 0;
18435  }
18436  return zNew;
18437}
18438
18439/*
18440** Create a string from the zFromat argument and the va_list that follows.
18441** Store the string in memory obtained from sqliteMalloc() and make *pz
18442** point to that string.
18443*/
18444SQLITE_PRIVATE void sqlite3SetString(char **pz, sqlite3 *db, const char *zFormat, ...){
18445  va_list ap;
18446  char *z;
18447
18448  va_start(ap, zFormat);
18449  z = sqlite3VMPrintf(db, zFormat, ap);
18450  va_end(ap);
18451  sqlite3DbFree(db, *pz);
18452  *pz = z;
18453}
18454
18455
18456/*
18457** This function must be called before exiting any API function (i.e.
18458** returning control to the user) that has called sqlite3_malloc or
18459** sqlite3_realloc.
18460**
18461** The returned value is normally a copy of the second argument to this
18462** function. However, if a malloc() failure has occurred since the previous
18463** invocation SQLITE_NOMEM is returned instead.
18464**
18465** If the first argument, db, is not NULL and a malloc() error has occurred,
18466** then the connection error-code (the value returned by sqlite3_errcode())
18467** is set to SQLITE_NOMEM.
18468*/
18469SQLITE_PRIVATE int sqlite3ApiExit(sqlite3* db, int rc){
18470  /* If the db handle is not NULL, then we must hold the connection handle
18471  ** mutex here. Otherwise the read (and possible write) of db->mallocFailed
18472  ** is unsafe, as is the call to sqlite3Error().
18473  */
18474  assert( !db || sqlite3_mutex_held(db->mutex) );
18475  if( db && (db->mallocFailed || rc==SQLITE_IOERR_NOMEM) ){
18476    sqlite3Error(db, SQLITE_NOMEM, 0);
18477    db->mallocFailed = 0;
18478    rc = SQLITE_NOMEM;
18479  }
18480  return rc & (db ? db->errMask : 0xff);
18481}
18482
18483/************** End of malloc.c **********************************************/
18484/************** Begin file printf.c ******************************************/
18485/*
18486** The "printf" code that follows dates from the 1980's.  It is in
18487** the public domain.  The original comments are included here for
18488** completeness.  They are very out-of-date but might be useful as
18489** an historical reference.  Most of the "enhancements" have been backed
18490** out so that the functionality is now the same as standard printf().
18491**
18492**************************************************************************
18493**
18494** The following modules is an enhanced replacement for the "printf" subroutines
18495** found in the standard C library.  The following enhancements are
18496** supported:
18497**
18498**      +  Additional functions.  The standard set of "printf" functions
18499**         includes printf, fprintf, sprintf, vprintf, vfprintf, and
18500**         vsprintf.  This module adds the following:
18501**
18502**           *  snprintf -- Works like sprintf, but has an extra argument
18503**                          which is the size of the buffer written to.
18504**
18505**           *  mprintf --  Similar to sprintf.  Writes output to memory
18506**                          obtained from malloc.
18507**
18508**           *  xprintf --  Calls a function to dispose of output.
18509**
18510**           *  nprintf --  No output, but returns the number of characters
18511**                          that would have been output by printf.
18512**
18513**           *  A v- version (ex: vsnprintf) of every function is also
18514**              supplied.
18515**
18516**      +  A few extensions to the formatting notation are supported:
18517**
18518**           *  The "=" flag (similar to "-") causes the output to be
18519**              be centered in the appropriately sized field.
18520**
18521**           *  The %b field outputs an integer in binary notation.
18522**
18523**           *  The %c field now accepts a precision.  The character output
18524**              is repeated by the number of times the precision specifies.
18525**
18526**           *  The %' field works like %c, but takes as its character the
18527**              next character of the format string, instead of the next
18528**              argument.  For example,  printf("%.78'-")  prints 78 minus
18529**              signs, the same as  printf("%.78c",'-').
18530**
18531**      +  When compiled using GCC on a SPARC, this version of printf is
18532**         faster than the library printf for SUN OS 4.1.
18533**
18534**      +  All functions are fully reentrant.
18535**
18536*/
18537
18538/*
18539** Conversion types fall into various categories as defined by the
18540** following enumeration.
18541*/
18542#define etRADIX       1 /* Integer types.  %d, %x, %o, and so forth */
18543#define etFLOAT       2 /* Floating point.  %f */
18544#define etEXP         3 /* Exponentional notation. %e and %E */
18545#define etGENERIC     4 /* Floating or exponential, depending on exponent. %g */
18546#define etSIZE        5 /* Return number of characters processed so far. %n */
18547#define etSTRING      6 /* Strings. %s */
18548#define etDYNSTRING   7 /* Dynamically allocated strings. %z */
18549#define etPERCENT     8 /* Percent symbol. %% */
18550#define etCHARX       9 /* Characters. %c */
18551/* The rest are extensions, not normally found in printf() */
18552#define etSQLESCAPE  10 /* Strings with '\'' doubled.  %q */
18553#define etSQLESCAPE2 11 /* Strings with '\'' doubled and enclosed in '',
18554                          NULL pointers replaced by SQL NULL.  %Q */
18555#define etTOKEN      12 /* a pointer to a Token structure */
18556#define etSRCLIST    13 /* a pointer to a SrcList */
18557#define etPOINTER    14 /* The %p conversion */
18558#define etSQLESCAPE3 15 /* %w -> Strings with '\"' doubled */
18559#define etORDINAL    16 /* %r -> 1st, 2nd, 3rd, 4th, etc.  English only */
18560
18561#define etINVALID     0 /* Any unrecognized conversion type */
18562
18563
18564/*
18565** An "etByte" is an 8-bit unsigned value.
18566*/
18567typedef unsigned char etByte;
18568
18569/*
18570** Each builtin conversion character (ex: the 'd' in "%d") is described
18571** by an instance of the following structure
18572*/
18573typedef struct et_info {   /* Information about each format field */
18574  char fmttype;            /* The format field code letter */
18575  etByte base;             /* The base for radix conversion */
18576  etByte flags;            /* One or more of FLAG_ constants below */
18577  etByte type;             /* Conversion paradigm */
18578  etByte charset;          /* Offset into aDigits[] of the digits string */
18579  etByte prefix;           /* Offset into aPrefix[] of the prefix string */
18580} et_info;
18581
18582/*
18583** Allowed values for et_info.flags
18584*/
18585#define FLAG_SIGNED  1     /* True if the value to convert is signed */
18586#define FLAG_INTERN  2     /* True if for internal use only */
18587#define FLAG_STRING  4     /* Allow infinity precision */
18588
18589
18590/*
18591** The following table is searched linearly, so it is good to put the
18592** most frequently used conversion types first.
18593*/
18594static const char aDigits[] = "0123456789ABCDEF0123456789abcdef";
18595static const char aPrefix[] = "-x0\000X0";
18596static const et_info fmtinfo[] = {
18597  {  'd', 10, 1, etRADIX,      0,  0 },
18598  {  's',  0, 4, etSTRING,     0,  0 },
18599  {  'g',  0, 1, etGENERIC,    30, 0 },
18600  {  'z',  0, 4, etDYNSTRING,  0,  0 },
18601  {  'q',  0, 4, etSQLESCAPE,  0,  0 },
18602  {  'Q',  0, 4, etSQLESCAPE2, 0,  0 },
18603  {  'w',  0, 4, etSQLESCAPE3, 0,  0 },
18604  {  'c',  0, 0, etCHARX,      0,  0 },
18605  {  'o',  8, 0, etRADIX,      0,  2 },
18606  {  'u', 10, 0, etRADIX,      0,  0 },
18607  {  'x', 16, 0, etRADIX,      16, 1 },
18608  {  'X', 16, 0, etRADIX,      0,  4 },
18609#ifndef SQLITE_OMIT_FLOATING_POINT
18610  {  'f',  0, 1, etFLOAT,      0,  0 },
18611  {  'e',  0, 1, etEXP,        30, 0 },
18612  {  'E',  0, 1, etEXP,        14, 0 },
18613  {  'G',  0, 1, etGENERIC,    14, 0 },
18614#endif
18615  {  'i', 10, 1, etRADIX,      0,  0 },
18616  {  'n',  0, 0, etSIZE,       0,  0 },
18617  {  '%',  0, 0, etPERCENT,    0,  0 },
18618  {  'p', 16, 0, etPOINTER,    0,  1 },
18619
18620/* All the rest have the FLAG_INTERN bit set and are thus for internal
18621** use only */
18622  {  'T',  0, 2, etTOKEN,      0,  0 },
18623  {  'S',  0, 2, etSRCLIST,    0,  0 },
18624  {  'r', 10, 3, etORDINAL,    0,  0 },
18625};
18626
18627/*
18628** If SQLITE_OMIT_FLOATING_POINT is defined, then none of the floating point
18629** conversions will work.
18630*/
18631#ifndef SQLITE_OMIT_FLOATING_POINT
18632/*
18633** "*val" is a double such that 0.1 <= *val < 10.0
18634** Return the ascii code for the leading digit of *val, then
18635** multiply "*val" by 10.0 to renormalize.
18636**
18637** Example:
18638**     input:     *val = 3.14159
18639**     output:    *val = 1.4159    function return = '3'
18640**
18641** The counter *cnt is incremented each time.  After counter exceeds
18642** 16 (the number of significant digits in a 64-bit float) '0' is
18643** always returned.
18644*/
18645static char et_getdigit(LONGDOUBLE_TYPE *val, int *cnt){
18646  int digit;
18647  LONGDOUBLE_TYPE d;
18648  if( (*cnt)++ >= 16 ) return '0';
18649  digit = (int)*val;
18650  d = digit;
18651  digit += '0';
18652  *val = (*val - d)*10.0;
18653  return (char)digit;
18654}
18655#endif /* SQLITE_OMIT_FLOATING_POINT */
18656
18657/*
18658** Append N space characters to the given string buffer.
18659*/
18660static void appendSpace(StrAccum *pAccum, int N){
18661  static const char zSpaces[] = "                             ";
18662  while( N>=(int)sizeof(zSpaces)-1 ){
18663    sqlite3StrAccumAppend(pAccum, zSpaces, sizeof(zSpaces)-1);
18664    N -= sizeof(zSpaces)-1;
18665  }
18666  if( N>0 ){
18667    sqlite3StrAccumAppend(pAccum, zSpaces, N);
18668  }
18669}
18670
18671/*
18672** On machines with a small stack size, you can redefine the
18673** SQLITE_PRINT_BUF_SIZE to be less than 350.
18674*/
18675#ifndef SQLITE_PRINT_BUF_SIZE
18676# if defined(SQLITE_SMALL_STACK)
18677#   define SQLITE_PRINT_BUF_SIZE 50
18678# else
18679#   define SQLITE_PRINT_BUF_SIZE 350
18680# endif
18681#endif
18682#define etBUFSIZE SQLITE_PRINT_BUF_SIZE  /* Size of the output buffer */
18683
18684/*
18685** The root program.  All variations call this core.
18686**
18687** INPUTS:
18688**   func   This is a pointer to a function taking three arguments
18689**            1. A pointer to anything.  Same as the "arg" parameter.
18690**            2. A pointer to the list of characters to be output
18691**               (Note, this list is NOT null terminated.)
18692**            3. An integer number of characters to be output.
18693**               (Note: This number might be zero.)
18694**
18695**   arg    This is the pointer to anything which will be passed as the
18696**          first argument to "func".  Use it for whatever you like.
18697**
18698**   fmt    This is the format string, as in the usual print.
18699**
18700**   ap     This is a pointer to a list of arguments.  Same as in
18701**          vfprint.
18702**
18703** OUTPUTS:
18704**          The return value is the total number of characters sent to
18705**          the function "func".  Returns -1 on a error.
18706**
18707** Note that the order in which automatic variables are declared below
18708** seems to make a big difference in determining how fast this beast
18709** will run.
18710*/
18711SQLITE_PRIVATE void sqlite3VXPrintf(
18712  StrAccum *pAccum,                  /* Accumulate results here */
18713  int useExtended,                   /* Allow extended %-conversions */
18714  const char *fmt,                   /* Format string */
18715  va_list ap                         /* arguments */
18716){
18717  int c;                     /* Next character in the format string */
18718  char *bufpt;               /* Pointer to the conversion buffer */
18719  int precision;             /* Precision of the current field */
18720  int length;                /* Length of the field */
18721  int idx;                   /* A general purpose loop counter */
18722  int width;                 /* Width of the current field */
18723  etByte flag_leftjustify;   /* True if "-" flag is present */
18724  etByte flag_plussign;      /* True if "+" flag is present */
18725  etByte flag_blanksign;     /* True if " " flag is present */
18726  etByte flag_alternateform; /* True if "#" flag is present */
18727  etByte flag_altform2;      /* True if "!" flag is present */
18728  etByte flag_zeropad;       /* True if field width constant starts with zero */
18729  etByte flag_long;          /* True if "l" flag is present */
18730  etByte flag_longlong;      /* True if the "ll" flag is present */
18731  etByte done;               /* Loop termination flag */
18732  sqlite_uint64 longvalue;   /* Value for integer types */
18733  LONGDOUBLE_TYPE realvalue; /* Value for real types */
18734  const et_info *infop;      /* Pointer to the appropriate info structure */
18735  char buf[etBUFSIZE];       /* Conversion buffer */
18736  char prefix;               /* Prefix character.  "+" or "-" or " " or '\0'. */
18737  etByte xtype = 0;          /* Conversion paradigm */
18738  char *zExtra;              /* Extra memory used for etTCLESCAPE conversions */
18739#ifndef SQLITE_OMIT_FLOATING_POINT
18740  int  exp, e2;              /* exponent of real numbers */
18741  double rounder;            /* Used for rounding floating point values */
18742  etByte flag_dp;            /* True if decimal point should be shown */
18743  etByte flag_rtz;           /* True if trailing zeros should be removed */
18744  etByte flag_exp;           /* True to force display of the exponent */
18745  int nsd;                   /* Number of significant digits returned */
18746#endif
18747
18748  length = 0;
18749  bufpt = 0;
18750  for(; (c=(*fmt))!=0; ++fmt){
18751    if( c!='%' ){
18752      int amt;
18753      bufpt = (char *)fmt;
18754      amt = 1;
18755      while( (c=(*++fmt))!='%' && c!=0 ) amt++;
18756      sqlite3StrAccumAppend(pAccum, bufpt, amt);
18757      if( c==0 ) break;
18758    }
18759    if( (c=(*++fmt))==0 ){
18760      sqlite3StrAccumAppend(pAccum, "%", 1);
18761      break;
18762    }
18763    /* Find out what flags are present */
18764    flag_leftjustify = flag_plussign = flag_blanksign =
18765     flag_alternateform = flag_altform2 = flag_zeropad = 0;
18766    done = 0;
18767    do{
18768      switch( c ){
18769        case '-':   flag_leftjustify = 1;     break;
18770        case '+':   flag_plussign = 1;        break;
18771        case ' ':   flag_blanksign = 1;       break;
18772        case '#':   flag_alternateform = 1;   break;
18773        case '!':   flag_altform2 = 1;        break;
18774        case '0':   flag_zeropad = 1;         break;
18775        default:    done = 1;                 break;
18776      }
18777    }while( !done && (c=(*++fmt))!=0 );
18778    /* Get the field width */
18779    width = 0;
18780    if( c=='*' ){
18781      width = va_arg(ap,int);
18782      if( width<0 ){
18783        flag_leftjustify = 1;
18784        width = -width;
18785      }
18786      c = *++fmt;
18787    }else{
18788      while( c>='0' && c<='9' ){
18789        width = width*10 + c - '0';
18790        c = *++fmt;
18791      }
18792    }
18793    if( width > etBUFSIZE-10 ){
18794      width = etBUFSIZE-10;
18795    }
18796    /* Get the precision */
18797    if( c=='.' ){
18798      precision = 0;
18799      c = *++fmt;
18800      if( c=='*' ){
18801        precision = va_arg(ap,int);
18802        if( precision<0 ) precision = -precision;
18803        c = *++fmt;
18804      }else{
18805        while( c>='0' && c<='9' ){
18806          precision = precision*10 + c - '0';
18807          c = *++fmt;
18808        }
18809      }
18810    }else{
18811      precision = -1;
18812    }
18813    /* Get the conversion type modifier */
18814    if( c=='l' ){
18815      flag_long = 1;
18816      c = *++fmt;
18817      if( c=='l' ){
18818        flag_longlong = 1;
18819        c = *++fmt;
18820      }else{
18821        flag_longlong = 0;
18822      }
18823    }else{
18824      flag_long = flag_longlong = 0;
18825    }
18826    /* Fetch the info entry for the field */
18827    infop = &fmtinfo[0];
18828    xtype = etINVALID;
18829    for(idx=0; idx<ArraySize(fmtinfo); idx++){
18830      if( c==fmtinfo[idx].fmttype ){
18831        infop = &fmtinfo[idx];
18832        if( useExtended || (infop->flags & FLAG_INTERN)==0 ){
18833          xtype = infop->type;
18834        }else{
18835          return;
18836        }
18837        break;
18838      }
18839    }
18840    zExtra = 0;
18841
18842
18843    /* Limit the precision to prevent overflowing buf[] during conversion */
18844    if( precision>etBUFSIZE-40 && (infop->flags & FLAG_STRING)==0 ){
18845      precision = etBUFSIZE-40;
18846    }
18847
18848    /*
18849    ** At this point, variables are initialized as follows:
18850    **
18851    **   flag_alternateform          TRUE if a '#' is present.
18852    **   flag_altform2               TRUE if a '!' is present.
18853    **   flag_plussign               TRUE if a '+' is present.
18854    **   flag_leftjustify            TRUE if a '-' is present or if the
18855    **                               field width was negative.
18856    **   flag_zeropad                TRUE if the width began with 0.
18857    **   flag_long                   TRUE if the letter 'l' (ell) prefixed
18858    **                               the conversion character.
18859    **   flag_longlong               TRUE if the letter 'll' (ell ell) prefixed
18860    **                               the conversion character.
18861    **   flag_blanksign              TRUE if a ' ' is present.
18862    **   width                       The specified field width.  This is
18863    **                               always non-negative.  Zero is the default.
18864    **   precision                   The specified precision.  The default
18865    **                               is -1.
18866    **   xtype                       The class of the conversion.
18867    **   infop                       Pointer to the appropriate info struct.
18868    */
18869    switch( xtype ){
18870      case etPOINTER:
18871        flag_longlong = sizeof(char*)==sizeof(i64);
18872        flag_long = sizeof(char*)==sizeof(long int);
18873        /* Fall through into the next case */
18874      case etORDINAL:
18875      case etRADIX:
18876        if( infop->flags & FLAG_SIGNED ){
18877          i64 v;
18878          if( flag_longlong ){
18879            v = va_arg(ap,i64);
18880          }else if( flag_long ){
18881            v = va_arg(ap,long int);
18882          }else{
18883            v = va_arg(ap,int);
18884          }
18885          if( v<0 ){
18886            if( v==SMALLEST_INT64 ){
18887              longvalue = ((u64)1)<<63;
18888            }else{
18889              longvalue = -v;
18890            }
18891            prefix = '-';
18892          }else{
18893            longvalue = v;
18894            if( flag_plussign )        prefix = '+';
18895            else if( flag_blanksign )  prefix = ' ';
18896            else                       prefix = 0;
18897          }
18898        }else{
18899          if( flag_longlong ){
18900            longvalue = va_arg(ap,u64);
18901          }else if( flag_long ){
18902            longvalue = va_arg(ap,unsigned long int);
18903          }else{
18904            longvalue = va_arg(ap,unsigned int);
18905          }
18906          prefix = 0;
18907        }
18908        if( longvalue==0 ) flag_alternateform = 0;
18909        if( flag_zeropad && precision<width-(prefix!=0) ){
18910          precision = width-(prefix!=0);
18911        }
18912        bufpt = &buf[etBUFSIZE-1];
18913        if( xtype==etORDINAL ){
18914          static const char zOrd[] = "thstndrd";
18915          int x = (int)(longvalue % 10);
18916          if( x>=4 || (longvalue/10)%10==1 ){
18917            x = 0;
18918          }
18919          buf[etBUFSIZE-3] = zOrd[x*2];
18920          buf[etBUFSIZE-2] = zOrd[x*2+1];
18921          bufpt -= 2;
18922        }
18923        {
18924          register const char *cset;      /* Use registers for speed */
18925          register int base;
18926          cset = &aDigits[infop->charset];
18927          base = infop->base;
18928          do{                                           /* Convert to ascii */
18929            *(--bufpt) = cset[longvalue%base];
18930            longvalue = longvalue/base;
18931          }while( longvalue>0 );
18932        }
18933        length = (int)(&buf[etBUFSIZE-1]-bufpt);
18934        for(idx=precision-length; idx>0; idx--){
18935          *(--bufpt) = '0';                             /* Zero pad */
18936        }
18937        if( prefix ) *(--bufpt) = prefix;               /* Add sign */
18938        if( flag_alternateform && infop->prefix ){      /* Add "0" or "0x" */
18939          const char *pre;
18940          char x;
18941          pre = &aPrefix[infop->prefix];
18942          for(; (x=(*pre))!=0; pre++) *(--bufpt) = x;
18943        }
18944        length = (int)(&buf[etBUFSIZE-1]-bufpt);
18945        break;
18946      case etFLOAT:
18947      case etEXP:
18948      case etGENERIC:
18949        realvalue = va_arg(ap,double);
18950#ifdef SQLITE_OMIT_FLOATING_POINT
18951        length = 0;
18952#else
18953        if( precision<0 ) precision = 6;         /* Set default precision */
18954        if( precision>etBUFSIZE/2-10 ) precision = etBUFSIZE/2-10;
18955        if( realvalue<0.0 ){
18956          realvalue = -realvalue;
18957          prefix = '-';
18958        }else{
18959          if( flag_plussign )          prefix = '+';
18960          else if( flag_blanksign )    prefix = ' ';
18961          else                         prefix = 0;
18962        }
18963        if( xtype==etGENERIC && precision>0 ) precision--;
18964#if 0
18965        /* Rounding works like BSD when the constant 0.4999 is used.  Wierd! */
18966        for(idx=precision, rounder=0.4999; idx>0; idx--, rounder*=0.1);
18967#else
18968        /* It makes more sense to use 0.5 */
18969        for(idx=precision, rounder=0.5; idx>0; idx--, rounder*=0.1){}
18970#endif
18971        if( xtype==etFLOAT ) realvalue += rounder;
18972        /* Normalize realvalue to within 10.0 > realvalue >= 1.0 */
18973        exp = 0;
18974        if( sqlite3IsNaN((double)realvalue) ){
18975          bufpt = "NaN";
18976          length = 3;
18977          break;
18978        }
18979        if( realvalue>0.0 ){
18980          while( realvalue>=1e32 && exp<=350 ){ realvalue *= 1e-32; exp+=32; }
18981          while( realvalue>=1e8 && exp<=350 ){ realvalue *= 1e-8; exp+=8; }
18982          while( realvalue>=10.0 && exp<=350 ){ realvalue *= 0.1; exp++; }
18983          while( realvalue<1e-8 ){ realvalue *= 1e8; exp-=8; }
18984          while( realvalue<1.0 ){ realvalue *= 10.0; exp--; }
18985          if( exp>350 ){
18986            if( prefix=='-' ){
18987              bufpt = "-Inf";
18988            }else if( prefix=='+' ){
18989              bufpt = "+Inf";
18990            }else{
18991              bufpt = "Inf";
18992            }
18993            length = sqlite3Strlen30(bufpt);
18994            break;
18995          }
18996        }
18997        bufpt = buf;
18998        /*
18999        ** If the field type is etGENERIC, then convert to either etEXP
19000        ** or etFLOAT, as appropriate.
19001        */
19002        flag_exp = xtype==etEXP;
19003        if( xtype!=etFLOAT ){
19004          realvalue += rounder;
19005          if( realvalue>=10.0 ){ realvalue *= 0.1; exp++; }
19006        }
19007        if( xtype==etGENERIC ){
19008          flag_rtz = !flag_alternateform;
19009          if( exp<-4 || exp>precision ){
19010            xtype = etEXP;
19011          }else{
19012            precision = precision - exp;
19013            xtype = etFLOAT;
19014          }
19015        }else{
19016          flag_rtz = 0;
19017        }
19018        if( xtype==etEXP ){
19019          e2 = 0;
19020        }else{
19021          e2 = exp;
19022        }
19023        nsd = 0;
19024        flag_dp = (precision>0 ?1:0) | flag_alternateform | flag_altform2;
19025        /* The sign in front of the number */
19026        if( prefix ){
19027          *(bufpt++) = prefix;
19028        }
19029        /* Digits prior to the decimal point */
19030        if( e2<0 ){
19031          *(bufpt++) = '0';
19032        }else{
19033          for(; e2>=0; e2--){
19034            *(bufpt++) = et_getdigit(&realvalue,&nsd);
19035          }
19036        }
19037        /* The decimal point */
19038        if( flag_dp ){
19039          *(bufpt++) = '.';
19040        }
19041        /* "0" digits after the decimal point but before the first
19042        ** significant digit of the number */
19043        for(e2++; e2<0; precision--, e2++){
19044          assert( precision>0 );
19045          *(bufpt++) = '0';
19046        }
19047        /* Significant digits after the decimal point */
19048        while( (precision--)>0 ){
19049          *(bufpt++) = et_getdigit(&realvalue,&nsd);
19050        }
19051        /* Remove trailing zeros and the "." if no digits follow the "." */
19052        if( flag_rtz && flag_dp ){
19053          while( bufpt[-1]=='0' ) *(--bufpt) = 0;
19054          assert( bufpt>buf );
19055          if( bufpt[-1]=='.' ){
19056            if( flag_altform2 ){
19057              *(bufpt++) = '0';
19058            }else{
19059              *(--bufpt) = 0;
19060            }
19061          }
19062        }
19063        /* Add the "eNNN" suffix */
19064        if( flag_exp || xtype==etEXP ){
19065          *(bufpt++) = aDigits[infop->charset];
19066          if( exp<0 ){
19067            *(bufpt++) = '-'; exp = -exp;
19068          }else{
19069            *(bufpt++) = '+';
19070          }
19071          if( exp>=100 ){
19072            *(bufpt++) = (char)((exp/100)+'0');        /* 100's digit */
19073            exp %= 100;
19074          }
19075          *(bufpt++) = (char)(exp/10+'0');             /* 10's digit */
19076          *(bufpt++) = (char)(exp%10+'0');             /* 1's digit */
19077        }
19078        *bufpt = 0;
19079
19080        /* The converted number is in buf[] and zero terminated. Output it.
19081        ** Note that the number is in the usual order, not reversed as with
19082        ** integer conversions. */
19083        length = (int)(bufpt-buf);
19084        bufpt = buf;
19085
19086        /* Special case:  Add leading zeros if the flag_zeropad flag is
19087        ** set and we are not left justified */
19088        if( flag_zeropad && !flag_leftjustify && length < width){
19089          int i;
19090          int nPad = width - length;
19091          for(i=width; i>=nPad; i--){
19092            bufpt[i] = bufpt[i-nPad];
19093          }
19094          i = prefix!=0;
19095          while( nPad-- ) bufpt[i++] = '0';
19096          length = width;
19097        }
19098#endif /* !defined(SQLITE_OMIT_FLOATING_POINT) */
19099        break;
19100      case etSIZE:
19101        *(va_arg(ap,int*)) = pAccum->nChar;
19102        length = width = 0;
19103        break;
19104      case etPERCENT:
19105        buf[0] = '%';
19106        bufpt = buf;
19107        length = 1;
19108        break;
19109      case etCHARX:
19110        c = va_arg(ap,int);
19111        buf[0] = (char)c;
19112        if( precision>=0 ){
19113          for(idx=1; idx<precision; idx++) buf[idx] = (char)c;
19114          length = precision;
19115        }else{
19116          length =1;
19117        }
19118        bufpt = buf;
19119        break;
19120      case etSTRING:
19121      case etDYNSTRING:
19122        bufpt = va_arg(ap,char*);
19123        if( bufpt==0 ){
19124          bufpt = "";
19125        }else if( xtype==etDYNSTRING ){
19126          zExtra = bufpt;
19127        }
19128        if( precision>=0 ){
19129          for(length=0; length<precision && bufpt[length]; length++){}
19130        }else{
19131          length = sqlite3Strlen30(bufpt);
19132        }
19133        break;
19134      case etSQLESCAPE:
19135      case etSQLESCAPE2:
19136      case etSQLESCAPE3: {
19137        int i, j, k, n, isnull;
19138        int needQuote;
19139        char ch;
19140        char q = ((xtype==etSQLESCAPE3)?'"':'\'');   /* Quote character */
19141        char *escarg = va_arg(ap,char*);
19142        isnull = escarg==0;
19143        if( isnull ) escarg = (xtype==etSQLESCAPE2 ? "NULL" : "(NULL)");
19144        k = precision;
19145        for(i=n=0; k!=0 && (ch=escarg[i])!=0; i++, k--){
19146          if( ch==q )  n++;
19147        }
19148        needQuote = !isnull && xtype==etSQLESCAPE2;
19149        n += i + 1 + needQuote*2;
19150        if( n>etBUFSIZE ){
19151          bufpt = zExtra = sqlite3Malloc( n );
19152          if( bufpt==0 ){
19153            pAccum->mallocFailed = 1;
19154            return;
19155          }
19156        }else{
19157          bufpt = buf;
19158        }
19159        j = 0;
19160        if( needQuote ) bufpt[j++] = q;
19161        k = i;
19162        for(i=0; i<k; i++){
19163          bufpt[j++] = ch = escarg[i];
19164          if( ch==q ) bufpt[j++] = ch;
19165        }
19166        if( needQuote ) bufpt[j++] = q;
19167        bufpt[j] = 0;
19168        length = j;
19169        /* The precision in %q and %Q means how many input characters to
19170        ** consume, not the length of the output...
19171        ** if( precision>=0 && precision<length ) length = precision; */
19172        break;
19173      }
19174      case etTOKEN: {
19175        Token *pToken = va_arg(ap, Token*);
19176        if( pToken ){
19177          sqlite3StrAccumAppend(pAccum, (const char*)pToken->z, pToken->n);
19178        }
19179        length = width = 0;
19180        break;
19181      }
19182      case etSRCLIST: {
19183        SrcList *pSrc = va_arg(ap, SrcList*);
19184        int k = va_arg(ap, int);
19185        struct SrcList_item *pItem = &pSrc->a[k];
19186        assert( k>=0 && k<pSrc->nSrc );
19187        if( pItem->zDatabase ){
19188          sqlite3StrAccumAppend(pAccum, pItem->zDatabase, -1);
19189          sqlite3StrAccumAppend(pAccum, ".", 1);
19190        }
19191        sqlite3StrAccumAppend(pAccum, pItem->zName, -1);
19192        length = width = 0;
19193        break;
19194      }
19195      default: {
19196        assert( xtype==etINVALID );
19197        return;
19198      }
19199    }/* End switch over the format type */
19200    /*
19201    ** The text of the conversion is pointed to by "bufpt" and is
19202    ** "length" characters long.  The field width is "width".  Do
19203    ** the output.
19204    */
19205    if( !flag_leftjustify ){
19206      register int nspace;
19207      nspace = width-length;
19208      if( nspace>0 ){
19209        appendSpace(pAccum, nspace);
19210      }
19211    }
19212    if( length>0 ){
19213      sqlite3StrAccumAppend(pAccum, bufpt, length);
19214    }
19215    if( flag_leftjustify ){
19216      register int nspace;
19217      nspace = width-length;
19218      if( nspace>0 ){
19219        appendSpace(pAccum, nspace);
19220      }
19221    }
19222    if( zExtra ){
19223      sqlite3_free(zExtra);
19224    }
19225  }/* End for loop over the format string */
19226} /* End of function */
19227
19228/*
19229** Append N bytes of text from z to the StrAccum object.
19230*/
19231SQLITE_PRIVATE void sqlite3StrAccumAppend(StrAccum *p, const char *z, int N){
19232  assert( z!=0 || N==0 );
19233  if( p->tooBig | p->mallocFailed ){
19234    testcase(p->tooBig);
19235    testcase(p->mallocFailed);
19236    return;
19237  }
19238  if( N<0 ){
19239    N = sqlite3Strlen30(z);
19240  }
19241  if( N==0 || NEVER(z==0) ){
19242    return;
19243  }
19244  if( p->nChar+N >= p->nAlloc ){
19245    char *zNew;
19246    if( !p->useMalloc ){
19247      p->tooBig = 1;
19248      N = p->nAlloc - p->nChar - 1;
19249      if( N<=0 ){
19250        return;
19251      }
19252    }else{
19253      char *zOld = (p->zText==p->zBase ? 0 : p->zText);
19254      i64 szNew = p->nChar;
19255      szNew += N + 1;
19256      if( szNew > p->mxAlloc ){
19257        sqlite3StrAccumReset(p);
19258        p->tooBig = 1;
19259        return;
19260      }else{
19261        p->nAlloc = (int)szNew;
19262      }
19263      if( p->useMalloc==1 ){
19264        zNew = sqlite3DbRealloc(p->db, zOld, p->nAlloc);
19265      }else{
19266        zNew = sqlite3_realloc(zOld, p->nAlloc);
19267      }
19268      if( zNew ){
19269        if( zOld==0 ) memcpy(zNew, p->zText, p->nChar);
19270        p->zText = zNew;
19271      }else{
19272        p->mallocFailed = 1;
19273        sqlite3StrAccumReset(p);
19274        return;
19275      }
19276    }
19277  }
19278  memcpy(&p->zText[p->nChar], z, N);
19279  p->nChar += N;
19280}
19281
19282/*
19283** Finish off a string by making sure it is zero-terminated.
19284** Return a pointer to the resulting string.  Return a NULL
19285** pointer if any kind of error was encountered.
19286*/
19287SQLITE_PRIVATE char *sqlite3StrAccumFinish(StrAccum *p){
19288  if( p->zText ){
19289    p->zText[p->nChar] = 0;
19290    if( p->useMalloc && p->zText==p->zBase ){
19291      if( p->useMalloc==1 ){
19292        p->zText = sqlite3DbMallocRaw(p->db, p->nChar+1 );
19293      }else{
19294        p->zText = sqlite3_malloc(p->nChar+1);
19295      }
19296      if( p->zText ){
19297        memcpy(p->zText, p->zBase, p->nChar+1);
19298      }else{
19299        p->mallocFailed = 1;
19300      }
19301    }
19302  }
19303  return p->zText;
19304}
19305
19306/*
19307** Reset an StrAccum string.  Reclaim all malloced memory.
19308*/
19309SQLITE_PRIVATE void sqlite3StrAccumReset(StrAccum *p){
19310  if( p->zText!=p->zBase ){
19311    if( p->useMalloc==1 ){
19312      sqlite3DbFree(p->db, p->zText);
19313    }else{
19314      sqlite3_free(p->zText);
19315    }
19316  }
19317  p->zText = 0;
19318}
19319
19320/*
19321** Initialize a string accumulator
19322*/
19323SQLITE_PRIVATE void sqlite3StrAccumInit(StrAccum *p, char *zBase, int n, int mx){
19324  p->zText = p->zBase = zBase;
19325  p->db = 0;
19326  p->nChar = 0;
19327  p->nAlloc = n;
19328  p->mxAlloc = mx;
19329  p->useMalloc = 1;
19330  p->tooBig = 0;
19331  p->mallocFailed = 0;
19332}
19333
19334/*
19335** Print into memory obtained from sqliteMalloc().  Use the internal
19336** %-conversion extensions.
19337*/
19338SQLITE_PRIVATE char *sqlite3VMPrintf(sqlite3 *db, const char *zFormat, va_list ap){
19339  char *z;
19340  char zBase[SQLITE_PRINT_BUF_SIZE];
19341  StrAccum acc;
19342  assert( db!=0 );
19343  sqlite3StrAccumInit(&acc, zBase, sizeof(zBase),
19344                      db->aLimit[SQLITE_LIMIT_LENGTH]);
19345  acc.db = db;
19346  sqlite3VXPrintf(&acc, 1, zFormat, ap);
19347  z = sqlite3StrAccumFinish(&acc);
19348  if( acc.mallocFailed ){
19349    db->mallocFailed = 1;
19350  }
19351  return z;
19352}
19353
19354/*
19355** Print into memory obtained from sqliteMalloc().  Use the internal
19356** %-conversion extensions.
19357*/
19358SQLITE_PRIVATE char *sqlite3MPrintf(sqlite3 *db, const char *zFormat, ...){
19359  va_list ap;
19360  char *z;
19361  va_start(ap, zFormat);
19362  z = sqlite3VMPrintf(db, zFormat, ap);
19363  va_end(ap);
19364  return z;
19365}
19366
19367/*
19368** Like sqlite3MPrintf(), but call sqlite3DbFree() on zStr after formatting
19369** the string and before returnning.  This routine is intended to be used
19370** to modify an existing string.  For example:
19371**
19372**       x = sqlite3MPrintf(db, x, "prefix %s suffix", x);
19373**
19374*/
19375SQLITE_PRIVATE char *sqlite3MAppendf(sqlite3 *db, char *zStr, const char *zFormat, ...){
19376  va_list ap;
19377  char *z;
19378  va_start(ap, zFormat);
19379  z = sqlite3VMPrintf(db, zFormat, ap);
19380  va_end(ap);
19381  sqlite3DbFree(db, zStr);
19382  return z;
19383}
19384
19385/*
19386** Print into memory obtained from sqlite3_malloc().  Omit the internal
19387** %-conversion extensions.
19388*/
19389SQLITE_API char *sqlite3_vmprintf(const char *zFormat, va_list ap){
19390  char *z;
19391  char zBase[SQLITE_PRINT_BUF_SIZE];
19392  StrAccum acc;
19393#ifndef SQLITE_OMIT_AUTOINIT
19394  if( sqlite3_initialize() ) return 0;
19395#endif
19396  sqlite3StrAccumInit(&acc, zBase, sizeof(zBase), SQLITE_MAX_LENGTH);
19397  acc.useMalloc = 2;
19398  sqlite3VXPrintf(&acc, 0, zFormat, ap);
19399  z = sqlite3StrAccumFinish(&acc);
19400  return z;
19401}
19402
19403/*
19404** Print into memory obtained from sqlite3_malloc()().  Omit the internal
19405** %-conversion extensions.
19406*/
19407SQLITE_API char *sqlite3_mprintf(const char *zFormat, ...){
19408  va_list ap;
19409  char *z;
19410#ifndef SQLITE_OMIT_AUTOINIT
19411  if( sqlite3_initialize() ) return 0;
19412#endif
19413  va_start(ap, zFormat);
19414  z = sqlite3_vmprintf(zFormat, ap);
19415  va_end(ap);
19416  return z;
19417}
19418
19419/*
19420** sqlite3_snprintf() works like snprintf() except that it ignores the
19421** current locale settings.  This is important for SQLite because we
19422** are not able to use a "," as the decimal point in place of "." as
19423** specified by some locales.
19424**
19425** Oops:  The first two arguments of sqlite3_snprintf() are backwards
19426** from the snprintf() standard.  Unfortunately, it is too late to change
19427** this without breaking compatibility, so we just have to live with the
19428** mistake.
19429**
19430** sqlite3_vsnprintf() is the varargs version.
19431*/
19432SQLITE_API char *sqlite3_vsnprintf(int n, char *zBuf, const char *zFormat, va_list ap){
19433  StrAccum acc;
19434  if( n<=0 ) return zBuf;
19435  sqlite3StrAccumInit(&acc, zBuf, n, 0);
19436  acc.useMalloc = 0;
19437  sqlite3VXPrintf(&acc, 0, zFormat, ap);
19438  return sqlite3StrAccumFinish(&acc);
19439}
19440SQLITE_API char *sqlite3_snprintf(int n, char *zBuf, const char *zFormat, ...){
19441  char *z;
19442  va_list ap;
19443  va_start(ap,zFormat);
19444  z = sqlite3_vsnprintf(n, zBuf, zFormat, ap);
19445  va_end(ap);
19446  return z;
19447}
19448
19449/*
19450** This is the routine that actually formats the sqlite3_log() message.
19451** We house it in a separate routine from sqlite3_log() to avoid using
19452** stack space on small-stack systems when logging is disabled.
19453**
19454** sqlite3_log() must render into a static buffer.  It cannot dynamically
19455** allocate memory because it might be called while the memory allocator
19456** mutex is held.
19457*/
19458static void renderLogMsg(int iErrCode, const char *zFormat, va_list ap){
19459  StrAccum acc;                          /* String accumulator */
19460  char zMsg[SQLITE_PRINT_BUF_SIZE*3];    /* Complete log message */
19461
19462  sqlite3StrAccumInit(&acc, zMsg, sizeof(zMsg), 0);
19463  acc.useMalloc = 0;
19464  sqlite3VXPrintf(&acc, 0, zFormat, ap);
19465  sqlite3GlobalConfig.xLog(sqlite3GlobalConfig.pLogArg, iErrCode,
19466                           sqlite3StrAccumFinish(&acc));
19467}
19468
19469/*
19470** Format and write a message to the log if logging is enabled.
19471*/
19472SQLITE_API void sqlite3_log(int iErrCode, const char *zFormat, ...){
19473  va_list ap;                             /* Vararg list */
19474  if( sqlite3GlobalConfig.xLog ){
19475    va_start(ap, zFormat);
19476    renderLogMsg(iErrCode, zFormat, ap);
19477    va_end(ap);
19478  }
19479}
19480
19481#if defined(SQLITE_DEBUG)
19482/*
19483** A version of printf() that understands %lld.  Used for debugging.
19484** The printf() built into some versions of windows does not understand %lld
19485** and segfaults if you give it a long long int.
19486*/
19487SQLITE_PRIVATE void sqlite3DebugPrintf(const char *zFormat, ...){
19488  va_list ap;
19489  StrAccum acc;
19490  char zBuf[500];
19491  sqlite3StrAccumInit(&acc, zBuf, sizeof(zBuf), 0);
19492  acc.useMalloc = 0;
19493  va_start(ap,zFormat);
19494  sqlite3VXPrintf(&acc, 0, zFormat, ap);
19495  va_end(ap);
19496  sqlite3StrAccumFinish(&acc);
19497  fprintf(stdout,"%s", zBuf);
19498  fflush(stdout);
19499}
19500#endif
19501
19502#ifndef SQLITE_OMIT_TRACE
19503/*
19504** variable-argument wrapper around sqlite3VXPrintf().
19505*/
19506SQLITE_PRIVATE void sqlite3XPrintf(StrAccum *p, const char *zFormat, ...){
19507  va_list ap;
19508  va_start(ap,zFormat);
19509  sqlite3VXPrintf(p, 1, zFormat, ap);
19510  va_end(ap);
19511}
19512#endif
19513
19514/************** End of printf.c **********************************************/
19515/************** Begin file random.c ******************************************/
19516/*
19517** 2001 September 15
19518**
19519** The author disclaims copyright to this source code.  In place of
19520** a legal notice, here is a blessing:
19521**
19522**    May you do good and not evil.
19523**    May you find forgiveness for yourself and forgive others.
19524**    May you share freely, never taking more than you give.
19525**
19526*************************************************************************
19527** This file contains code to implement a pseudo-random number
19528** generator (PRNG) for SQLite.
19529**
19530** Random numbers are used by some of the database backends in order
19531** to generate random integer keys for tables or random filenames.
19532*/
19533
19534
19535/* All threads share a single random number generator.
19536** This structure is the current state of the generator.
19537*/
19538static SQLITE_WSD struct sqlite3PrngType {
19539  unsigned char isInit;          /* True if initialized */
19540  unsigned char i, j;            /* State variables */
19541  unsigned char s[256];          /* State variables */
19542} sqlite3Prng;
19543
19544/*
19545** Get a single 8-bit random value from the RC4 PRNG.  The Mutex
19546** must be held while executing this routine.
19547**
19548** Why not just use a library random generator like lrand48() for this?
19549** Because the OP_NewRowid opcode in the VDBE depends on having a very
19550** good source of random numbers.  The lrand48() library function may
19551** well be good enough.  But maybe not.  Or maybe lrand48() has some
19552** subtle problems on some systems that could cause problems.  It is hard
19553** to know.  To minimize the risk of problems due to bad lrand48()
19554** implementations, SQLite uses this random number generator based
19555** on RC4, which we know works very well.
19556**
19557** (Later):  Actually, OP_NewRowid does not depend on a good source of
19558** randomness any more.  But we will leave this code in all the same.
19559*/
19560static u8 randomByte(void){
19561  unsigned char t;
19562
19563
19564  /* The "wsdPrng" macro will resolve to the pseudo-random number generator
19565  ** state vector.  If writable static data is unsupported on the target,
19566  ** we have to locate the state vector at run-time.  In the more common
19567  ** case where writable static data is supported, wsdPrng can refer directly
19568  ** to the "sqlite3Prng" state vector declared above.
19569  */
19570#ifdef SQLITE_OMIT_WSD
19571  struct sqlite3PrngType *p = &GLOBAL(struct sqlite3PrngType, sqlite3Prng);
19572# define wsdPrng p[0]
19573#else
19574# define wsdPrng sqlite3Prng
19575#endif
19576
19577
19578  /* Initialize the state of the random number generator once,
19579  ** the first time this routine is called.  The seed value does
19580  ** not need to contain a lot of randomness since we are not
19581  ** trying to do secure encryption or anything like that...
19582  **
19583  ** Nothing in this file or anywhere else in SQLite does any kind of
19584  ** encryption.  The RC4 algorithm is being used as a PRNG (pseudo-random
19585  ** number generator) not as an encryption device.
19586  */
19587  if( !wsdPrng.isInit ){
19588    int i;
19589    char k[256];
19590    wsdPrng.j = 0;
19591    wsdPrng.i = 0;
19592    sqlite3OsRandomness(sqlite3_vfs_find(0), 256, k);
19593    for(i=0; i<256; i++){
19594      wsdPrng.s[i] = (u8)i;
19595    }
19596    for(i=0; i<256; i++){
19597      wsdPrng.j += wsdPrng.s[i] + k[i];
19598      t = wsdPrng.s[wsdPrng.j];
19599      wsdPrng.s[wsdPrng.j] = wsdPrng.s[i];
19600      wsdPrng.s[i] = t;
19601    }
19602    wsdPrng.isInit = 1;
19603  }
19604
19605  /* Generate and return single random byte
19606  */
19607  wsdPrng.i++;
19608  t = wsdPrng.s[wsdPrng.i];
19609  wsdPrng.j += t;
19610  wsdPrng.s[wsdPrng.i] = wsdPrng.s[wsdPrng.j];
19611  wsdPrng.s[wsdPrng.j] = t;
19612  t += wsdPrng.s[wsdPrng.i];
19613  return wsdPrng.s[t];
19614}
19615
19616/*
19617** Return N random bytes.
19618*/
19619SQLITE_API void sqlite3_randomness(int N, void *pBuf){
19620  unsigned char *zBuf = pBuf;
19621#if SQLITE_THREADSAFE
19622  sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_PRNG);
19623#endif
19624  sqlite3_mutex_enter(mutex);
19625  while( N-- ){
19626    *(zBuf++) = randomByte();
19627  }
19628  sqlite3_mutex_leave(mutex);
19629}
19630
19631#ifndef SQLITE_OMIT_BUILTIN_TEST
19632/*
19633** For testing purposes, we sometimes want to preserve the state of
19634** PRNG and restore the PRNG to its saved state at a later time, or
19635** to reset the PRNG to its initial state.  These routines accomplish
19636** those tasks.
19637**
19638** The sqlite3_test_control() interface calls these routines to
19639** control the PRNG.
19640*/
19641static SQLITE_WSD struct sqlite3PrngType sqlite3SavedPrng;
19642SQLITE_PRIVATE void sqlite3PrngSaveState(void){
19643  memcpy(
19644    &GLOBAL(struct sqlite3PrngType, sqlite3SavedPrng),
19645    &GLOBAL(struct sqlite3PrngType, sqlite3Prng),
19646    sizeof(sqlite3Prng)
19647  );
19648}
19649SQLITE_PRIVATE void sqlite3PrngRestoreState(void){
19650  memcpy(
19651    &GLOBAL(struct sqlite3PrngType, sqlite3Prng),
19652    &GLOBAL(struct sqlite3PrngType, sqlite3SavedPrng),
19653    sizeof(sqlite3Prng)
19654  );
19655}
19656SQLITE_PRIVATE void sqlite3PrngResetState(void){
19657  GLOBAL(struct sqlite3PrngType, sqlite3Prng).isInit = 0;
19658}
19659#endif /* SQLITE_OMIT_BUILTIN_TEST */
19660
19661/************** End of random.c **********************************************/
19662/************** Begin file utf.c *********************************************/
19663/*
19664** 2004 April 13
19665**
19666** The author disclaims copyright to this source code.  In place of
19667** a legal notice, here is a blessing:
19668**
19669**    May you do good and not evil.
19670**    May you find forgiveness for yourself and forgive others.
19671**    May you share freely, never taking more than you give.
19672**
19673*************************************************************************
19674** This file contains routines used to translate between UTF-8,
19675** UTF-16, UTF-16BE, and UTF-16LE.
19676**
19677** Notes on UTF-8:
19678**
19679**   Byte-0    Byte-1    Byte-2    Byte-3    Value
19680**  0xxxxxxx                                 00000000 00000000 0xxxxxxx
19681**  110yyyyy  10xxxxxx                       00000000 00000yyy yyxxxxxx
19682**  1110zzzz  10yyyyyy  10xxxxxx             00000000 zzzzyyyy yyxxxxxx
19683**  11110uuu  10uuzzzz  10yyyyyy  10xxxxxx   000uuuuu zzzzyyyy yyxxxxxx
19684**
19685**
19686** Notes on UTF-16:  (with wwww+1==uuuuu)
19687**
19688**      Word-0               Word-1          Value
19689**  110110ww wwzzzzyy   110111yy yyxxxxxx    000uuuuu zzzzyyyy yyxxxxxx
19690**  zzzzyyyy yyxxxxxx                        00000000 zzzzyyyy yyxxxxxx
19691**
19692**
19693** BOM or Byte Order Mark:
19694**     0xff 0xfe   little-endian utf-16 follows
19695**     0xfe 0xff   big-endian utf-16 follows
19696**
19697*/
19698
19699#ifndef SQLITE_AMALGAMATION
19700/*
19701** The following constant value is used by the SQLITE_BIGENDIAN and
19702** SQLITE_LITTLEENDIAN macros.
19703*/
19704SQLITE_PRIVATE const int sqlite3one = 1;
19705#endif /* SQLITE_AMALGAMATION */
19706
19707/*
19708** This lookup table is used to help decode the first byte of
19709** a multi-byte UTF8 character.
19710*/
19711static const unsigned char sqlite3Utf8Trans1[] = {
19712  0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
19713  0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
19714  0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
19715  0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
19716  0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
19717  0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
19718  0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
19719  0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,
19720};
19721
19722
19723#define WRITE_UTF8(zOut, c) {                          \
19724  if( c<0x00080 ){                                     \
19725    *zOut++ = (u8)(c&0xFF);                            \
19726  }                                                    \
19727  else if( c<0x00800 ){                                \
19728    *zOut++ = 0xC0 + (u8)((c>>6)&0x1F);                \
19729    *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
19730  }                                                    \
19731  else if( c<0x10000 ){                                \
19732    *zOut++ = 0xE0 + (u8)((c>>12)&0x0F);               \
19733    *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);              \
19734    *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
19735  }else{                                               \
19736    *zOut++ = 0xF0 + (u8)((c>>18) & 0x07);             \
19737    *zOut++ = 0x80 + (u8)((c>>12) & 0x3F);             \
19738    *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);              \
19739    *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
19740  }                                                    \
19741}
19742
19743#define WRITE_UTF16LE(zOut, c) {                                    \
19744  if( c<=0xFFFF ){                                                  \
19745    *zOut++ = (u8)(c&0x00FF);                                       \
19746    *zOut++ = (u8)((c>>8)&0x00FF);                                  \
19747  }else{                                                            \
19748    *zOut++ = (u8)(((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0));  \
19749    *zOut++ = (u8)(0x00D8 + (((c-0x10000)>>18)&0x03));              \
19750    *zOut++ = (u8)(c&0x00FF);                                       \
19751    *zOut++ = (u8)(0x00DC + ((c>>8)&0x03));                         \
19752  }                                                                 \
19753}
19754
19755#define WRITE_UTF16BE(zOut, c) {                                    \
19756  if( c<=0xFFFF ){                                                  \
19757    *zOut++ = (u8)((c>>8)&0x00FF);                                  \
19758    *zOut++ = (u8)(c&0x00FF);                                       \
19759  }else{                                                            \
19760    *zOut++ = (u8)(0x00D8 + (((c-0x10000)>>18)&0x03));              \
19761    *zOut++ = (u8)(((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0));  \
19762    *zOut++ = (u8)(0x00DC + ((c>>8)&0x03));                         \
19763    *zOut++ = (u8)(c&0x00FF);                                       \
19764  }                                                                 \
19765}
19766
19767#define READ_UTF16LE(zIn, TERM, c){                                   \
19768  c = (*zIn++);                                                       \
19769  c += ((*zIn++)<<8);                                                 \
19770  if( c>=0xD800 && c<0xE000 && TERM ){                                \
19771    int c2 = (*zIn++);                                                \
19772    c2 += ((*zIn++)<<8);                                              \
19773    c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10);   \
19774  }                                                                   \
19775}
19776
19777#define READ_UTF16BE(zIn, TERM, c){                                   \
19778  c = ((*zIn++)<<8);                                                  \
19779  c += (*zIn++);                                                      \
19780  if( c>=0xD800 && c<0xE000 && TERM ){                                \
19781    int c2 = ((*zIn++)<<8);                                           \
19782    c2 += (*zIn++);                                                   \
19783    c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10);   \
19784  }                                                                   \
19785}
19786
19787/*
19788** Translate a single UTF-8 character.  Return the unicode value.
19789**
19790** During translation, assume that the byte that zTerm points
19791** is a 0x00.
19792**
19793** Write a pointer to the next unread byte back into *pzNext.
19794**
19795** Notes On Invalid UTF-8:
19796**
19797**  *  This routine never allows a 7-bit character (0x00 through 0x7f) to
19798**     be encoded as a multi-byte character.  Any multi-byte character that
19799**     attempts to encode a value between 0x00 and 0x7f is rendered as 0xfffd.
19800**
19801**  *  This routine never allows a UTF16 surrogate value to be encoded.
19802**     If a multi-byte character attempts to encode a value between
19803**     0xd800 and 0xe000 then it is rendered as 0xfffd.
19804**
19805**  *  Bytes in the range of 0x80 through 0xbf which occur as the first
19806**     byte of a character are interpreted as single-byte characters
19807**     and rendered as themselves even though they are technically
19808**     invalid characters.
19809**
19810**  *  This routine accepts an infinite number of different UTF8 encodings
19811**     for unicode values 0x80 and greater.  It do not change over-length
19812**     encodings to 0xfffd as some systems recommend.
19813*/
19814#define READ_UTF8(zIn, zTerm, c)                           \
19815  c = *(zIn++);                                            \
19816  if( c>=0xc0 ){                                           \
19817    c = sqlite3Utf8Trans1[c-0xc0];                         \
19818    while( zIn!=zTerm && (*zIn & 0xc0)==0x80 ){            \
19819      c = (c<<6) + (0x3f & *(zIn++));                      \
19820    }                                                      \
19821    if( c<0x80                                             \
19822        || (c&0xFFFFF800)==0xD800                          \
19823        || (c&0xFFFFFFFE)==0xFFFE ){  c = 0xFFFD; }        \
19824  }
19825SQLITE_PRIVATE int sqlite3Utf8Read(
19826  const unsigned char *zIn,       /* First byte of UTF-8 character */
19827  const unsigned char **pzNext    /* Write first byte past UTF-8 char here */
19828){
19829  unsigned int c;
19830
19831  /* Same as READ_UTF8() above but without the zTerm parameter.
19832  ** For this routine, we assume the UTF8 string is always zero-terminated.
19833  */
19834  c = *(zIn++);
19835  if( c>=0xc0 ){
19836    c = sqlite3Utf8Trans1[c-0xc0];
19837    while( (*zIn & 0xc0)==0x80 ){
19838      c = (c<<6) + (0x3f & *(zIn++));
19839    }
19840    if( c<0x80
19841        || (c&0xFFFFF800)==0xD800
19842        || (c&0xFFFFFFFE)==0xFFFE ){  c = 0xFFFD; }
19843  }
19844  *pzNext = zIn;
19845  return c;
19846}
19847
19848
19849
19850
19851/*
19852** If the TRANSLATE_TRACE macro is defined, the value of each Mem is
19853** printed on stderr on the way into and out of sqlite3VdbeMemTranslate().
19854*/
19855/* #define TRANSLATE_TRACE 1 */
19856
19857#ifndef SQLITE_OMIT_UTF16
19858/*
19859** This routine transforms the internal text encoding used by pMem to
19860** desiredEnc. It is an error if the string is already of the desired
19861** encoding, or if *pMem does not contain a string value.
19862*/
19863SQLITE_PRIVATE int sqlite3VdbeMemTranslate(Mem *pMem, u8 desiredEnc){
19864  int len;                    /* Maximum length of output string in bytes */
19865  unsigned char *zOut;                  /* Output buffer */
19866  unsigned char *zIn;                   /* Input iterator */
19867  unsigned char *zTerm;                 /* End of input */
19868  unsigned char *z;                     /* Output iterator */
19869  unsigned int c;
19870
19871  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
19872  assert( pMem->flags&MEM_Str );
19873  assert( pMem->enc!=desiredEnc );
19874  assert( pMem->enc!=0 );
19875  assert( pMem->n>=0 );
19876
19877#if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG)
19878  {
19879    char zBuf[100];
19880    sqlite3VdbeMemPrettyPrint(pMem, zBuf);
19881    fprintf(stderr, "INPUT:  %s\n", zBuf);
19882  }
19883#endif
19884
19885  /* If the translation is between UTF-16 little and big endian, then
19886  ** all that is required is to swap the byte order. This case is handled
19887  ** differently from the others.
19888  */
19889  if( pMem->enc!=SQLITE_UTF8 && desiredEnc!=SQLITE_UTF8 ){
19890    u8 temp;
19891    int rc;
19892    rc = sqlite3VdbeMemMakeWriteable(pMem);
19893    if( rc!=SQLITE_OK ){
19894      assert( rc==SQLITE_NOMEM );
19895      return SQLITE_NOMEM;
19896    }
19897    zIn = (u8*)pMem->z;
19898    zTerm = &zIn[pMem->n&~1];
19899    while( zIn<zTerm ){
19900      temp = *zIn;
19901      *zIn = *(zIn+1);
19902      zIn++;
19903      *zIn++ = temp;
19904    }
19905    pMem->enc = desiredEnc;
19906    goto translate_out;
19907  }
19908
19909  /* Set len to the maximum number of bytes required in the output buffer. */
19910  if( desiredEnc==SQLITE_UTF8 ){
19911    /* When converting from UTF-16, the maximum growth results from
19912    ** translating a 2-byte character to a 4-byte UTF-8 character.
19913    ** A single byte is required for the output string
19914    ** nul-terminator.
19915    */
19916    pMem->n &= ~1;
19917    len = pMem->n * 2 + 1;
19918  }else{
19919    /* When converting from UTF-8 to UTF-16 the maximum growth is caused
19920    ** when a 1-byte UTF-8 character is translated into a 2-byte UTF-16
19921    ** character. Two bytes are required in the output buffer for the
19922    ** nul-terminator.
19923    */
19924    len = pMem->n * 2 + 2;
19925  }
19926
19927  /* Set zIn to point at the start of the input buffer and zTerm to point 1
19928  ** byte past the end.
19929  **
19930  ** Variable zOut is set to point at the output buffer, space obtained
19931  ** from sqlite3_malloc().
19932  */
19933  zIn = (u8*)pMem->z;
19934  zTerm = &zIn[pMem->n];
19935  zOut = sqlite3DbMallocRaw(pMem->db, len);
19936  if( !zOut ){
19937    return SQLITE_NOMEM;
19938  }
19939  z = zOut;
19940
19941  if( pMem->enc==SQLITE_UTF8 ){
19942    if( desiredEnc==SQLITE_UTF16LE ){
19943      /* UTF-8 -> UTF-16 Little-endian */
19944      while( zIn<zTerm ){
19945        /* c = sqlite3Utf8Read(zIn, zTerm, (const u8**)&zIn); */
19946        READ_UTF8(zIn, zTerm, c);
19947        WRITE_UTF16LE(z, c);
19948      }
19949    }else{
19950      assert( desiredEnc==SQLITE_UTF16BE );
19951      /* UTF-8 -> UTF-16 Big-endian */
19952      while( zIn<zTerm ){
19953        /* c = sqlite3Utf8Read(zIn, zTerm, (const u8**)&zIn); */
19954        READ_UTF8(zIn, zTerm, c);
19955        WRITE_UTF16BE(z, c);
19956      }
19957    }
19958    pMem->n = (int)(z - zOut);
19959    *z++ = 0;
19960  }else{
19961    assert( desiredEnc==SQLITE_UTF8 );
19962    if( pMem->enc==SQLITE_UTF16LE ){
19963      /* UTF-16 Little-endian -> UTF-8 */
19964      while( zIn<zTerm ){
19965        READ_UTF16LE(zIn, zIn<zTerm, c);
19966        WRITE_UTF8(z, c);
19967      }
19968    }else{
19969      /* UTF-16 Big-endian -> UTF-8 */
19970      while( zIn<zTerm ){
19971        READ_UTF16BE(zIn, zIn<zTerm, c);
19972        WRITE_UTF8(z, c);
19973      }
19974    }
19975    pMem->n = (int)(z - zOut);
19976  }
19977  *z = 0;
19978  assert( (pMem->n+(desiredEnc==SQLITE_UTF8?1:2))<=len );
19979
19980  sqlite3VdbeMemRelease(pMem);
19981  pMem->flags &= ~(MEM_Static|MEM_Dyn|MEM_Ephem);
19982  pMem->enc = desiredEnc;
19983  pMem->flags |= (MEM_Term|MEM_Dyn);
19984  pMem->z = (char*)zOut;
19985  pMem->zMalloc = pMem->z;
19986
19987translate_out:
19988#if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG)
19989  {
19990    char zBuf[100];
19991    sqlite3VdbeMemPrettyPrint(pMem, zBuf);
19992    fprintf(stderr, "OUTPUT: %s\n", zBuf);
19993  }
19994#endif
19995  return SQLITE_OK;
19996}
19997
19998/*
19999** This routine checks for a byte-order mark at the beginning of the
20000** UTF-16 string stored in *pMem. If one is present, it is removed and
20001** the encoding of the Mem adjusted. This routine does not do any
20002** byte-swapping, it just sets Mem.enc appropriately.
20003**
20004** The allocation (static, dynamic etc.) and encoding of the Mem may be
20005** changed by this function.
20006*/
20007SQLITE_PRIVATE int sqlite3VdbeMemHandleBom(Mem *pMem){
20008  int rc = SQLITE_OK;
20009  u8 bom = 0;
20010
20011  assert( pMem->n>=0 );
20012  if( pMem->n>1 ){
20013    u8 b1 = *(u8 *)pMem->z;
20014    u8 b2 = *(((u8 *)pMem->z) + 1);
20015    if( b1==0xFE && b2==0xFF ){
20016      bom = SQLITE_UTF16BE;
20017    }
20018    if( b1==0xFF && b2==0xFE ){
20019      bom = SQLITE_UTF16LE;
20020    }
20021  }
20022
20023  if( bom ){
20024    rc = sqlite3VdbeMemMakeWriteable(pMem);
20025    if( rc==SQLITE_OK ){
20026      pMem->n -= 2;
20027      memmove(pMem->z, &pMem->z[2], pMem->n);
20028      pMem->z[pMem->n] = '\0';
20029      pMem->z[pMem->n+1] = '\0';
20030      pMem->flags |= MEM_Term;
20031      pMem->enc = bom;
20032    }
20033  }
20034  return rc;
20035}
20036#endif /* SQLITE_OMIT_UTF16 */
20037
20038/*
20039** pZ is a UTF-8 encoded unicode string. If nByte is less than zero,
20040** return the number of unicode characters in pZ up to (but not including)
20041** the first 0x00 byte. If nByte is not less than zero, return the
20042** number of unicode characters in the first nByte of pZ (or up to
20043** the first 0x00, whichever comes first).
20044*/
20045SQLITE_PRIVATE int sqlite3Utf8CharLen(const char *zIn, int nByte){
20046  int r = 0;
20047  const u8 *z = (const u8*)zIn;
20048  const u8 *zTerm;
20049  if( nByte>=0 ){
20050    zTerm = &z[nByte];
20051  }else{
20052    zTerm = (const u8*)(-1);
20053  }
20054  assert( z<=zTerm );
20055  while( *z!=0 && z<zTerm ){
20056    SQLITE_SKIP_UTF8(z);
20057    r++;
20058  }
20059  return r;
20060}
20061
20062/* This test function is not currently used by the automated test-suite.
20063** Hence it is only available in debug builds.
20064*/
20065#if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
20066/*
20067** Translate UTF-8 to UTF-8.
20068**
20069** This has the effect of making sure that the string is well-formed
20070** UTF-8.  Miscoded characters are removed.
20071**
20072** The translation is done in-place and aborted if the output
20073** overruns the input.
20074*/
20075SQLITE_PRIVATE int sqlite3Utf8To8(unsigned char *zIn){
20076  unsigned char *zOut = zIn;
20077  unsigned char *zStart = zIn;
20078  u32 c;
20079
20080  while( zIn[0] && zOut<=zIn ){
20081    c = sqlite3Utf8Read(zIn, (const u8**)&zIn);
20082    if( c!=0xfffd ){
20083      WRITE_UTF8(zOut, c);
20084    }
20085  }
20086  *zOut = 0;
20087  return (int)(zOut - zStart);
20088}
20089#endif
20090
20091#ifndef SQLITE_OMIT_UTF16
20092/*
20093** Convert a UTF-16 string in the native encoding into a UTF-8 string.
20094** Memory to hold the UTF-8 string is obtained from sqlite3_malloc and must
20095** be freed by the calling function.
20096**
20097** NULL is returned if there is an allocation error.
20098*/
20099SQLITE_PRIVATE char *sqlite3Utf16to8(sqlite3 *db, const void *z, int nByte, u8 enc){
20100  Mem m;
20101  memset(&m, 0, sizeof(m));
20102  m.db = db;
20103  sqlite3VdbeMemSetStr(&m, z, nByte, enc, SQLITE_STATIC);
20104  sqlite3VdbeChangeEncoding(&m, SQLITE_UTF8);
20105  if( db->mallocFailed ){
20106    sqlite3VdbeMemRelease(&m);
20107    m.z = 0;
20108  }
20109  assert( (m.flags & MEM_Term)!=0 || db->mallocFailed );
20110  assert( (m.flags & MEM_Str)!=0 || db->mallocFailed );
20111  assert( (m.flags & MEM_Dyn)!=0 || db->mallocFailed );
20112  assert( m.z || db->mallocFailed );
20113  return m.z;
20114}
20115
20116/*
20117** Convert a UTF-8 string to the UTF-16 encoding specified by parameter
20118** enc. A pointer to the new string is returned, and the value of *pnOut
20119** is set to the length of the returned string in bytes. The call should
20120** arrange to call sqlite3DbFree() on the returned pointer when it is
20121** no longer required.
20122**
20123** If a malloc failure occurs, NULL is returned and the db.mallocFailed
20124** flag set.
20125*/
20126#ifdef SQLITE_ENABLE_STAT2
20127SQLITE_PRIVATE char *sqlite3Utf8to16(sqlite3 *db, u8 enc, char *z, int n, int *pnOut){
20128  Mem m;
20129  memset(&m, 0, sizeof(m));
20130  m.db = db;
20131  sqlite3VdbeMemSetStr(&m, z, n, SQLITE_UTF8, SQLITE_STATIC);
20132  if( sqlite3VdbeMemTranslate(&m, enc) ){
20133    assert( db->mallocFailed );
20134    return 0;
20135  }
20136  assert( m.z==m.zMalloc );
20137  *pnOut = m.n;
20138  return m.z;
20139}
20140#endif
20141
20142/*
20143** zIn is a UTF-16 encoded unicode string at least nChar characters long.
20144** Return the number of bytes in the first nChar unicode characters
20145** in pZ.  nChar must be non-negative.
20146*/
20147SQLITE_PRIVATE int sqlite3Utf16ByteLen(const void *zIn, int nChar){
20148  int c;
20149  unsigned char const *z = zIn;
20150  int n = 0;
20151
20152  if( SQLITE_UTF16NATIVE==SQLITE_UTF16BE ){
20153    while( n<nChar ){
20154      READ_UTF16BE(z, 1, c);
20155      n++;
20156    }
20157  }else{
20158    while( n<nChar ){
20159      READ_UTF16LE(z, 1, c);
20160      n++;
20161    }
20162  }
20163  return (int)(z-(unsigned char const *)zIn);
20164}
20165
20166#if defined(SQLITE_TEST)
20167/*
20168** This routine is called from the TCL test function "translate_selftest".
20169** It checks that the primitives for serializing and deserializing
20170** characters in each encoding are inverses of each other.
20171*/
20172SQLITE_PRIVATE void sqlite3UtfSelfTest(void){
20173  unsigned int i, t;
20174  unsigned char zBuf[20];
20175  unsigned char *z;
20176  int n;
20177  unsigned int c;
20178
20179  for(i=0; i<0x00110000; i++){
20180    z = zBuf;
20181    WRITE_UTF8(z, i);
20182    n = (int)(z-zBuf);
20183    assert( n>0 && n<=4 );
20184    z[0] = 0;
20185    z = zBuf;
20186    c = sqlite3Utf8Read(z, (const u8**)&z);
20187    t = i;
20188    if( i>=0xD800 && i<=0xDFFF ) t = 0xFFFD;
20189    if( (i&0xFFFFFFFE)==0xFFFE ) t = 0xFFFD;
20190    assert( c==t );
20191    assert( (z-zBuf)==n );
20192  }
20193  for(i=0; i<0x00110000; i++){
20194    if( i>=0xD800 && i<0xE000 ) continue;
20195    z = zBuf;
20196    WRITE_UTF16LE(z, i);
20197    n = (int)(z-zBuf);
20198    assert( n>0 && n<=4 );
20199    z[0] = 0;
20200    z = zBuf;
20201    READ_UTF16LE(z, 1, c);
20202    assert( c==i );
20203    assert( (z-zBuf)==n );
20204  }
20205  for(i=0; i<0x00110000; i++){
20206    if( i>=0xD800 && i<0xE000 ) continue;
20207    z = zBuf;
20208    WRITE_UTF16BE(z, i);
20209    n = (int)(z-zBuf);
20210    assert( n>0 && n<=4 );
20211    z[0] = 0;
20212    z = zBuf;
20213    READ_UTF16BE(z, 1, c);
20214    assert( c==i );
20215    assert( (z-zBuf)==n );
20216  }
20217}
20218#endif /* SQLITE_TEST */
20219#endif /* SQLITE_OMIT_UTF16 */
20220
20221/************** End of utf.c *************************************************/
20222/************** Begin file util.c ********************************************/
20223/*
20224** 2001 September 15
20225**
20226** The author disclaims copyright to this source code.  In place of
20227** a legal notice, here is a blessing:
20228**
20229**    May you do good and not evil.
20230**    May you find forgiveness for yourself and forgive others.
20231**    May you share freely, never taking more than you give.
20232**
20233*************************************************************************
20234** Utility functions used throughout sqlite.
20235**
20236** This file contains functions for allocating memory, comparing
20237** strings, and stuff like that.
20238**
20239*/
20240#ifdef SQLITE_HAVE_ISNAN
20241# include <math.h>
20242#endif
20243
20244/*
20245** Routine needed to support the testcase() macro.
20246*/
20247#ifdef SQLITE_COVERAGE_TEST
20248SQLITE_PRIVATE void sqlite3Coverage(int x){
20249  static unsigned dummy = 0;
20250  dummy += (unsigned)x;
20251}
20252#endif
20253
20254#ifndef SQLITE_OMIT_FLOATING_POINT
20255/*
20256** Return true if the floating point value is Not a Number (NaN).
20257**
20258** Use the math library isnan() function if compiled with SQLITE_HAVE_ISNAN.
20259** Otherwise, we have our own implementation that works on most systems.
20260*/
20261SQLITE_PRIVATE int sqlite3IsNaN(double x){
20262  int rc;   /* The value return */
20263#if !defined(SQLITE_HAVE_ISNAN)
20264  /*
20265  ** Systems that support the isnan() library function should probably
20266  ** make use of it by compiling with -DSQLITE_HAVE_ISNAN.  But we have
20267  ** found that many systems do not have a working isnan() function so
20268  ** this implementation is provided as an alternative.
20269  **
20270  ** This NaN test sometimes fails if compiled on GCC with -ffast-math.
20271  ** On the other hand, the use of -ffast-math comes with the following
20272  ** warning:
20273  **
20274  **      This option [-ffast-math] should never be turned on by any
20275  **      -O option since it can result in incorrect output for programs
20276  **      which depend on an exact implementation of IEEE or ISO
20277  **      rules/specifications for math functions.
20278  **
20279  ** Under MSVC, this NaN test may fail if compiled with a floating-
20280  ** point precision mode other than /fp:precise.  From the MSDN
20281  ** documentation:
20282  **
20283  **      The compiler [with /fp:precise] will properly handle comparisons
20284  **      involving NaN. For example, x != x evaluates to true if x is NaN
20285  **      ...
20286  */
20287#ifdef __FAST_MATH__
20288# error SQLite will not work correctly with the -ffast-math option of GCC.
20289#endif
20290  volatile double y = x;
20291  volatile double z = y;
20292  rc = (y!=z);
20293#else  /* if defined(SQLITE_HAVE_ISNAN) */
20294  rc = isnan(x);
20295#endif /* SQLITE_HAVE_ISNAN */
20296  testcase( rc );
20297  return rc;
20298}
20299#endif /* SQLITE_OMIT_FLOATING_POINT */
20300
20301/*
20302** Compute a string length that is limited to what can be stored in
20303** lower 30 bits of a 32-bit signed integer.
20304**
20305** The value returned will never be negative.  Nor will it ever be greater
20306** than the actual length of the string.  For very long strings (greater
20307** than 1GiB) the value returned might be less than the true string length.
20308*/
20309SQLITE_PRIVATE int sqlite3Strlen30(const char *z){
20310  const char *z2 = z;
20311  if( z==0 ) return 0;
20312  while( *z2 ){ z2++; }
20313  return 0x3fffffff & (int)(z2 - z);
20314}
20315
20316/*
20317** Set the most recent error code and error string for the sqlite
20318** handle "db". The error code is set to "err_code".
20319**
20320** If it is not NULL, string zFormat specifies the format of the
20321** error string in the style of the printf functions: The following
20322** format characters are allowed:
20323**
20324**      %s      Insert a string
20325**      %z      A string that should be freed after use
20326**      %d      Insert an integer
20327**      %T      Insert a token
20328**      %S      Insert the first element of a SrcList
20329**
20330** zFormat and any string tokens that follow it are assumed to be
20331** encoded in UTF-8.
20332**
20333** To clear the most recent error for sqlite handle "db", sqlite3Error
20334** should be called with err_code set to SQLITE_OK and zFormat set
20335** to NULL.
20336*/
20337SQLITE_PRIVATE void sqlite3Error(sqlite3 *db, int err_code, const char *zFormat, ...){
20338  if( db && (db->pErr || (db->pErr = sqlite3ValueNew(db))!=0) ){
20339    db->errCode = err_code;
20340    if( zFormat ){
20341      char *z;
20342      va_list ap;
20343      va_start(ap, zFormat);
20344      z = sqlite3VMPrintf(db, zFormat, ap);
20345      va_end(ap);
20346      sqlite3ValueSetStr(db->pErr, -1, z, SQLITE_UTF8, SQLITE_DYNAMIC);
20347    }else{
20348      sqlite3ValueSetStr(db->pErr, 0, 0, SQLITE_UTF8, SQLITE_STATIC);
20349    }
20350  }
20351}
20352
20353/*
20354** Add an error message to pParse->zErrMsg and increment pParse->nErr.
20355** The following formatting characters are allowed:
20356**
20357**      %s      Insert a string
20358**      %z      A string that should be freed after use
20359**      %d      Insert an integer
20360**      %T      Insert a token
20361**      %S      Insert the first element of a SrcList
20362**
20363** This function should be used to report any error that occurs whilst
20364** compiling an SQL statement (i.e. within sqlite3_prepare()). The
20365** last thing the sqlite3_prepare() function does is copy the error
20366** stored by this function into the database handle using sqlite3Error().
20367** Function sqlite3Error() should be used during statement execution
20368** (sqlite3_step() etc.).
20369*/
20370SQLITE_PRIVATE void sqlite3ErrorMsg(Parse *pParse, const char *zFormat, ...){
20371  char *zMsg;
20372  va_list ap;
20373  sqlite3 *db = pParse->db;
20374  va_start(ap, zFormat);
20375  zMsg = sqlite3VMPrintf(db, zFormat, ap);
20376  va_end(ap);
20377  if( db->suppressErr ){
20378    sqlite3DbFree(db, zMsg);
20379  }else{
20380    pParse->nErr++;
20381    sqlite3DbFree(db, pParse->zErrMsg);
20382    pParse->zErrMsg = zMsg;
20383    pParse->rc = SQLITE_ERROR;
20384  }
20385}
20386
20387/*
20388** Convert an SQL-style quoted string into a normal string by removing
20389** the quote characters.  The conversion is done in-place.  If the
20390** input does not begin with a quote character, then this routine
20391** is a no-op.
20392**
20393** The input string must be zero-terminated.  A new zero-terminator
20394** is added to the dequoted string.
20395**
20396** The return value is -1 if no dequoting occurs or the length of the
20397** dequoted string, exclusive of the zero terminator, if dequoting does
20398** occur.
20399**
20400** 2002-Feb-14: This routine is extended to remove MS-Access style
20401** brackets from around identifers.  For example:  "[a-b-c]" becomes
20402** "a-b-c".
20403*/
20404SQLITE_PRIVATE int sqlite3Dequote(char *z){
20405  char quote;
20406  int i, j;
20407  if( z==0 ) return -1;
20408  quote = z[0];
20409  switch( quote ){
20410    case '\'':  break;
20411    case '"':   break;
20412    case '`':   break;                /* For MySQL compatibility */
20413    case '[':   quote = ']';  break;  /* For MS SqlServer compatibility */
20414    default:    return -1;
20415  }
20416  for(i=1, j=0; ALWAYS(z[i]); i++){
20417    if( z[i]==quote ){
20418      if( z[i+1]==quote ){
20419        z[j++] = quote;
20420        i++;
20421      }else{
20422        break;
20423      }
20424    }else{
20425      z[j++] = z[i];
20426    }
20427  }
20428  z[j] = 0;
20429  return j;
20430}
20431
20432/* Convenient short-hand */
20433#define UpperToLower sqlite3UpperToLower
20434
20435/*
20436** Some systems have stricmp().  Others have strcasecmp().  Because
20437** there is no consistency, we will define our own.
20438**
20439** IMPLEMENTATION-OF: R-20522-24639 The sqlite3_strnicmp() API allows
20440** applications and extensions to compare the contents of two buffers
20441** containing UTF-8 strings in a case-independent fashion, using the same
20442** definition of case independence that SQLite uses internally when
20443** comparing identifiers.
20444*/
20445SQLITE_PRIVATE int sqlite3StrICmp(const char *zLeft, const char *zRight){
20446  register unsigned char *a, *b;
20447  a = (unsigned char *)zLeft;
20448  b = (unsigned char *)zRight;
20449  while( *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
20450  return UpperToLower[*a] - UpperToLower[*b];
20451}
20452SQLITE_API int sqlite3_strnicmp(const char *zLeft, const char *zRight, int N){
20453  register unsigned char *a, *b;
20454  a = (unsigned char *)zLeft;
20455  b = (unsigned char *)zRight;
20456  while( N-- > 0 && *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
20457  return N<0 ? 0 : UpperToLower[*a] - UpperToLower[*b];
20458}
20459
20460/*
20461** The string z[] is an text representation of a real number.
20462** Convert this string to a double and write it into *pResult.
20463**
20464** The string z[] is length bytes in length (bytes, not characters) and
20465** uses the encoding enc.  The string is not necessarily zero-terminated.
20466**
20467** Return TRUE if the result is a valid real number (or integer) and FALSE
20468** if the string is empty or contains extraneous text.  Valid numbers
20469** are in one of these formats:
20470**
20471**    [+-]digits[E[+-]digits]
20472**    [+-]digits.[digits][E[+-]digits]
20473**    [+-].digits[E[+-]digits]
20474**
20475** Leading and trailing whitespace is ignored for the purpose of determining
20476** validity.
20477**
20478** If some prefix of the input string is a valid number, this routine
20479** returns FALSE but it still converts the prefix and writes the result
20480** into *pResult.
20481*/
20482SQLITE_PRIVATE int sqlite3AtoF(const char *z, double *pResult, int length, u8 enc){
20483#ifndef SQLITE_OMIT_FLOATING_POINT
20484  int incr = (enc==SQLITE_UTF8?1:2);
20485  const char *zEnd = z + length;
20486  /* sign * significand * (10 ^ (esign * exponent)) */
20487  int sign = 1;    /* sign of significand */
20488  i64 s = 0;       /* significand */
20489  int d = 0;       /* adjust exponent for shifting decimal point */
20490  int esign = 1;   /* sign of exponent */
20491  int e = 0;       /* exponent */
20492  int eValid = 1;  /* True exponent is either not used or is well-formed */
20493  double result;
20494  int nDigits = 0;
20495
20496  *pResult = 0.0;   /* Default return value, in case of an error */
20497
20498  if( enc==SQLITE_UTF16BE ) z++;
20499
20500  /* skip leading spaces */
20501  while( z<zEnd && sqlite3Isspace(*z) ) z+=incr;
20502  if( z>=zEnd ) return 0;
20503
20504  /* get sign of significand */
20505  if( *z=='-' ){
20506    sign = -1;
20507    z+=incr;
20508  }else if( *z=='+' ){
20509    z+=incr;
20510  }
20511
20512  /* skip leading zeroes */
20513  while( z<zEnd && z[0]=='0' ) z+=incr, nDigits++;
20514
20515  /* copy max significant digits to significand */
20516  while( z<zEnd && sqlite3Isdigit(*z) && s<((LARGEST_INT64-9)/10) ){
20517    s = s*10 + (*z - '0');
20518    z+=incr, nDigits++;
20519  }
20520
20521  /* skip non-significant significand digits
20522  ** (increase exponent by d to shift decimal left) */
20523  while( z<zEnd && sqlite3Isdigit(*z) ) z+=incr, nDigits++, d++;
20524  if( z>=zEnd ) goto do_atof_calc;
20525
20526  /* if decimal point is present */
20527  if( *z=='.' ){
20528    z+=incr;
20529    /* copy digits from after decimal to significand
20530    ** (decrease exponent by d to shift decimal right) */
20531    while( z<zEnd && sqlite3Isdigit(*z) && s<((LARGEST_INT64-9)/10) ){
20532      s = s*10 + (*z - '0');
20533      z+=incr, nDigits++, d--;
20534    }
20535    /* skip non-significant digits */
20536    while( z<zEnd && sqlite3Isdigit(*z) ) z+=incr, nDigits++;
20537  }
20538  if( z>=zEnd ) goto do_atof_calc;
20539
20540  /* if exponent is present */
20541  if( *z=='e' || *z=='E' ){
20542    z+=incr;
20543    eValid = 0;
20544    if( z>=zEnd ) goto do_atof_calc;
20545    /* get sign of exponent */
20546    if( *z=='-' ){
20547      esign = -1;
20548      z+=incr;
20549    }else if( *z=='+' ){
20550      z+=incr;
20551    }
20552    /* copy digits to exponent */
20553    while( z<zEnd && sqlite3Isdigit(*z) ){
20554      e = e*10 + (*z - '0');
20555      z+=incr;
20556      eValid = 1;
20557    }
20558  }
20559
20560  /* skip trailing spaces */
20561  if( nDigits && eValid ){
20562    while( z<zEnd && sqlite3Isspace(*z) ) z+=incr;
20563  }
20564
20565do_atof_calc:
20566  /* adjust exponent by d, and update sign */
20567  e = (e*esign) + d;
20568  if( e<0 ) {
20569    esign = -1;
20570    e *= -1;
20571  } else {
20572    esign = 1;
20573  }
20574
20575  /* if 0 significand */
20576  if( !s ) {
20577    /* In the IEEE 754 standard, zero is signed.
20578    ** Add the sign if we've seen at least one digit */
20579    result = (sign<0 && nDigits) ? -(double)0 : (double)0;
20580  } else {
20581    /* attempt to reduce exponent */
20582    if( esign>0 ){
20583      while( s<(LARGEST_INT64/10) && e>0 ) e--,s*=10;
20584    }else{
20585      while( !(s%10) && e>0 ) e--,s/=10;
20586    }
20587
20588    /* adjust the sign of significand */
20589    s = sign<0 ? -s : s;
20590
20591    /* if exponent, scale significand as appropriate
20592    ** and store in result. */
20593    if( e ){
20594      double scale = 1.0;
20595      /* attempt to handle extremely small/large numbers better */
20596      if( e>307 && e<342 ){
20597        while( e%308 ) { scale *= 1.0e+1; e -= 1; }
20598        if( esign<0 ){
20599          result = s / scale;
20600          result /= 1.0e+308;
20601        }else{
20602          result = s * scale;
20603          result *= 1.0e+308;
20604        }
20605      }else{
20606        /* 1.0e+22 is the largest power of 10 than can be
20607        ** represented exactly. */
20608        while( e%22 ) { scale *= 1.0e+1; e -= 1; }
20609        while( e>0 ) { scale *= 1.0e+22; e -= 22; }
20610        if( esign<0 ){
20611          result = s / scale;
20612        }else{
20613          result = s * scale;
20614        }
20615      }
20616    } else {
20617      result = (double)s;
20618    }
20619  }
20620
20621  /* store the result */
20622  *pResult = result;
20623
20624  /* return true if number and no extra non-whitespace chracters after */
20625  return z>=zEnd && nDigits>0 && eValid;
20626#else
20627  return !sqlite3Atoi64(z, pResult, length, enc);
20628#endif /* SQLITE_OMIT_FLOATING_POINT */
20629}
20630
20631/*
20632** Compare the 19-character string zNum against the text representation
20633** value 2^63:  9223372036854775808.  Return negative, zero, or positive
20634** if zNum is less than, equal to, or greater than the string.
20635** Note that zNum must contain exactly 19 characters.
20636**
20637** Unlike memcmp() this routine is guaranteed to return the difference
20638** in the values of the last digit if the only difference is in the
20639** last digit.  So, for example,
20640**
20641**      compare2pow63("9223372036854775800", 1)
20642**
20643** will return -8.
20644*/
20645static int compare2pow63(const char *zNum, int incr){
20646  int c = 0;
20647  int i;
20648                    /* 012345678901234567 */
20649  const char *pow63 = "922337203685477580";
20650  for(i=0; c==0 && i<18; i++){
20651    c = (zNum[i*incr]-pow63[i])*10;
20652  }
20653  if( c==0 ){
20654    c = zNum[18*incr] - '8';
20655    testcase( c==(-1) );
20656    testcase( c==0 );
20657    testcase( c==(+1) );
20658  }
20659  return c;
20660}
20661
20662
20663/*
20664** Convert zNum to a 64-bit signed integer.
20665**
20666** If the zNum value is representable as a 64-bit twos-complement
20667** integer, then write that value into *pNum and return 0.
20668**
20669** If zNum is exactly 9223372036854665808, return 2.  This special
20670** case is broken out because while 9223372036854665808 cannot be a
20671** signed 64-bit integer, its negative -9223372036854665808 can be.
20672**
20673** If zNum is too big for a 64-bit integer and is not
20674** 9223372036854665808 then return 1.
20675**
20676** length is the number of bytes in the string (bytes, not characters).
20677** The string is not necessarily zero-terminated.  The encoding is
20678** given by enc.
20679*/
20680SQLITE_PRIVATE int sqlite3Atoi64(const char *zNum, i64 *pNum, int length, u8 enc){
20681  int incr = (enc==SQLITE_UTF8?1:2);
20682  u64 u = 0;
20683  int neg = 0; /* assume positive */
20684  int i;
20685  int c = 0;
20686  const char *zStart;
20687  const char *zEnd = zNum + length;
20688  if( enc==SQLITE_UTF16BE ) zNum++;
20689  while( zNum<zEnd && sqlite3Isspace(*zNum) ) zNum+=incr;
20690  if( zNum<zEnd ){
20691    if( *zNum=='-' ){
20692      neg = 1;
20693      zNum+=incr;
20694    }else if( *zNum=='+' ){
20695      zNum+=incr;
20696    }
20697  }
20698  zStart = zNum;
20699  while( zNum<zEnd && zNum[0]=='0' ){ zNum+=incr; } /* Skip leading zeros. */
20700  for(i=0; &zNum[i]<zEnd && (c=zNum[i])>='0' && c<='9'; i+=incr){
20701    u = u*10 + c - '0';
20702  }
20703  if( u>LARGEST_INT64 ){
20704    *pNum = SMALLEST_INT64;
20705  }else if( neg ){
20706    *pNum = -(i64)u;
20707  }else{
20708    *pNum = (i64)u;
20709  }
20710  testcase( i==18 );
20711  testcase( i==19 );
20712  testcase( i==20 );
20713  if( (c!=0 && &zNum[i]<zEnd) || (i==0 && zStart==zNum) || i>19*incr ){
20714    /* zNum is empty or contains non-numeric text or is longer
20715    ** than 19 digits (thus guaranteeing that it is too large) */
20716    return 1;
20717  }else if( i<19*incr ){
20718    /* Less than 19 digits, so we know that it fits in 64 bits */
20719    assert( u<=LARGEST_INT64 );
20720    return 0;
20721  }else{
20722    /* zNum is a 19-digit numbers.  Compare it against 9223372036854775808. */
20723    c = compare2pow63(zNum, incr);
20724    if( c<0 ){
20725      /* zNum is less than 9223372036854775808 so it fits */
20726      assert( u<=LARGEST_INT64 );
20727      return 0;
20728    }else if( c>0 ){
20729      /* zNum is greater than 9223372036854775808 so it overflows */
20730      return 1;
20731    }else{
20732      /* zNum is exactly 9223372036854775808.  Fits if negative.  The
20733      ** special case 2 overflow if positive */
20734      assert( u-1==LARGEST_INT64 );
20735      assert( (*pNum)==SMALLEST_INT64 );
20736      return neg ? 0 : 2;
20737    }
20738  }
20739}
20740
20741/*
20742** If zNum represents an integer that will fit in 32-bits, then set
20743** *pValue to that integer and return true.  Otherwise return false.
20744**
20745** Any non-numeric characters that following zNum are ignored.
20746** This is different from sqlite3Atoi64() which requires the
20747** input number to be zero-terminated.
20748*/
20749SQLITE_PRIVATE int sqlite3GetInt32(const char *zNum, int *pValue){
20750  sqlite_int64 v = 0;
20751  int i, c;
20752  int neg = 0;
20753  if( zNum[0]=='-' ){
20754    neg = 1;
20755    zNum++;
20756  }else if( zNum[0]=='+' ){
20757    zNum++;
20758  }
20759  while( zNum[0]=='0' ) zNum++;
20760  for(i=0; i<11 && (c = zNum[i] - '0')>=0 && c<=9; i++){
20761    v = v*10 + c;
20762  }
20763
20764  /* The longest decimal representation of a 32 bit integer is 10 digits:
20765  **
20766  **             1234567890
20767  **     2^31 -> 2147483648
20768  */
20769  testcase( i==10 );
20770  if( i>10 ){
20771    return 0;
20772  }
20773  testcase( v-neg==2147483647 );
20774  if( v-neg>2147483647 ){
20775    return 0;
20776  }
20777  if( neg ){
20778    v = -v;
20779  }
20780  *pValue = (int)v;
20781  return 1;
20782}
20783
20784/*
20785** Return a 32-bit integer value extracted from a string.  If the
20786** string is not an integer, just return 0.
20787*/
20788SQLITE_PRIVATE int sqlite3Atoi(const char *z){
20789  int x = 0;
20790  if( z ) sqlite3GetInt32(z, &x);
20791  return x;
20792}
20793
20794/*
20795** The variable-length integer encoding is as follows:
20796**
20797** KEY:
20798**         A = 0xxxxxxx    7 bits of data and one flag bit
20799**         B = 1xxxxxxx    7 bits of data and one flag bit
20800**         C = xxxxxxxx    8 bits of data
20801**
20802**  7 bits - A
20803** 14 bits - BA
20804** 21 bits - BBA
20805** 28 bits - BBBA
20806** 35 bits - BBBBA
20807** 42 bits - BBBBBA
20808** 49 bits - BBBBBBA
20809** 56 bits - BBBBBBBA
20810** 64 bits - BBBBBBBBC
20811*/
20812
20813/*
20814** Write a 64-bit variable-length integer to memory starting at p[0].
20815** The length of data write will be between 1 and 9 bytes.  The number
20816** of bytes written is returned.
20817**
20818** A variable-length integer consists of the lower 7 bits of each byte
20819** for all bytes that have the 8th bit set and one byte with the 8th
20820** bit clear.  Except, if we get to the 9th byte, it stores the full
20821** 8 bits and is the last byte.
20822*/
20823SQLITE_PRIVATE int sqlite3PutVarint(unsigned char *p, u64 v){
20824  int i, j, n;
20825  u8 buf[10];
20826  if( v & (((u64)0xff000000)<<32) ){
20827    p[8] = (u8)v;
20828    v >>= 8;
20829    for(i=7; i>=0; i--){
20830      p[i] = (u8)((v & 0x7f) | 0x80);
20831      v >>= 7;
20832    }
20833    return 9;
20834  }
20835  n = 0;
20836  do{
20837    buf[n++] = (u8)((v & 0x7f) | 0x80);
20838    v >>= 7;
20839  }while( v!=0 );
20840  buf[0] &= 0x7f;
20841  assert( n<=9 );
20842  for(i=0, j=n-1; j>=0; j--, i++){
20843    p[i] = buf[j];
20844  }
20845  return n;
20846}
20847
20848/*
20849** This routine is a faster version of sqlite3PutVarint() that only
20850** works for 32-bit positive integers and which is optimized for
20851** the common case of small integers.  A MACRO version, putVarint32,
20852** is provided which inlines the single-byte case.  All code should use
20853** the MACRO version as this function assumes the single-byte case has
20854** already been handled.
20855*/
20856SQLITE_PRIVATE int sqlite3PutVarint32(unsigned char *p, u32 v){
20857#ifndef putVarint32
20858  if( (v & ~0x7f)==0 ){
20859    p[0] = v;
20860    return 1;
20861  }
20862#endif
20863  if( (v & ~0x3fff)==0 ){
20864    p[0] = (u8)((v>>7) | 0x80);
20865    p[1] = (u8)(v & 0x7f);
20866    return 2;
20867  }
20868  return sqlite3PutVarint(p, v);
20869}
20870
20871/*
20872** Bitmasks used by sqlite3GetVarint().  These precomputed constants
20873** are defined here rather than simply putting the constant expressions
20874** inline in order to work around bugs in the RVT compiler.
20875**
20876** SLOT_2_0     A mask for  (0x7f<<14) | 0x7f
20877**
20878** SLOT_4_2_0   A mask for  (0x7f<<28) | SLOT_2_0
20879*/
20880#define SLOT_2_0     0x001fc07f
20881#define SLOT_4_2_0   0xf01fc07f
20882
20883
20884/*
20885** Read a 64-bit variable-length integer from memory starting at p[0].
20886** Return the number of bytes read.  The value is stored in *v.
20887*/
20888SQLITE_PRIVATE u8 sqlite3GetVarint(const unsigned char *p, u64 *v){
20889  u32 a,b,s;
20890
20891  a = *p;
20892  /* a: p0 (unmasked) */
20893  if (!(a&0x80))
20894  {
20895    *v = a;
20896    return 1;
20897  }
20898
20899  p++;
20900  b = *p;
20901  /* b: p1 (unmasked) */
20902  if (!(b&0x80))
20903  {
20904    a &= 0x7f;
20905    a = a<<7;
20906    a |= b;
20907    *v = a;
20908    return 2;
20909  }
20910
20911  /* Verify that constants are precomputed correctly */
20912  assert( SLOT_2_0 == ((0x7f<<14) | (0x7f)) );
20913  assert( SLOT_4_2_0 == ((0xfU<<28) | (0x7f<<14) | (0x7f)) );
20914
20915  p++;
20916  a = a<<14;
20917  a |= *p;
20918  /* a: p0<<14 | p2 (unmasked) */
20919  if (!(a&0x80))
20920  {
20921    a &= SLOT_2_0;
20922    b &= 0x7f;
20923    b = b<<7;
20924    a |= b;
20925    *v = a;
20926    return 3;
20927  }
20928
20929  /* CSE1 from below */
20930  a &= SLOT_2_0;
20931  p++;
20932  b = b<<14;
20933  b |= *p;
20934  /* b: p1<<14 | p3 (unmasked) */
20935  if (!(b&0x80))
20936  {
20937    b &= SLOT_2_0;
20938    /* moved CSE1 up */
20939    /* a &= (0x7f<<14)|(0x7f); */
20940    a = a<<7;
20941    a |= b;
20942    *v = a;
20943    return 4;
20944  }
20945
20946  /* a: p0<<14 | p2 (masked) */
20947  /* b: p1<<14 | p3 (unmasked) */
20948  /* 1:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
20949  /* moved CSE1 up */
20950  /* a &= (0x7f<<14)|(0x7f); */
20951  b &= SLOT_2_0;
20952  s = a;
20953  /* s: p0<<14 | p2 (masked) */
20954
20955  p++;
20956  a = a<<14;
20957  a |= *p;
20958  /* a: p0<<28 | p2<<14 | p4 (unmasked) */
20959  if (!(a&0x80))
20960  {
20961    /* we can skip these cause they were (effectively) done above in calc'ing s */
20962    /* a &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
20963    /* b &= (0x7f<<14)|(0x7f); */
20964    b = b<<7;
20965    a |= b;
20966    s = s>>18;
20967    *v = ((u64)s)<<32 | a;
20968    return 5;
20969  }
20970
20971  /* 2:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
20972  s = s<<7;
20973  s |= b;
20974  /* s: p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
20975
20976  p++;
20977  b = b<<14;
20978  b |= *p;
20979  /* b: p1<<28 | p3<<14 | p5 (unmasked) */
20980  if (!(b&0x80))
20981  {
20982    /* we can skip this cause it was (effectively) done above in calc'ing s */
20983    /* b &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
20984    a &= SLOT_2_0;
20985    a = a<<7;
20986    a |= b;
20987    s = s>>18;
20988    *v = ((u64)s)<<32 | a;
20989    return 6;
20990  }
20991
20992  p++;
20993  a = a<<14;
20994  a |= *p;
20995  /* a: p2<<28 | p4<<14 | p6 (unmasked) */
20996  if (!(a&0x80))
20997  {
20998    a &= SLOT_4_2_0;
20999    b &= SLOT_2_0;
21000    b = b<<7;
21001    a |= b;
21002    s = s>>11;
21003    *v = ((u64)s)<<32 | a;
21004    return 7;
21005  }
21006
21007  /* CSE2 from below */
21008  a &= SLOT_2_0;
21009  p++;
21010  b = b<<14;
21011  b |= *p;
21012  /* b: p3<<28 | p5<<14 | p7 (unmasked) */
21013  if (!(b&0x80))
21014  {
21015    b &= SLOT_4_2_0;
21016    /* moved CSE2 up */
21017    /* a &= (0x7f<<14)|(0x7f); */
21018    a = a<<7;
21019    a |= b;
21020    s = s>>4;
21021    *v = ((u64)s)<<32 | a;
21022    return 8;
21023  }
21024
21025  p++;
21026  a = a<<15;
21027  a |= *p;
21028  /* a: p4<<29 | p6<<15 | p8 (unmasked) */
21029
21030  /* moved CSE2 up */
21031  /* a &= (0x7f<<29)|(0x7f<<15)|(0xff); */
21032  b &= SLOT_2_0;
21033  b = b<<8;
21034  a |= b;
21035
21036  s = s<<4;
21037  b = p[-4];
21038  b &= 0x7f;
21039  b = b>>3;
21040  s |= b;
21041
21042  *v = ((u64)s)<<32 | a;
21043
21044  return 9;
21045}
21046
21047/*
21048** Read a 32-bit variable-length integer from memory starting at p[0].
21049** Return the number of bytes read.  The value is stored in *v.
21050**
21051** If the varint stored in p[0] is larger than can fit in a 32-bit unsigned
21052** integer, then set *v to 0xffffffff.
21053**
21054** A MACRO version, getVarint32, is provided which inlines the
21055** single-byte case.  All code should use the MACRO version as
21056** this function assumes the single-byte case has already been handled.
21057*/
21058SQLITE_PRIVATE u8 sqlite3GetVarint32(const unsigned char *p, u32 *v){
21059  u32 a,b;
21060
21061  /* The 1-byte case.  Overwhelmingly the most common.  Handled inline
21062  ** by the getVarin32() macro */
21063  a = *p;
21064  /* a: p0 (unmasked) */
21065#ifndef getVarint32
21066  if (!(a&0x80))
21067  {
21068    /* Values between 0 and 127 */
21069    *v = a;
21070    return 1;
21071  }
21072#endif
21073
21074  /* The 2-byte case */
21075  p++;
21076  b = *p;
21077  /* b: p1 (unmasked) */
21078  if (!(b&0x80))
21079  {
21080    /* Values between 128 and 16383 */
21081    a &= 0x7f;
21082    a = a<<7;
21083    *v = a | b;
21084    return 2;
21085  }
21086
21087  /* The 3-byte case */
21088  p++;
21089  a = a<<14;
21090  a |= *p;
21091  /* a: p0<<14 | p2 (unmasked) */
21092  if (!(a&0x80))
21093  {
21094    /* Values between 16384 and 2097151 */
21095    a &= (0x7f<<14)|(0x7f);
21096    b &= 0x7f;
21097    b = b<<7;
21098    *v = a | b;
21099    return 3;
21100  }
21101
21102  /* A 32-bit varint is used to store size information in btrees.
21103  ** Objects are rarely larger than 2MiB limit of a 3-byte varint.
21104  ** A 3-byte varint is sufficient, for example, to record the size
21105  ** of a 1048569-byte BLOB or string.
21106  **
21107  ** We only unroll the first 1-, 2-, and 3- byte cases.  The very
21108  ** rare larger cases can be handled by the slower 64-bit varint
21109  ** routine.
21110  */
21111#if 1
21112  {
21113    u64 v64;
21114    u8 n;
21115
21116    p -= 2;
21117    n = sqlite3GetVarint(p, &v64);
21118    assert( n>3 && n<=9 );
21119    if( (v64 & SQLITE_MAX_U32)!=v64 ){
21120      *v = 0xffffffff;
21121    }else{
21122      *v = (u32)v64;
21123    }
21124    return n;
21125  }
21126
21127#else
21128  /* For following code (kept for historical record only) shows an
21129  ** unrolling for the 3- and 4-byte varint cases.  This code is
21130  ** slightly faster, but it is also larger and much harder to test.
21131  */
21132  p++;
21133  b = b<<14;
21134  b |= *p;
21135  /* b: p1<<14 | p3 (unmasked) */
21136  if (!(b&0x80))
21137  {
21138    /* Values between 2097152 and 268435455 */
21139    b &= (0x7f<<14)|(0x7f);
21140    a &= (0x7f<<14)|(0x7f);
21141    a = a<<7;
21142    *v = a | b;
21143    return 4;
21144  }
21145
21146  p++;
21147  a = a<<14;
21148  a |= *p;
21149  /* a: p0<<28 | p2<<14 | p4 (unmasked) */
21150  if (!(a&0x80))
21151  {
21152    /* Values  between 268435456 and 34359738367 */
21153    a &= SLOT_4_2_0;
21154    b &= SLOT_4_2_0;
21155    b = b<<7;
21156    *v = a | b;
21157    return 5;
21158  }
21159
21160  /* We can only reach this point when reading a corrupt database
21161  ** file.  In that case we are not in any hurry.  Use the (relatively
21162  ** slow) general-purpose sqlite3GetVarint() routine to extract the
21163  ** value. */
21164  {
21165    u64 v64;
21166    u8 n;
21167
21168    p -= 4;
21169    n = sqlite3GetVarint(p, &v64);
21170    assert( n>5 && n<=9 );
21171    *v = (u32)v64;
21172    return n;
21173  }
21174#endif
21175}
21176
21177/*
21178** Return the number of bytes that will be needed to store the given
21179** 64-bit integer.
21180*/
21181SQLITE_PRIVATE int sqlite3VarintLen(u64 v){
21182  int i = 0;
21183  do{
21184    i++;
21185    v >>= 7;
21186  }while( v!=0 && ALWAYS(i<9) );
21187  return i;
21188}
21189
21190
21191/*
21192** Read or write a four-byte big-endian integer value.
21193*/
21194SQLITE_PRIVATE u32 sqlite3Get4byte(const u8 *p){
21195  return (p[0]<<24) | (p[1]<<16) | (p[2]<<8) | p[3];
21196}
21197SQLITE_PRIVATE void sqlite3Put4byte(unsigned char *p, u32 v){
21198  p[0] = (u8)(v>>24);
21199  p[1] = (u8)(v>>16);
21200  p[2] = (u8)(v>>8);
21201  p[3] = (u8)v;
21202}
21203
21204
21205
21206#if !defined(SQLITE_OMIT_BLOB_LITERAL) || defined(SQLITE_HAS_CODEC)
21207/*
21208** Translate a single byte of Hex into an integer.
21209** This routine only works if h really is a valid hexadecimal
21210** character:  0..9a..fA..F
21211*/
21212static u8 hexToInt(int h){
21213  assert( (h>='0' && h<='9') ||  (h>='a' && h<='f') ||  (h>='A' && h<='F') );
21214#ifdef SQLITE_ASCII
21215  h += 9*(1&(h>>6));
21216#endif
21217#ifdef SQLITE_EBCDIC
21218  h += 9*(1&~(h>>4));
21219#endif
21220  return (u8)(h & 0xf);
21221}
21222#endif /* !SQLITE_OMIT_BLOB_LITERAL || SQLITE_HAS_CODEC */
21223
21224#if !defined(SQLITE_OMIT_BLOB_LITERAL) || defined(SQLITE_HAS_CODEC)
21225/*
21226** Convert a BLOB literal of the form "x'hhhhhh'" into its binary
21227** value.  Return a pointer to its binary value.  Space to hold the
21228** binary value has been obtained from malloc and must be freed by
21229** the calling routine.
21230*/
21231SQLITE_PRIVATE void *sqlite3HexToBlob(sqlite3 *db, const char *z, int n){
21232  char *zBlob;
21233  int i;
21234
21235  zBlob = (char *)sqlite3DbMallocRaw(db, n/2 + 1);
21236  n--;
21237  if( zBlob ){
21238    for(i=0; i<n; i+=2){
21239      zBlob[i/2] = (hexToInt(z[i])<<4) | hexToInt(z[i+1]);
21240    }
21241    zBlob[i/2] = 0;
21242  }
21243  return zBlob;
21244}
21245#endif /* !SQLITE_OMIT_BLOB_LITERAL || SQLITE_HAS_CODEC */
21246
21247/*
21248** Log an error that is an API call on a connection pointer that should
21249** not have been used.  The "type" of connection pointer is given as the
21250** argument.  The zType is a word like "NULL" or "closed" or "invalid".
21251*/
21252static void logBadConnection(const char *zType){
21253  sqlite3_log(SQLITE_MISUSE,
21254     "API call with %s database connection pointer",
21255     zType
21256  );
21257}
21258
21259/*
21260** Check to make sure we have a valid db pointer.  This test is not
21261** foolproof but it does provide some measure of protection against
21262** misuse of the interface such as passing in db pointers that are
21263** NULL or which have been previously closed.  If this routine returns
21264** 1 it means that the db pointer is valid and 0 if it should not be
21265** dereferenced for any reason.  The calling function should invoke
21266** SQLITE_MISUSE immediately.
21267**
21268** sqlite3SafetyCheckOk() requires that the db pointer be valid for
21269** use.  sqlite3SafetyCheckSickOrOk() allows a db pointer that failed to
21270** open properly and is not fit for general use but which can be
21271** used as an argument to sqlite3_errmsg() or sqlite3_close().
21272*/
21273SQLITE_PRIVATE int sqlite3SafetyCheckOk(sqlite3 *db){
21274  u32 magic;
21275  if( db==0 ){
21276    logBadConnection("NULL");
21277    return 0;
21278  }
21279  magic = db->magic;
21280  if( magic!=SQLITE_MAGIC_OPEN ){
21281    if( sqlite3SafetyCheckSickOrOk(db) ){
21282      testcase( sqlite3GlobalConfig.xLog!=0 );
21283      logBadConnection("unopened");
21284    }
21285    return 0;
21286  }else{
21287    return 1;
21288  }
21289}
21290SQLITE_PRIVATE int sqlite3SafetyCheckSickOrOk(sqlite3 *db){
21291  u32 magic;
21292  magic = db->magic;
21293  if( magic!=SQLITE_MAGIC_SICK &&
21294      magic!=SQLITE_MAGIC_OPEN &&
21295      magic!=SQLITE_MAGIC_BUSY ){
21296    testcase( sqlite3GlobalConfig.xLog!=0 );
21297    logBadConnection("invalid");
21298    return 0;
21299  }else{
21300    return 1;
21301  }
21302}
21303
21304/*
21305** Attempt to add, substract, or multiply the 64-bit signed value iB against
21306** the other 64-bit signed integer at *pA and store the result in *pA.
21307** Return 0 on success.  Or if the operation would have resulted in an
21308** overflow, leave *pA unchanged and return 1.
21309*/
21310SQLITE_PRIVATE int sqlite3AddInt64(i64 *pA, i64 iB){
21311  i64 iA = *pA;
21312  testcase( iA==0 ); testcase( iA==1 );
21313  testcase( iB==-1 ); testcase( iB==0 );
21314  if( iB>=0 ){
21315    testcase( iA>0 && LARGEST_INT64 - iA == iB );
21316    testcase( iA>0 && LARGEST_INT64 - iA == iB - 1 );
21317    if( iA>0 && LARGEST_INT64 - iA < iB ) return 1;
21318    *pA += iB;
21319  }else{
21320    testcase( iA<0 && -(iA + LARGEST_INT64) == iB + 1 );
21321    testcase( iA<0 && -(iA + LARGEST_INT64) == iB + 2 );
21322    if( iA<0 && -(iA + LARGEST_INT64) > iB + 1 ) return 1;
21323    *pA += iB;
21324  }
21325  return 0;
21326}
21327SQLITE_PRIVATE int sqlite3SubInt64(i64 *pA, i64 iB){
21328  testcase( iB==SMALLEST_INT64+1 );
21329  if( iB==SMALLEST_INT64 ){
21330    testcase( (*pA)==(-1) ); testcase( (*pA)==0 );
21331    if( (*pA)>=0 ) return 1;
21332    *pA -= iB;
21333    return 0;
21334  }else{
21335    return sqlite3AddInt64(pA, -iB);
21336  }
21337}
21338#define TWOPOWER32 (((i64)1)<<32)
21339#define TWOPOWER31 (((i64)1)<<31)
21340SQLITE_PRIVATE int sqlite3MulInt64(i64 *pA, i64 iB){
21341  i64 iA = *pA;
21342  i64 iA1, iA0, iB1, iB0, r;
21343
21344  iA1 = iA/TWOPOWER32;
21345  iA0 = iA % TWOPOWER32;
21346  iB1 = iB/TWOPOWER32;
21347  iB0 = iB % TWOPOWER32;
21348  if( iA1*iB1 != 0 ) return 1;
21349  assert( iA1*iB0==0 || iA0*iB1==0 );
21350  r = iA1*iB0 + iA0*iB1;
21351  testcase( r==(-TWOPOWER31)-1 );
21352  testcase( r==(-TWOPOWER31) );
21353  testcase( r==TWOPOWER31 );
21354  testcase( r==TWOPOWER31-1 );
21355  if( r<(-TWOPOWER31) || r>=TWOPOWER31 ) return 1;
21356  r *= TWOPOWER32;
21357  if( sqlite3AddInt64(&r, iA0*iB0) ) return 1;
21358  *pA = r;
21359  return 0;
21360}
21361
21362/*
21363** Compute the absolute value of a 32-bit signed integer, of possible.  Or
21364** if the integer has a value of -2147483648, return +2147483647
21365*/
21366SQLITE_PRIVATE int sqlite3AbsInt32(int x){
21367  if( x>=0 ) return x;
21368  if( x==(int)0x80000000 ) return 0x7fffffff;
21369  return -x;
21370}
21371
21372/************** End of util.c ************************************************/
21373/************** Begin file hash.c ********************************************/
21374/*
21375** 2001 September 22
21376**
21377** The author disclaims copyright to this source code.  In place of
21378** a legal notice, here is a blessing:
21379**
21380**    May you do good and not evil.
21381**    May you find forgiveness for yourself and forgive others.
21382**    May you share freely, never taking more than you give.
21383**
21384*************************************************************************
21385** This is the implementation of generic hash-tables
21386** used in SQLite.
21387*/
21388
21389/* Turn bulk memory into a hash table object by initializing the
21390** fields of the Hash structure.
21391**
21392** "pNew" is a pointer to the hash table that is to be initialized.
21393*/
21394SQLITE_PRIVATE void sqlite3HashInit(Hash *pNew){
21395  assert( pNew!=0 );
21396  pNew->first = 0;
21397  pNew->count = 0;
21398  pNew->htsize = 0;
21399  pNew->ht = 0;
21400}
21401
21402/* Remove all entries from a hash table.  Reclaim all memory.
21403** Call this routine to delete a hash table or to reset a hash table
21404** to the empty state.
21405*/
21406SQLITE_PRIVATE void sqlite3HashClear(Hash *pH){
21407  HashElem *elem;         /* For looping over all elements of the table */
21408
21409  assert( pH!=0 );
21410  elem = pH->first;
21411  pH->first = 0;
21412  sqlite3_free(pH->ht);
21413  pH->ht = 0;
21414  pH->htsize = 0;
21415  while( elem ){
21416    HashElem *next_elem = elem->next;
21417    sqlite3_free(elem);
21418    elem = next_elem;
21419  }
21420  pH->count = 0;
21421}
21422
21423/*
21424** The hashing function.
21425*/
21426static unsigned int strHash(const char *z, int nKey){
21427  int h = 0;
21428  assert( nKey>=0 );
21429  while( nKey > 0  ){
21430    h = (h<<3) ^ h ^ sqlite3UpperToLower[(unsigned char)*z++];
21431    nKey--;
21432  }
21433  return h;
21434}
21435
21436
21437/* Link pNew element into the hash table pH.  If pEntry!=0 then also
21438** insert pNew into the pEntry hash bucket.
21439*/
21440static void insertElement(
21441  Hash *pH,              /* The complete hash table */
21442  struct _ht *pEntry,    /* The entry into which pNew is inserted */
21443  HashElem *pNew         /* The element to be inserted */
21444){
21445  HashElem *pHead;       /* First element already in pEntry */
21446  if( pEntry ){
21447    pHead = pEntry->count ? pEntry->chain : 0;
21448    pEntry->count++;
21449    pEntry->chain = pNew;
21450  }else{
21451    pHead = 0;
21452  }
21453  if( pHead ){
21454    pNew->next = pHead;
21455    pNew->prev = pHead->prev;
21456    if( pHead->prev ){ pHead->prev->next = pNew; }
21457    else             { pH->first = pNew; }
21458    pHead->prev = pNew;
21459  }else{
21460    pNew->next = pH->first;
21461    if( pH->first ){ pH->first->prev = pNew; }
21462    pNew->prev = 0;
21463    pH->first = pNew;
21464  }
21465}
21466
21467
21468/* Resize the hash table so that it cantains "new_size" buckets.
21469**
21470** The hash table might fail to resize if sqlite3_malloc() fails or
21471** if the new size is the same as the prior size.
21472** Return TRUE if the resize occurs and false if not.
21473*/
21474static int rehash(Hash *pH, unsigned int new_size){
21475  struct _ht *new_ht;            /* The new hash table */
21476  HashElem *elem, *next_elem;    /* For looping over existing elements */
21477
21478#if SQLITE_MALLOC_SOFT_LIMIT>0
21479  if( new_size*sizeof(struct _ht)>SQLITE_MALLOC_SOFT_LIMIT ){
21480    new_size = SQLITE_MALLOC_SOFT_LIMIT/sizeof(struct _ht);
21481  }
21482  if( new_size==pH->htsize ) return 0;
21483#endif
21484
21485  /* The inability to allocates space for a larger hash table is
21486  ** a performance hit but it is not a fatal error.  So mark the
21487  ** allocation as a benign.
21488  */
21489  sqlite3BeginBenignMalloc();
21490  new_ht = (struct _ht *)sqlite3Malloc( new_size*sizeof(struct _ht) );
21491  sqlite3EndBenignMalloc();
21492
21493  if( new_ht==0 ) return 0;
21494  sqlite3_free(pH->ht);
21495  pH->ht = new_ht;
21496  pH->htsize = new_size = sqlite3MallocSize(new_ht)/sizeof(struct _ht);
21497  memset(new_ht, 0, new_size*sizeof(struct _ht));
21498  for(elem=pH->first, pH->first=0; elem; elem = next_elem){
21499    unsigned int h = strHash(elem->pKey, elem->nKey) % new_size;
21500    next_elem = elem->next;
21501    insertElement(pH, &new_ht[h], elem);
21502  }
21503  return 1;
21504}
21505
21506/* This function (for internal use only) locates an element in an
21507** hash table that matches the given key.  The hash for this key has
21508** already been computed and is passed as the 4th parameter.
21509*/
21510static HashElem *findElementGivenHash(
21511  const Hash *pH,     /* The pH to be searched */
21512  const char *pKey,   /* The key we are searching for */
21513  int nKey,           /* Bytes in key (not counting zero terminator) */
21514  unsigned int h      /* The hash for this key. */
21515){
21516  HashElem *elem;                /* Used to loop thru the element list */
21517  int count;                     /* Number of elements left to test */
21518
21519  if( pH->ht ){
21520    struct _ht *pEntry = &pH->ht[h];
21521    elem = pEntry->chain;
21522    count = pEntry->count;
21523  }else{
21524    elem = pH->first;
21525    count = pH->count;
21526  }
21527  while( count-- && ALWAYS(elem) ){
21528    if( elem->nKey==nKey && sqlite3StrNICmp(elem->pKey,pKey,nKey)==0 ){
21529      return elem;
21530    }
21531    elem = elem->next;
21532  }
21533  return 0;
21534}
21535
21536/* Remove a single entry from the hash table given a pointer to that
21537** element and a hash on the element's key.
21538*/
21539static void removeElementGivenHash(
21540  Hash *pH,         /* The pH containing "elem" */
21541  HashElem* elem,   /* The element to be removed from the pH */
21542  unsigned int h    /* Hash value for the element */
21543){
21544  struct _ht *pEntry;
21545  if( elem->prev ){
21546    elem->prev->next = elem->next;
21547  }else{
21548    pH->first = elem->next;
21549  }
21550  if( elem->next ){
21551    elem->next->prev = elem->prev;
21552  }
21553  if( pH->ht ){
21554    pEntry = &pH->ht[h];
21555    if( pEntry->chain==elem ){
21556      pEntry->chain = elem->next;
21557    }
21558    pEntry->count--;
21559    assert( pEntry->count>=0 );
21560  }
21561  sqlite3_free( elem );
21562  pH->count--;
21563  if( pH->count<=0 ){
21564    assert( pH->first==0 );
21565    assert( pH->count==0 );
21566    sqlite3HashClear(pH);
21567  }
21568}
21569
21570/* Attempt to locate an element of the hash table pH with a key
21571** that matches pKey,nKey.  Return the data for this element if it is
21572** found, or NULL if there is no match.
21573*/
21574SQLITE_PRIVATE void *sqlite3HashFind(const Hash *pH, const char *pKey, int nKey){
21575  HashElem *elem;    /* The element that matches key */
21576  unsigned int h;    /* A hash on key */
21577
21578  assert( pH!=0 );
21579  assert( pKey!=0 );
21580  assert( nKey>=0 );
21581  if( pH->ht ){
21582    h = strHash(pKey, nKey) % pH->htsize;
21583  }else{
21584    h = 0;
21585  }
21586  elem = findElementGivenHash(pH, pKey, nKey, h);
21587  return elem ? elem->data : 0;
21588}
21589
21590/* Insert an element into the hash table pH.  The key is pKey,nKey
21591** and the data is "data".
21592**
21593** If no element exists with a matching key, then a new
21594** element is created and NULL is returned.
21595**
21596** If another element already exists with the same key, then the
21597** new data replaces the old data and the old data is returned.
21598** The key is not copied in this instance.  If a malloc fails, then
21599** the new data is returned and the hash table is unchanged.
21600**
21601** If the "data" parameter to this function is NULL, then the
21602** element corresponding to "key" is removed from the hash table.
21603*/
21604SQLITE_PRIVATE void *sqlite3HashInsert(Hash *pH, const char *pKey, int nKey, void *data){
21605  unsigned int h;       /* the hash of the key modulo hash table size */
21606  HashElem *elem;       /* Used to loop thru the element list */
21607  HashElem *new_elem;   /* New element added to the pH */
21608
21609  assert( pH!=0 );
21610  assert( pKey!=0 );
21611  assert( nKey>=0 );
21612  if( pH->htsize ){
21613    h = strHash(pKey, nKey) % pH->htsize;
21614  }else{
21615    h = 0;
21616  }
21617  elem = findElementGivenHash(pH,pKey,nKey,h);
21618  if( elem ){
21619    void *old_data = elem->data;
21620    if( data==0 ){
21621      removeElementGivenHash(pH,elem,h);
21622    }else{
21623      elem->data = data;
21624      elem->pKey = pKey;
21625      assert(nKey==elem->nKey);
21626    }
21627    return old_data;
21628  }
21629  if( data==0 ) return 0;
21630  new_elem = (HashElem*)sqlite3Malloc( sizeof(HashElem) );
21631  if( new_elem==0 ) return data;
21632  new_elem->pKey = pKey;
21633  new_elem->nKey = nKey;
21634  new_elem->data = data;
21635  pH->count++;
21636  if( pH->count>=10 && pH->count > 2*pH->htsize ){
21637    if( rehash(pH, pH->count*2) ){
21638      assert( pH->htsize>0 );
21639      h = strHash(pKey, nKey) % pH->htsize;
21640    }
21641  }
21642  if( pH->ht ){
21643    insertElement(pH, &pH->ht[h], new_elem);
21644  }else{
21645    insertElement(pH, 0, new_elem);
21646  }
21647  return 0;
21648}
21649
21650/************** End of hash.c ************************************************/
21651/************** Begin file opcodes.c *****************************************/
21652/* Automatically generated.  Do not edit */
21653/* See the mkopcodec.awk script for details. */
21654#if !defined(SQLITE_OMIT_EXPLAIN) || !defined(NDEBUG) || defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
21655SQLITE_PRIVATE const char *sqlite3OpcodeName(int i){
21656 static const char *const azName[] = { "?",
21657     /*   1 */ "Goto",
21658     /*   2 */ "Gosub",
21659     /*   3 */ "Return",
21660     /*   4 */ "Yield",
21661     /*   5 */ "HaltIfNull",
21662     /*   6 */ "Halt",
21663     /*   7 */ "Integer",
21664     /*   8 */ "Int64",
21665     /*   9 */ "String",
21666     /*  10 */ "Null",
21667     /*  11 */ "Blob",
21668     /*  12 */ "Variable",
21669     /*  13 */ "Move",
21670     /*  14 */ "Copy",
21671     /*  15 */ "SCopy",
21672     /*  16 */ "ResultRow",
21673     /*  17 */ "CollSeq",
21674     /*  18 */ "Function",
21675     /*  19 */ "Not",
21676     /*  20 */ "AddImm",
21677     /*  21 */ "MustBeInt",
21678     /*  22 */ "RealAffinity",
21679     /*  23 */ "Permutation",
21680     /*  24 */ "Compare",
21681     /*  25 */ "Jump",
21682     /*  26 */ "If",
21683     /*  27 */ "IfNot",
21684     /*  28 */ "Column",
21685     /*  29 */ "Affinity",
21686     /*  30 */ "MakeRecord",
21687     /*  31 */ "Count",
21688     /*  32 */ "Savepoint",
21689     /*  33 */ "AutoCommit",
21690     /*  34 */ "Transaction",
21691     /*  35 */ "ReadCookie",
21692     /*  36 */ "SetCookie",
21693     /*  37 */ "VerifyCookie",
21694     /*  38 */ "OpenRead",
21695     /*  39 */ "OpenWrite",
21696     /*  40 */ "OpenAutoindex",
21697     /*  41 */ "OpenEphemeral",
21698     /*  42 */ "OpenPseudo",
21699     /*  43 */ "Close",
21700     /*  44 */ "SeekLt",
21701     /*  45 */ "SeekLe",
21702     /*  46 */ "SeekGe",
21703     /*  47 */ "SeekGt",
21704     /*  48 */ "Seek",
21705     /*  49 */ "NotFound",
21706     /*  50 */ "Found",
21707     /*  51 */ "IsUnique",
21708     /*  52 */ "NotExists",
21709     /*  53 */ "Sequence",
21710     /*  54 */ "NewRowid",
21711     /*  55 */ "Insert",
21712     /*  56 */ "InsertInt",
21713     /*  57 */ "Delete",
21714     /*  58 */ "ResetCount",
21715     /*  59 */ "RowKey",
21716     /*  60 */ "RowData",
21717     /*  61 */ "Rowid",
21718     /*  62 */ "NullRow",
21719     /*  63 */ "Last",
21720     /*  64 */ "Sort",
21721     /*  65 */ "Rewind",
21722     /*  66 */ "Prev",
21723     /*  67 */ "Next",
21724     /*  68 */ "Or",
21725     /*  69 */ "And",
21726     /*  70 */ "IdxInsert",
21727     /*  71 */ "IdxDelete",
21728     /*  72 */ "IdxRowid",
21729     /*  73 */ "IsNull",
21730     /*  74 */ "NotNull",
21731     /*  75 */ "Ne",
21732     /*  76 */ "Eq",
21733     /*  77 */ "Gt",
21734     /*  78 */ "Le",
21735     /*  79 */ "Lt",
21736     /*  80 */ "Ge",
21737     /*  81 */ "IdxLT",
21738     /*  82 */ "BitAnd",
21739     /*  83 */ "BitOr",
21740     /*  84 */ "ShiftLeft",
21741     /*  85 */ "ShiftRight",
21742     /*  86 */ "Add",
21743     /*  87 */ "Subtract",
21744     /*  88 */ "Multiply",
21745     /*  89 */ "Divide",
21746     /*  90 */ "Remainder",
21747     /*  91 */ "Concat",
21748     /*  92 */ "IdxGE",
21749     /*  93 */ "BitNot",
21750     /*  94 */ "String8",
21751     /*  95 */ "Destroy",
21752     /*  96 */ "Clear",
21753     /*  97 */ "CreateIndex",
21754     /*  98 */ "CreateTable",
21755     /*  99 */ "ParseSchema",
21756     /* 100 */ "LoadAnalysis",
21757     /* 101 */ "DropTable",
21758     /* 102 */ "DropIndex",
21759     /* 103 */ "DropTrigger",
21760     /* 104 */ "IntegrityCk",
21761     /* 105 */ "RowSetAdd",
21762     /* 106 */ "RowSetRead",
21763     /* 107 */ "RowSetTest",
21764     /* 108 */ "Program",
21765     /* 109 */ "Param",
21766     /* 110 */ "FkCounter",
21767     /* 111 */ "FkIfZero",
21768     /* 112 */ "MemMax",
21769     /* 113 */ "IfPos",
21770     /* 114 */ "IfNeg",
21771     /* 115 */ "IfZero",
21772     /* 116 */ "AggStep",
21773     /* 117 */ "AggFinal",
21774     /* 118 */ "Checkpoint",
21775     /* 119 */ "JournalMode",
21776     /* 120 */ "Vacuum",
21777     /* 121 */ "IncrVacuum",
21778     /* 122 */ "Expire",
21779     /* 123 */ "TableLock",
21780     /* 124 */ "VBegin",
21781     /* 125 */ "VCreate",
21782     /* 126 */ "VDestroy",
21783     /* 127 */ "VOpen",
21784     /* 128 */ "VFilter",
21785     /* 129 */ "VColumn",
21786     /* 130 */ "Real",
21787     /* 131 */ "VNext",
21788     /* 132 */ "VRename",
21789     /* 133 */ "VUpdate",
21790     /* 134 */ "Pagecount",
21791     /* 135 */ "MaxPgcnt",
21792     /* 136 */ "Trace",
21793     /* 137 */ "Noop",
21794     /* 138 */ "Explain",
21795     /* 139 */ "NotUsed_139",
21796     /* 140 */ "NotUsed_140",
21797     /* 141 */ "ToText",
21798     /* 142 */ "ToBlob",
21799     /* 143 */ "ToNumeric",
21800     /* 144 */ "ToInt",
21801     /* 145 */ "ToReal",
21802  };
21803  return azName[i];
21804}
21805#endif
21806
21807/************** End of opcodes.c *********************************************/
21808/************** Begin file os_os2.c ******************************************/
21809/*
21810** 2006 Feb 14
21811**
21812** The author disclaims copyright to this source code.  In place of
21813** a legal notice, here is a blessing:
21814**
21815**    May you do good and not evil.
21816**    May you find forgiveness for yourself and forgive others.
21817**    May you share freely, never taking more than you give.
21818**
21819******************************************************************************
21820**
21821** This file contains code that is specific to OS/2.
21822*/
21823
21824
21825#if SQLITE_OS_OS2
21826
21827/*
21828** A Note About Memory Allocation:
21829**
21830** This driver uses malloc()/free() directly rather than going through
21831** the SQLite-wrappers sqlite3_malloc()/sqlite3_free().  Those wrappers
21832** are designed for use on embedded systems where memory is scarce and
21833** malloc failures happen frequently.  OS/2 does not typically run on
21834** embedded systems, and when it does the developers normally have bigger
21835** problems to worry about than running out of memory.  So there is not
21836** a compelling need to use the wrappers.
21837**
21838** But there is a good reason to not use the wrappers.  If we use the
21839** wrappers then we will get simulated malloc() failures within this
21840** driver.  And that causes all kinds of problems for our tests.  We
21841** could enhance SQLite to deal with simulated malloc failures within
21842** the OS driver, but the code to deal with those failure would not
21843** be exercised on Linux (which does not need to malloc() in the driver)
21844** and so we would have difficulty writing coverage tests for that
21845** code.  Better to leave the code out, we think.
21846**
21847** The point of this discussion is as follows:  When creating a new
21848** OS layer for an embedded system, if you use this file as an example,
21849** avoid the use of malloc()/free().  Those routines work ok on OS/2
21850** desktops but not so well in embedded systems.
21851*/
21852
21853/*
21854** Macros used to determine whether or not to use threads.
21855*/
21856#if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE
21857# define SQLITE_OS2_THREADS 1
21858#endif
21859
21860/*
21861** Include code that is common to all os_*.c files
21862*/
21863/************** Include os_common.h in the middle of os_os2.c ****************/
21864/************** Begin file os_common.h ***************************************/
21865/*
21866** 2004 May 22
21867**
21868** The author disclaims copyright to this source code.  In place of
21869** a legal notice, here is a blessing:
21870**
21871**    May you do good and not evil.
21872**    May you find forgiveness for yourself and forgive others.
21873**    May you share freely, never taking more than you give.
21874**
21875******************************************************************************
21876**
21877** This file contains macros and a little bit of code that is common to
21878** all of the platform-specific files (os_*.c) and is #included into those
21879** files.
21880**
21881** This file should be #included by the os_*.c files only.  It is not a
21882** general purpose header file.
21883*/
21884#ifndef _OS_COMMON_H_
21885#define _OS_COMMON_H_
21886
21887/*
21888** At least two bugs have slipped in because we changed the MEMORY_DEBUG
21889** macro to SQLITE_DEBUG and some older makefiles have not yet made the
21890** switch.  The following code should catch this problem at compile-time.
21891*/
21892#ifdef MEMORY_DEBUG
21893# error "The MEMORY_DEBUG macro is obsolete.  Use SQLITE_DEBUG instead."
21894#endif
21895
21896#ifdef SQLITE_DEBUG
21897SQLITE_PRIVATE int sqlite3OSTrace = 0;
21898#define OSTRACE(X)          if( sqlite3OSTrace ) sqlite3DebugPrintf X
21899#else
21900#define OSTRACE(X)
21901#endif
21902
21903/*
21904** Macros for performance tracing.  Normally turned off.  Only works
21905** on i486 hardware.
21906*/
21907#ifdef SQLITE_PERFORMANCE_TRACE
21908
21909/*
21910** hwtime.h contains inline assembler code for implementing
21911** high-performance timing routines.
21912*/
21913/************** Include hwtime.h in the middle of os_common.h ****************/
21914/************** Begin file hwtime.h ******************************************/
21915/*
21916** 2008 May 27
21917**
21918** The author disclaims copyright to this source code.  In place of
21919** a legal notice, here is a blessing:
21920**
21921**    May you do good and not evil.
21922**    May you find forgiveness for yourself and forgive others.
21923**    May you share freely, never taking more than you give.
21924**
21925******************************************************************************
21926**
21927** This file contains inline asm code for retrieving "high-performance"
21928** counters for x86 class CPUs.
21929*/
21930#ifndef _HWTIME_H_
21931#define _HWTIME_H_
21932
21933/*
21934** The following routine only works on pentium-class (or newer) processors.
21935** It uses the RDTSC opcode to read the cycle count value out of the
21936** processor and returns that value.  This can be used for high-res
21937** profiling.
21938*/
21939#if (defined(__GNUC__) || defined(_MSC_VER)) && \
21940      (defined(i386) || defined(__i386__) || defined(_M_IX86))
21941
21942  #if defined(__GNUC__)
21943
21944  __inline__ sqlite_uint64 sqlite3Hwtime(void){
21945     unsigned int lo, hi;
21946     __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
21947     return (sqlite_uint64)hi << 32 | lo;
21948  }
21949
21950  #elif defined(_MSC_VER)
21951
21952  __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
21953     __asm {
21954        rdtsc
21955        ret       ; return value at EDX:EAX
21956     }
21957  }
21958
21959  #endif
21960
21961#elif (defined(__GNUC__) && defined(__x86_64__))
21962
21963  __inline__ sqlite_uint64 sqlite3Hwtime(void){
21964      unsigned long val;
21965      __asm__ __volatile__ ("rdtsc" : "=A" (val));
21966      return val;
21967  }
21968
21969#elif (defined(__GNUC__) && defined(__ppc__))
21970
21971  __inline__ sqlite_uint64 sqlite3Hwtime(void){
21972      unsigned long long retval;
21973      unsigned long junk;
21974      __asm__ __volatile__ ("\n\
21975          1:      mftbu   %1\n\
21976                  mftb    %L0\n\
21977                  mftbu   %0\n\
21978                  cmpw    %0,%1\n\
21979                  bne     1b"
21980                  : "=r" (retval), "=r" (junk));
21981      return retval;
21982  }
21983
21984#else
21985
21986  #error Need implementation of sqlite3Hwtime() for your platform.
21987
21988  /*
21989  ** To compile without implementing sqlite3Hwtime() for your platform,
21990  ** you can remove the above #error and use the following
21991  ** stub function.  You will lose timing support for many
21992  ** of the debugging and testing utilities, but it should at
21993  ** least compile and run.
21994  */
21995SQLITE_PRIVATE   sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
21996
21997#endif
21998
21999#endif /* !defined(_HWTIME_H_) */
22000
22001/************** End of hwtime.h **********************************************/
22002/************** Continuing where we left off in os_common.h ******************/
22003
22004static sqlite_uint64 g_start;
22005static sqlite_uint64 g_elapsed;
22006#define TIMER_START       g_start=sqlite3Hwtime()
22007#define TIMER_END         g_elapsed=sqlite3Hwtime()-g_start
22008#define TIMER_ELAPSED     g_elapsed
22009#else
22010#define TIMER_START
22011#define TIMER_END
22012#define TIMER_ELAPSED     ((sqlite_uint64)0)
22013#endif
22014
22015/*
22016** If we compile with the SQLITE_TEST macro set, then the following block
22017** of code will give us the ability to simulate a disk I/O error.  This
22018** is used for testing the I/O recovery logic.
22019*/
22020#ifdef SQLITE_TEST
22021SQLITE_API int sqlite3_io_error_hit = 0;            /* Total number of I/O Errors */
22022SQLITE_API int sqlite3_io_error_hardhit = 0;        /* Number of non-benign errors */
22023SQLITE_API int sqlite3_io_error_pending = 0;        /* Count down to first I/O error */
22024SQLITE_API int sqlite3_io_error_persist = 0;        /* True if I/O errors persist */
22025SQLITE_API int sqlite3_io_error_benign = 0;         /* True if errors are benign */
22026SQLITE_API int sqlite3_diskfull_pending = 0;
22027SQLITE_API int sqlite3_diskfull = 0;
22028#define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
22029#define SimulateIOError(CODE)  \
22030  if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
22031       || sqlite3_io_error_pending-- == 1 )  \
22032              { local_ioerr(); CODE; }
22033static void local_ioerr(){
22034  IOTRACE(("IOERR\n"));
22035  sqlite3_io_error_hit++;
22036  if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
22037}
22038#define SimulateDiskfullError(CODE) \
22039   if( sqlite3_diskfull_pending ){ \
22040     if( sqlite3_diskfull_pending == 1 ){ \
22041       local_ioerr(); \
22042       sqlite3_diskfull = 1; \
22043       sqlite3_io_error_hit = 1; \
22044       CODE; \
22045     }else{ \
22046       sqlite3_diskfull_pending--; \
22047     } \
22048   }
22049#else
22050#define SimulateIOErrorBenign(X)
22051#define SimulateIOError(A)
22052#define SimulateDiskfullError(A)
22053#endif
22054
22055/*
22056** When testing, keep a count of the number of open files.
22057*/
22058#ifdef SQLITE_TEST
22059SQLITE_API int sqlite3_open_file_count = 0;
22060#define OpenCounter(X)  sqlite3_open_file_count+=(X)
22061#else
22062#define OpenCounter(X)
22063#endif
22064
22065#endif /* !defined(_OS_COMMON_H_) */
22066
22067/************** End of os_common.h *******************************************/
22068/************** Continuing where we left off in os_os2.c *********************/
22069
22070/* Forward references */
22071typedef struct os2File os2File;         /* The file structure */
22072typedef struct os2ShmNode os2ShmNode;   /* A shared descritive memory node */
22073typedef struct os2ShmLink os2ShmLink;   /* A connection to shared-memory */
22074
22075/*
22076** The os2File structure is subclass of sqlite3_file specific for the OS/2
22077** protability layer.
22078*/
22079struct os2File {
22080  const sqlite3_io_methods *pMethod;  /* Always the first entry */
22081  HFILE h;                  /* Handle for accessing the file */
22082  int flags;                /* Flags provided to os2Open() */
22083  int locktype;             /* Type of lock currently held on this file */
22084  int szChunk;              /* Chunk size configured by FCNTL_CHUNK_SIZE */
22085  char *zFullPathCp;        /* Full path name of this file */
22086  os2ShmLink *pShmLink;     /* Instance of shared memory on this file */
22087};
22088
22089#define LOCK_TIMEOUT 10L /* the default locking timeout */
22090
22091/*
22092** Missing from some versions of the OS/2 toolkit -
22093** used to allocate from high memory if possible
22094*/
22095#ifndef OBJ_ANY
22096# define OBJ_ANY 0x00000400
22097#endif
22098
22099/*****************************************************************************
22100** The next group of routines implement the I/O methods specified
22101** by the sqlite3_io_methods object.
22102******************************************************************************/
22103
22104/*
22105** Close a file.
22106*/
22107static int os2Close( sqlite3_file *id ){
22108  APIRET rc;
22109  os2File *pFile = (os2File*)id;
22110
22111  assert( id!=0 );
22112  OSTRACE(( "CLOSE %d (%s)\n", pFile->h, pFile->zFullPathCp ));
22113
22114  rc = DosClose( pFile->h );
22115
22116  if( pFile->flags & SQLITE_OPEN_DELETEONCLOSE )
22117    DosForceDelete( (PSZ)pFile->zFullPathCp );
22118
22119  free( pFile->zFullPathCp );
22120  pFile->zFullPathCp = NULL;
22121  pFile->locktype = NO_LOCK;
22122  pFile->h = (HFILE)-1;
22123  pFile->flags = 0;
22124
22125  OpenCounter( -1 );
22126  return rc == NO_ERROR ? SQLITE_OK : SQLITE_IOERR;
22127}
22128
22129/*
22130** Read data from a file into a buffer.  Return SQLITE_OK if all
22131** bytes were read successfully and SQLITE_IOERR if anything goes
22132** wrong.
22133*/
22134static int os2Read(
22135  sqlite3_file *id,               /* File to read from */
22136  void *pBuf,                     /* Write content into this buffer */
22137  int amt,                        /* Number of bytes to read */
22138  sqlite3_int64 offset            /* Begin reading at this offset */
22139){
22140  ULONG fileLocation = 0L;
22141  ULONG got;
22142  os2File *pFile = (os2File*)id;
22143  assert( id!=0 );
22144  SimulateIOError( return SQLITE_IOERR_READ );
22145  OSTRACE(( "READ %d lock=%d\n", pFile->h, pFile->locktype ));
22146  if( DosSetFilePtr(pFile->h, offset, FILE_BEGIN, &fileLocation) != NO_ERROR ){
22147    return SQLITE_IOERR;
22148  }
22149  if( DosRead( pFile->h, pBuf, amt, &got ) != NO_ERROR ){
22150    return SQLITE_IOERR_READ;
22151  }
22152  if( got == (ULONG)amt )
22153    return SQLITE_OK;
22154  else {
22155    /* Unread portions of the input buffer must be zero-filled */
22156    memset(&((char*)pBuf)[got], 0, amt-got);
22157    return SQLITE_IOERR_SHORT_READ;
22158  }
22159}
22160
22161/*
22162** Write data from a buffer into a file.  Return SQLITE_OK on success
22163** or some other error code on failure.
22164*/
22165static int os2Write(
22166  sqlite3_file *id,               /* File to write into */
22167  const void *pBuf,               /* The bytes to be written */
22168  int amt,                        /* Number of bytes to write */
22169  sqlite3_int64 offset            /* Offset into the file to begin writing at */
22170){
22171  ULONG fileLocation = 0L;
22172  APIRET rc = NO_ERROR;
22173  ULONG wrote;
22174  os2File *pFile = (os2File*)id;
22175  assert( id!=0 );
22176  SimulateIOError( return SQLITE_IOERR_WRITE );
22177  SimulateDiskfullError( return SQLITE_FULL );
22178  OSTRACE(( "WRITE %d lock=%d\n", pFile->h, pFile->locktype ));
22179  if( DosSetFilePtr(pFile->h, offset, FILE_BEGIN, &fileLocation) != NO_ERROR ){
22180    return SQLITE_IOERR;
22181  }
22182  assert( amt>0 );
22183  while( amt > 0 &&
22184         ( rc = DosWrite( pFile->h, (PVOID)pBuf, amt, &wrote ) ) == NO_ERROR &&
22185         wrote > 0
22186  ){
22187    amt -= wrote;
22188    pBuf = &((char*)pBuf)[wrote];
22189  }
22190
22191  return ( rc != NO_ERROR || amt > (int)wrote ) ? SQLITE_FULL : SQLITE_OK;
22192}
22193
22194/*
22195** Truncate an open file to a specified size
22196*/
22197static int os2Truncate( sqlite3_file *id, i64 nByte ){
22198  APIRET rc;
22199  os2File *pFile = (os2File*)id;
22200  assert( id!=0 );
22201  OSTRACE(( "TRUNCATE %d %lld\n", pFile->h, nByte ));
22202  SimulateIOError( return SQLITE_IOERR_TRUNCATE );
22203
22204  /* If the user has configured a chunk-size for this file, truncate the
22205  ** file so that it consists of an integer number of chunks (i.e. the
22206  ** actual file size after the operation may be larger than the requested
22207  ** size).
22208  */
22209  if( pFile->szChunk ){
22210    nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
22211  }
22212
22213  rc = DosSetFileSize( pFile->h, nByte );
22214  return rc == NO_ERROR ? SQLITE_OK : SQLITE_IOERR_TRUNCATE;
22215}
22216
22217#ifdef SQLITE_TEST
22218/*
22219** Count the number of fullsyncs and normal syncs.  This is used to test
22220** that syncs and fullsyncs are occuring at the right times.
22221*/
22222SQLITE_API int sqlite3_sync_count = 0;
22223SQLITE_API int sqlite3_fullsync_count = 0;
22224#endif
22225
22226/*
22227** Make sure all writes to a particular file are committed to disk.
22228*/
22229static int os2Sync( sqlite3_file *id, int flags ){
22230  os2File *pFile = (os2File*)id;
22231  OSTRACE(( "SYNC %d lock=%d\n", pFile->h, pFile->locktype ));
22232#ifdef SQLITE_TEST
22233  if( flags & SQLITE_SYNC_FULL){
22234    sqlite3_fullsync_count++;
22235  }
22236  sqlite3_sync_count++;
22237#endif
22238  /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
22239  ** no-op
22240  */
22241#ifdef SQLITE_NO_SYNC
22242  UNUSED_PARAMETER(pFile);
22243  return SQLITE_OK;
22244#else
22245  return DosResetBuffer( pFile->h ) == NO_ERROR ? SQLITE_OK : SQLITE_IOERR;
22246#endif
22247}
22248
22249/*
22250** Determine the current size of a file in bytes
22251*/
22252static int os2FileSize( sqlite3_file *id, sqlite3_int64 *pSize ){
22253  APIRET rc = NO_ERROR;
22254  FILESTATUS3 fsts3FileInfo;
22255  memset(&fsts3FileInfo, 0, sizeof(fsts3FileInfo));
22256  assert( id!=0 );
22257  SimulateIOError( return SQLITE_IOERR_FSTAT );
22258  rc = DosQueryFileInfo( ((os2File*)id)->h, FIL_STANDARD, &fsts3FileInfo, sizeof(FILESTATUS3) );
22259  if( rc == NO_ERROR ){
22260    *pSize = fsts3FileInfo.cbFile;
22261    return SQLITE_OK;
22262  }else{
22263    return SQLITE_IOERR_FSTAT;
22264  }
22265}
22266
22267/*
22268** Acquire a reader lock.
22269*/
22270static int getReadLock( os2File *pFile ){
22271  FILELOCK  LockArea,
22272            UnlockArea;
22273  APIRET res;
22274  memset(&LockArea, 0, sizeof(LockArea));
22275  memset(&UnlockArea, 0, sizeof(UnlockArea));
22276  LockArea.lOffset = SHARED_FIRST;
22277  LockArea.lRange = SHARED_SIZE;
22278  UnlockArea.lOffset = 0L;
22279  UnlockArea.lRange = 0L;
22280  res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 1L );
22281  OSTRACE(( "GETREADLOCK %d res=%d\n", pFile->h, res ));
22282  return res;
22283}
22284
22285/*
22286** Undo a readlock
22287*/
22288static int unlockReadLock( os2File *id ){
22289  FILELOCK  LockArea,
22290            UnlockArea;
22291  APIRET res;
22292  memset(&LockArea, 0, sizeof(LockArea));
22293  memset(&UnlockArea, 0, sizeof(UnlockArea));
22294  LockArea.lOffset = 0L;
22295  LockArea.lRange = 0L;
22296  UnlockArea.lOffset = SHARED_FIRST;
22297  UnlockArea.lRange = SHARED_SIZE;
22298  res = DosSetFileLocks( id->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 1L );
22299  OSTRACE(( "UNLOCK-READLOCK file handle=%d res=%d?\n", id->h, res ));
22300  return res;
22301}
22302
22303/*
22304** Lock the file with the lock specified by parameter locktype - one
22305** of the following:
22306**
22307**     (1) SHARED_LOCK
22308**     (2) RESERVED_LOCK
22309**     (3) PENDING_LOCK
22310**     (4) EXCLUSIVE_LOCK
22311**
22312** Sometimes when requesting one lock state, additional lock states
22313** are inserted in between.  The locking might fail on one of the later
22314** transitions leaving the lock state different from what it started but
22315** still short of its goal.  The following chart shows the allowed
22316** transitions and the inserted intermediate states:
22317**
22318**    UNLOCKED -> SHARED
22319**    SHARED -> RESERVED
22320**    SHARED -> (PENDING) -> EXCLUSIVE
22321**    RESERVED -> (PENDING) -> EXCLUSIVE
22322**    PENDING -> EXCLUSIVE
22323**
22324** This routine will only increase a lock.  The os2Unlock() routine
22325** erases all locks at once and returns us immediately to locking level 0.
22326** It is not possible to lower the locking level one step at a time.  You
22327** must go straight to locking level 0.
22328*/
22329static int os2Lock( sqlite3_file *id, int locktype ){
22330  int rc = SQLITE_OK;       /* Return code from subroutines */
22331  APIRET res = NO_ERROR;    /* Result of an OS/2 lock call */
22332  int newLocktype;       /* Set pFile->locktype to this value before exiting */
22333  int gotPendingLock = 0;/* True if we acquired a PENDING lock this time */
22334  FILELOCK  LockArea,
22335            UnlockArea;
22336  os2File *pFile = (os2File*)id;
22337  memset(&LockArea, 0, sizeof(LockArea));
22338  memset(&UnlockArea, 0, sizeof(UnlockArea));
22339  assert( pFile!=0 );
22340  OSTRACE(( "LOCK %d %d was %d\n", pFile->h, locktype, pFile->locktype ));
22341
22342  /* If there is already a lock of this type or more restrictive on the
22343  ** os2File, do nothing. Don't use the end_lock: exit path, as
22344  ** sqlite3_mutex_enter() hasn't been called yet.
22345  */
22346  if( pFile->locktype>=locktype ){
22347    OSTRACE(( "LOCK %d %d ok (already held)\n", pFile->h, locktype ));
22348    return SQLITE_OK;
22349  }
22350
22351  /* Make sure the locking sequence is correct
22352  */
22353  assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
22354  assert( locktype!=PENDING_LOCK );
22355  assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
22356
22357  /* Lock the PENDING_LOCK byte if we need to acquire a PENDING lock or
22358  ** a SHARED lock.  If we are acquiring a SHARED lock, the acquisition of
22359  ** the PENDING_LOCK byte is temporary.
22360  */
22361  newLocktype = pFile->locktype;
22362  if( pFile->locktype==NO_LOCK
22363      || (locktype==EXCLUSIVE_LOCK && pFile->locktype==RESERVED_LOCK)
22364  ){
22365    LockArea.lOffset = PENDING_BYTE;
22366    LockArea.lRange = 1L;
22367    UnlockArea.lOffset = 0L;
22368    UnlockArea.lRange = 0L;
22369
22370    /* wait longer than LOCK_TIMEOUT here not to have to try multiple times */
22371    res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, 100L, 0L );
22372    if( res == NO_ERROR ){
22373      gotPendingLock = 1;
22374      OSTRACE(( "LOCK %d pending lock boolean set.  res=%d\n", pFile->h, res ));
22375    }
22376  }
22377
22378  /* Acquire a shared lock
22379  */
22380  if( locktype==SHARED_LOCK && res == NO_ERROR ){
22381    assert( pFile->locktype==NO_LOCK );
22382    res = getReadLock(pFile);
22383    if( res == NO_ERROR ){
22384      newLocktype = SHARED_LOCK;
22385    }
22386    OSTRACE(( "LOCK %d acquire shared lock. res=%d\n", pFile->h, res ));
22387  }
22388
22389  /* Acquire a RESERVED lock
22390  */
22391  if( locktype==RESERVED_LOCK && res == NO_ERROR ){
22392    assert( pFile->locktype==SHARED_LOCK );
22393    LockArea.lOffset = RESERVED_BYTE;
22394    LockArea.lRange = 1L;
22395    UnlockArea.lOffset = 0L;
22396    UnlockArea.lRange = 0L;
22397    res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
22398    if( res == NO_ERROR ){
22399      newLocktype = RESERVED_LOCK;
22400    }
22401    OSTRACE(( "LOCK %d acquire reserved lock. res=%d\n", pFile->h, res ));
22402  }
22403
22404  /* Acquire a PENDING lock
22405  */
22406  if( locktype==EXCLUSIVE_LOCK && res == NO_ERROR ){
22407    newLocktype = PENDING_LOCK;
22408    gotPendingLock = 0;
22409    OSTRACE(( "LOCK %d acquire pending lock. pending lock boolean unset.\n",
22410               pFile->h ));
22411  }
22412
22413  /* Acquire an EXCLUSIVE lock
22414  */
22415  if( locktype==EXCLUSIVE_LOCK && res == NO_ERROR ){
22416    assert( pFile->locktype>=SHARED_LOCK );
22417    res = unlockReadLock(pFile);
22418    OSTRACE(( "unreadlock = %d\n", res ));
22419    LockArea.lOffset = SHARED_FIRST;
22420    LockArea.lRange = SHARED_SIZE;
22421    UnlockArea.lOffset = 0L;
22422    UnlockArea.lRange = 0L;
22423    res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
22424    if( res == NO_ERROR ){
22425      newLocktype = EXCLUSIVE_LOCK;
22426    }else{
22427      OSTRACE(( "OS/2 error-code = %d\n", res ));
22428      getReadLock(pFile);
22429    }
22430    OSTRACE(( "LOCK %d acquire exclusive lock.  res=%d\n", pFile->h, res ));
22431  }
22432
22433  /* If we are holding a PENDING lock that ought to be released, then
22434  ** release it now.
22435  */
22436  if( gotPendingLock && locktype==SHARED_LOCK ){
22437    int r;
22438    LockArea.lOffset = 0L;
22439    LockArea.lRange = 0L;
22440    UnlockArea.lOffset = PENDING_BYTE;
22441    UnlockArea.lRange = 1L;
22442    r = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
22443    OSTRACE(( "LOCK %d unlocking pending/is shared. r=%d\n", pFile->h, r ));
22444  }
22445
22446  /* Update the state of the lock has held in the file descriptor then
22447  ** return the appropriate result code.
22448  */
22449  if( res == NO_ERROR ){
22450    rc = SQLITE_OK;
22451  }else{
22452    OSTRACE(( "LOCK FAILED %d trying for %d but got %d\n", pFile->h,
22453              locktype, newLocktype ));
22454    rc = SQLITE_BUSY;
22455  }
22456  pFile->locktype = newLocktype;
22457  OSTRACE(( "LOCK %d now %d\n", pFile->h, pFile->locktype ));
22458  return rc;
22459}
22460
22461/*
22462** This routine checks if there is a RESERVED lock held on the specified
22463** file by this or any other process. If such a lock is held, return
22464** non-zero, otherwise zero.
22465*/
22466static int os2CheckReservedLock( sqlite3_file *id, int *pOut ){
22467  int r = 0;
22468  os2File *pFile = (os2File*)id;
22469  assert( pFile!=0 );
22470  if( pFile->locktype>=RESERVED_LOCK ){
22471    r = 1;
22472    OSTRACE(( "TEST WR-LOCK %d %d (local)\n", pFile->h, r ));
22473  }else{
22474    FILELOCK  LockArea,
22475              UnlockArea;
22476    APIRET rc = NO_ERROR;
22477    memset(&LockArea, 0, sizeof(LockArea));
22478    memset(&UnlockArea, 0, sizeof(UnlockArea));
22479    LockArea.lOffset = RESERVED_BYTE;
22480    LockArea.lRange = 1L;
22481    UnlockArea.lOffset = 0L;
22482    UnlockArea.lRange = 0L;
22483    rc = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
22484    OSTRACE(( "TEST WR-LOCK %d lock reserved byte rc=%d\n", pFile->h, rc ));
22485    if( rc == NO_ERROR ){
22486      APIRET rcu = NO_ERROR; /* return code for unlocking */
22487      LockArea.lOffset = 0L;
22488      LockArea.lRange = 0L;
22489      UnlockArea.lOffset = RESERVED_BYTE;
22490      UnlockArea.lRange = 1L;
22491      rcu = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
22492      OSTRACE(( "TEST WR-LOCK %d unlock reserved byte r=%d\n", pFile->h, rcu ));
22493    }
22494    r = !(rc == NO_ERROR);
22495    OSTRACE(( "TEST WR-LOCK %d %d (remote)\n", pFile->h, r ));
22496  }
22497  *pOut = r;
22498  return SQLITE_OK;
22499}
22500
22501/*
22502** Lower the locking level on file descriptor id to locktype.  locktype
22503** must be either NO_LOCK or SHARED_LOCK.
22504**
22505** If the locking level of the file descriptor is already at or below
22506** the requested locking level, this routine is a no-op.
22507**
22508** It is not possible for this routine to fail if the second argument
22509** is NO_LOCK.  If the second argument is SHARED_LOCK then this routine
22510** might return SQLITE_IOERR;
22511*/
22512static int os2Unlock( sqlite3_file *id, int locktype ){
22513  int type;
22514  os2File *pFile = (os2File*)id;
22515  APIRET rc = SQLITE_OK;
22516  APIRET res = NO_ERROR;
22517  FILELOCK  LockArea,
22518            UnlockArea;
22519  memset(&LockArea, 0, sizeof(LockArea));
22520  memset(&UnlockArea, 0, sizeof(UnlockArea));
22521  assert( pFile!=0 );
22522  assert( locktype<=SHARED_LOCK );
22523  OSTRACE(( "UNLOCK %d to %d was %d\n", pFile->h, locktype, pFile->locktype ));
22524  type = pFile->locktype;
22525  if( type>=EXCLUSIVE_LOCK ){
22526    LockArea.lOffset = 0L;
22527    LockArea.lRange = 0L;
22528    UnlockArea.lOffset = SHARED_FIRST;
22529    UnlockArea.lRange = SHARED_SIZE;
22530    res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
22531    OSTRACE(( "UNLOCK %d exclusive lock res=%d\n", pFile->h, res ));
22532    if( locktype==SHARED_LOCK && getReadLock(pFile) != NO_ERROR ){
22533      /* This should never happen.  We should always be able to
22534      ** reacquire the read lock */
22535      OSTRACE(( "UNLOCK %d to %d getReadLock() failed\n", pFile->h, locktype ));
22536      rc = SQLITE_IOERR_UNLOCK;
22537    }
22538  }
22539  if( type>=RESERVED_LOCK ){
22540    LockArea.lOffset = 0L;
22541    LockArea.lRange = 0L;
22542    UnlockArea.lOffset = RESERVED_BYTE;
22543    UnlockArea.lRange = 1L;
22544    res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
22545    OSTRACE(( "UNLOCK %d reserved res=%d\n", pFile->h, res ));
22546  }
22547  if( locktype==NO_LOCK && type>=SHARED_LOCK ){
22548    res = unlockReadLock(pFile);
22549    OSTRACE(( "UNLOCK %d is %d want %d res=%d\n",
22550              pFile->h, type, locktype, res ));
22551  }
22552  if( type>=PENDING_LOCK ){
22553    LockArea.lOffset = 0L;
22554    LockArea.lRange = 0L;
22555    UnlockArea.lOffset = PENDING_BYTE;
22556    UnlockArea.lRange = 1L;
22557    res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
22558    OSTRACE(( "UNLOCK %d pending res=%d\n", pFile->h, res ));
22559  }
22560  pFile->locktype = locktype;
22561  OSTRACE(( "UNLOCK %d now %d\n", pFile->h, pFile->locktype ));
22562  return rc;
22563}
22564
22565/*
22566** Control and query of the open file handle.
22567*/
22568static int os2FileControl(sqlite3_file *id, int op, void *pArg){
22569  switch( op ){
22570    case SQLITE_FCNTL_LOCKSTATE: {
22571      *(int*)pArg = ((os2File*)id)->locktype;
22572      OSTRACE(( "FCNTL_LOCKSTATE %d lock=%d\n",
22573                ((os2File*)id)->h, ((os2File*)id)->locktype ));
22574      return SQLITE_OK;
22575    }
22576    case SQLITE_FCNTL_CHUNK_SIZE: {
22577      ((os2File*)id)->szChunk = *(int*)pArg;
22578      return SQLITE_OK;
22579    }
22580    case SQLITE_FCNTL_SIZE_HINT: {
22581      sqlite3_int64 sz = *(sqlite3_int64*)pArg;
22582      SimulateIOErrorBenign(1);
22583      os2Truncate(id, sz);
22584      SimulateIOErrorBenign(0);
22585      return SQLITE_OK;
22586    }
22587    case SQLITE_FCNTL_SYNC_OMITTED: {
22588      return SQLITE_OK;
22589    }
22590  }
22591  return SQLITE_NOTFOUND;
22592}
22593
22594/*
22595** Return the sector size in bytes of the underlying block device for
22596** the specified file. This is almost always 512 bytes, but may be
22597** larger for some devices.
22598**
22599** SQLite code assumes this function cannot fail. It also assumes that
22600** if two files are created in the same file-system directory (i.e.
22601** a database and its journal file) that the sector size will be the
22602** same for both.
22603*/
22604static int os2SectorSize(sqlite3_file *id){
22605  UNUSED_PARAMETER(id);
22606  return SQLITE_DEFAULT_SECTOR_SIZE;
22607}
22608
22609/*
22610** Return a vector of device characteristics.
22611*/
22612static int os2DeviceCharacteristics(sqlite3_file *id){
22613  UNUSED_PARAMETER(id);
22614  return SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN;
22615}
22616
22617
22618/*
22619** Character set conversion objects used by conversion routines.
22620*/
22621static UconvObject ucUtf8 = NULL; /* convert between UTF-8 and UCS-2 */
22622static UconvObject uclCp = NULL;  /* convert between local codepage and UCS-2 */
22623
22624/*
22625** Helper function to initialize the conversion objects from and to UTF-8.
22626*/
22627static void initUconvObjects( void ){
22628  if( UniCreateUconvObject( UTF_8, &ucUtf8 ) != ULS_SUCCESS )
22629    ucUtf8 = NULL;
22630  if ( UniCreateUconvObject( (UniChar *)L"@path=yes", &uclCp ) != ULS_SUCCESS )
22631    uclCp = NULL;
22632}
22633
22634/*
22635** Helper function to free the conversion objects from and to UTF-8.
22636*/
22637static void freeUconvObjects( void ){
22638  if ( ucUtf8 )
22639    UniFreeUconvObject( ucUtf8 );
22640  if ( uclCp )
22641    UniFreeUconvObject( uclCp );
22642  ucUtf8 = NULL;
22643  uclCp = NULL;
22644}
22645
22646/*
22647** Helper function to convert UTF-8 filenames to local OS/2 codepage.
22648** The two-step process: first convert the incoming UTF-8 string
22649** into UCS-2 and then from UCS-2 to the current codepage.
22650** The returned char pointer has to be freed.
22651*/
22652static char *convertUtf8PathToCp( const char *in ){
22653  UniChar tempPath[CCHMAXPATH];
22654  char *out = (char *)calloc( CCHMAXPATH, 1 );
22655
22656  if( !out )
22657    return NULL;
22658
22659  if( !ucUtf8 || !uclCp )
22660    initUconvObjects();
22661
22662  /* determine string for the conversion of UTF-8 which is CP1208 */
22663  if( UniStrToUcs( ucUtf8, tempPath, (char *)in, CCHMAXPATH ) != ULS_SUCCESS )
22664    return out; /* if conversion fails, return the empty string */
22665
22666  /* conversion for current codepage which can be used for paths */
22667  UniStrFromUcs( uclCp, out, tempPath, CCHMAXPATH );
22668
22669  return out;
22670}
22671
22672/*
22673** Helper function to convert filenames from local codepage to UTF-8.
22674** The two-step process: first convert the incoming codepage-specific
22675** string into UCS-2 and then from UCS-2 to the codepage of UTF-8.
22676** The returned char pointer has to be freed.
22677**
22678** This function is non-static to be able to use this in shell.c and
22679** similar applications that take command line arguments.
22680*/
22681char *convertCpPathToUtf8( const char *in ){
22682  UniChar tempPath[CCHMAXPATH];
22683  char *out = (char *)calloc( CCHMAXPATH, 1 );
22684
22685  if( !out )
22686    return NULL;
22687
22688  if( !ucUtf8 || !uclCp )
22689    initUconvObjects();
22690
22691  /* conversion for current codepage which can be used for paths */
22692  if( UniStrToUcs( uclCp, tempPath, (char *)in, CCHMAXPATH ) != ULS_SUCCESS )
22693    return out; /* if conversion fails, return the empty string */
22694
22695  /* determine string for the conversion of UTF-8 which is CP1208 */
22696  UniStrFromUcs( ucUtf8, out, tempPath, CCHMAXPATH );
22697
22698  return out;
22699}
22700
22701
22702#ifndef SQLITE_OMIT_WAL
22703
22704/*
22705** Use main database file for interprocess locking. If un-defined
22706** a separate file is created for this purpose. The file will be
22707** used only to set file locks. There will be no data written to it.
22708*/
22709#define SQLITE_OS2_NO_WAL_LOCK_FILE
22710
22711#if 0
22712static void _ERR_TRACE( const char *fmt, ... ) {
22713  va_list  ap;
22714  va_start(ap, fmt);
22715  vfprintf(stderr, fmt, ap);
22716  fflush(stderr);
22717}
22718#define ERR_TRACE(rc, msg)        \
22719        if( (rc) != SQLITE_OK ) _ERR_TRACE msg;
22720#else
22721#define ERR_TRACE(rc, msg)
22722#endif
22723
22724/*
22725** Helper functions to obtain and relinquish the global mutex. The
22726** global mutex is used to protect os2ShmNodeList.
22727**
22728** Function os2ShmMutexHeld() is used to assert() that the global mutex
22729** is held when required. This function is only used as part of assert()
22730** statements. e.g.
22731**
22732**   os2ShmEnterMutex()
22733**     assert( os2ShmMutexHeld() );
22734**   os2ShmLeaveMutex()
22735*/
22736static void os2ShmEnterMutex(void){
22737  sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
22738}
22739static void os2ShmLeaveMutex(void){
22740  sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
22741}
22742#ifdef SQLITE_DEBUG
22743static int os2ShmMutexHeld(void) {
22744  return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
22745}
22746int GetCurrentProcessId(void) {
22747  PPIB pib;
22748  DosGetInfoBlocks(NULL, &pib);
22749  return (int)pib->pib_ulpid;
22750}
22751#endif
22752
22753/*
22754** Object used to represent a the shared memory area for a single log file.
22755** When multiple threads all reference the same log-summary, each thread has
22756** its own os2File object, but they all point to a single instance of this
22757** object.  In other words, each log-summary is opened only once per process.
22758**
22759** os2ShmMutexHeld() must be true when creating or destroying
22760** this object or while reading or writing the following fields:
22761**
22762**      nRef
22763**      pNext
22764**
22765** The following fields are read-only after the object is created:
22766**
22767**      szRegion
22768**      hLockFile
22769**      shmBaseName
22770**
22771** Either os2ShmNode.mutex must be held or os2ShmNode.nRef==0 and
22772** os2ShmMutexHeld() is true when reading or writing any other field
22773** in this structure.
22774**
22775*/
22776struct os2ShmNode {
22777  sqlite3_mutex *mutex;      /* Mutex to access this object */
22778  os2ShmNode *pNext;         /* Next in list of all os2ShmNode objects */
22779
22780  int szRegion;              /* Size of shared-memory regions */
22781
22782  int nRegion;               /* Size of array apRegion */
22783  void **apRegion;           /* Array of pointers to shared-memory regions */
22784
22785  int nRef;                  /* Number of os2ShmLink objects pointing to this */
22786  os2ShmLink *pFirst;        /* First os2ShmLink object pointing to this */
22787
22788  HFILE hLockFile;           /* File used for inter-process memory locking */
22789  char shmBaseName[1];       /* Name of the memory object !!! must last !!! */
22790};
22791
22792
22793/*
22794** Structure used internally by this VFS to record the state of an
22795** open shared memory connection.
22796**
22797** The following fields are initialized when this object is created and
22798** are read-only thereafter:
22799**
22800**    os2Shm.pShmNode
22801**    os2Shm.id
22802**
22803** All other fields are read/write.  The os2Shm.pShmNode->mutex must be held
22804** while accessing any read/write fields.
22805*/
22806struct os2ShmLink {
22807  os2ShmNode *pShmNode;      /* The underlying os2ShmNode object */
22808  os2ShmLink *pNext;         /* Next os2Shm with the same os2ShmNode */
22809  u32 sharedMask;            /* Mask of shared locks held */
22810  u32 exclMask;              /* Mask of exclusive locks held */
22811#ifdef SQLITE_DEBUG
22812  u8 id;                     /* Id of this connection with its os2ShmNode */
22813#endif
22814};
22815
22816
22817/*
22818** A global list of all os2ShmNode objects.
22819**
22820** The os2ShmMutexHeld() must be true while reading or writing this list.
22821*/
22822static os2ShmNode *os2ShmNodeList = NULL;
22823
22824/*
22825** Constants used for locking
22826*/
22827#ifdef  SQLITE_OS2_NO_WAL_LOCK_FILE
22828#define OS2_SHM_BASE   (PENDING_BYTE + 0x10000)         /* first lock byte */
22829#else
22830#define OS2_SHM_BASE   ((22+SQLITE_SHM_NLOCK)*4)        /* first lock byte */
22831#endif
22832
22833#define OS2_SHM_DMS    (OS2_SHM_BASE+SQLITE_SHM_NLOCK)  /* deadman switch */
22834
22835/*
22836** Apply advisory locks for all n bytes beginning at ofst.
22837*/
22838#define _SHM_UNLCK  1   /* no lock */
22839#define _SHM_RDLCK  2   /* shared lock, no wait */
22840#define _SHM_WRLCK  3   /* exlusive lock, no wait */
22841#define _SHM_WRLCK_WAIT 4 /* exclusive lock, wait */
22842static int os2ShmSystemLock(
22843  os2ShmNode *pNode,    /* Apply locks to this open shared-memory segment */
22844  int lockType,         /* _SHM_UNLCK, _SHM_RDLCK, _SHM_WRLCK or _SHM_WRLCK_WAIT */
22845  int ofst,             /* Offset to first byte to be locked/unlocked */
22846  int nByte             /* Number of bytes to lock or unlock */
22847){
22848  APIRET rc;
22849  FILELOCK area;
22850  ULONG mode, timeout;
22851
22852  /* Access to the os2ShmNode object is serialized by the caller */
22853  assert( sqlite3_mutex_held(pNode->mutex) || pNode->nRef==0 );
22854
22855  mode = 1;     /* shared lock */
22856  timeout = 0;  /* no wait */
22857  area.lOffset = ofst;
22858  area.lRange = nByte;
22859
22860  switch( lockType ) {
22861    case _SHM_WRLCK_WAIT:
22862      timeout = (ULONG)-1;      /* wait forever */
22863    case _SHM_WRLCK:
22864      mode = 0;                 /* exclusive lock */
22865    case _SHM_RDLCK:
22866      rc = DosSetFileLocks(pNode->hLockFile,
22867                           NULL, &area, timeout, mode);
22868      break;
22869    /* case _SHM_UNLCK: */
22870    default:
22871      rc = DosSetFileLocks(pNode->hLockFile,
22872                           &area, NULL, 0, 0);
22873      break;
22874  }
22875
22876  OSTRACE(("SHM-LOCK %d %s %s 0x%08lx\n",
22877           pNode->hLockFile,
22878           rc==SQLITE_OK ? "ok" : "failed",
22879           lockType==_SHM_UNLCK ? "Unlock" : "Lock",
22880           rc));
22881
22882  ERR_TRACE(rc, ("os2ShmSystemLock: %d %s\n", rc, pNode->shmBaseName))
22883
22884  return ( rc == 0 ) ?  SQLITE_OK : SQLITE_BUSY;
22885}
22886
22887/*
22888** Find an os2ShmNode in global list or allocate a new one, if not found.
22889**
22890** This is not a VFS shared-memory method; it is a utility function called
22891** by VFS shared-memory methods.
22892*/
22893static int os2OpenSharedMemory( os2File *fd, int szRegion ) {
22894  os2ShmLink *pLink;
22895  os2ShmNode *pNode;
22896  int cbShmName, rc = SQLITE_OK;
22897  char shmName[CCHMAXPATH + 30];
22898#ifndef SQLITE_OS2_NO_WAL_LOCK_FILE
22899  ULONG action;
22900#endif
22901
22902  /* We need some additional space at the end to append the region number */
22903  cbShmName = sprintf(shmName, "\\SHAREMEM\\%s", fd->zFullPathCp );
22904  if( cbShmName >= CCHMAXPATH-8 )
22905    return SQLITE_IOERR_SHMOPEN;
22906
22907  /* Replace colon in file name to form a valid shared memory name */
22908  shmName[10+1] = '!';
22909
22910  /* Allocate link object (we free it later in case of failure) */
22911  pLink = sqlite3_malloc( sizeof(*pLink) );
22912  if( !pLink )
22913    return SQLITE_NOMEM;
22914
22915  /* Access node list */
22916  os2ShmEnterMutex();
22917
22918  /* Find node by it's shared memory base name */
22919  for( pNode = os2ShmNodeList;
22920       pNode && stricmp(shmName, pNode->shmBaseName) != 0;
22921       pNode = pNode->pNext )   ;
22922
22923  /* Not found: allocate a new node */
22924  if( !pNode ) {
22925    pNode = sqlite3_malloc( sizeof(*pNode) + cbShmName );
22926    if( pNode ) {
22927      memset(pNode, 0, sizeof(*pNode) );
22928      pNode->szRegion = szRegion;
22929      pNode->hLockFile = (HFILE)-1;
22930      strcpy(pNode->shmBaseName, shmName);
22931
22932#ifdef SQLITE_OS2_NO_WAL_LOCK_FILE
22933      if( DosDupHandle(fd->h, &pNode->hLockFile) != 0 ) {
22934#else
22935      sprintf(shmName, "%s-lck", fd->zFullPathCp);
22936      if( DosOpen((PSZ)shmName, &pNode->hLockFile, &action, 0, FILE_NORMAL,
22937                  OPEN_ACTION_OPEN_IF_EXISTS | OPEN_ACTION_CREATE_IF_NEW,
22938                  OPEN_ACCESS_READWRITE | OPEN_SHARE_DENYNONE |
22939                  OPEN_FLAGS_NOINHERIT | OPEN_FLAGS_FAIL_ON_ERROR,
22940                  NULL) != 0 ) {
22941#endif
22942        sqlite3_free(pNode);
22943        rc = SQLITE_IOERR;
22944      } else {
22945        pNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
22946        if( !pNode->mutex ) {
22947          sqlite3_free(pNode);
22948          rc = SQLITE_NOMEM;
22949        }
22950      }
22951    } else {
22952      rc = SQLITE_NOMEM;
22953    }
22954
22955    if( rc == SQLITE_OK ) {
22956      pNode->pNext = os2ShmNodeList;
22957      os2ShmNodeList = pNode;
22958    } else {
22959      pNode = NULL;
22960    }
22961  } else if( pNode->szRegion != szRegion ) {
22962    rc = SQLITE_IOERR_SHMSIZE;
22963    pNode = NULL;
22964  }
22965
22966  if( pNode ) {
22967    sqlite3_mutex_enter(pNode->mutex);
22968
22969    memset(pLink, 0, sizeof(*pLink));
22970
22971    pLink->pShmNode = pNode;
22972    pLink->pNext = pNode->pFirst;
22973    pNode->pFirst = pLink;
22974    pNode->nRef++;
22975
22976    fd->pShmLink = pLink;
22977
22978    sqlite3_mutex_leave(pNode->mutex);
22979
22980  } else {
22981    /* Error occured. Free our link object. */
22982    sqlite3_free(pLink);
22983  }
22984
22985  os2ShmLeaveMutex();
22986
22987  ERR_TRACE(rc, ("os2OpenSharedMemory: %d  %s\n", rc, fd->zFullPathCp))
22988
22989  return rc;
22990}
22991
22992/*
22993** Purge the os2ShmNodeList list of all entries with nRef==0.
22994**
22995** This is not a VFS shared-memory method; it is a utility function called
22996** by VFS shared-memory methods.
22997*/
22998static void os2PurgeShmNodes( int deleteFlag ) {
22999  os2ShmNode *pNode;
23000  os2ShmNode **ppNode;
23001
23002  os2ShmEnterMutex();
23003
23004  ppNode = &os2ShmNodeList;
23005
23006  while( *ppNode ) {
23007    pNode = *ppNode;
23008
23009    if( pNode->nRef == 0 ) {
23010      *ppNode = pNode->pNext;
23011
23012      if( pNode->apRegion ) {
23013        /* Prevent other processes from resizing the shared memory */
23014        os2ShmSystemLock(pNode, _SHM_WRLCK_WAIT, OS2_SHM_DMS, 1);
23015
23016        while( pNode->nRegion-- ) {
23017#ifdef SQLITE_DEBUG
23018          int rc =
23019#endif
23020          DosFreeMem(pNode->apRegion[pNode->nRegion]);
23021
23022          OSTRACE(("SHM-PURGE pid-%d unmap region=%d %s\n",
23023                  (int)GetCurrentProcessId(), pNode->nRegion,
23024                  rc == 0 ? "ok" : "failed"));
23025        }
23026
23027        /* Allow other processes to resize the shared memory */
23028        os2ShmSystemLock(pNode, _SHM_UNLCK, OS2_SHM_DMS, 1);
23029
23030        sqlite3_free(pNode->apRegion);
23031      }
23032
23033      DosClose(pNode->hLockFile);
23034
23035#ifndef SQLITE_OS2_NO_WAL_LOCK_FILE
23036      if( deleteFlag ) {
23037         char fileName[CCHMAXPATH];
23038         /* Skip "\\SHAREMEM\\" */
23039         sprintf(fileName, "%s-lck", pNode->shmBaseName + 10);
23040         /* restore colon */
23041         fileName[1] = ':';
23042
23043         DosForceDelete(fileName);
23044      }
23045#endif
23046
23047      sqlite3_mutex_free(pNode->mutex);
23048
23049      sqlite3_free(pNode);
23050
23051    } else {
23052      ppNode = &pNode->pNext;
23053    }
23054  }
23055
23056  os2ShmLeaveMutex();
23057}
23058
23059/*
23060** This function is called to obtain a pointer to region iRegion of the
23061** shared-memory associated with the database file id. Shared-memory regions
23062** are numbered starting from zero. Each shared-memory region is szRegion
23063** bytes in size.
23064**
23065** If an error occurs, an error code is returned and *pp is set to NULL.
23066**
23067** Otherwise, if the bExtend parameter is 0 and the requested shared-memory
23068** region has not been allocated (by any client, including one running in a
23069** separate process), then *pp is set to NULL and SQLITE_OK returned. If
23070** bExtend is non-zero and the requested shared-memory region has not yet
23071** been allocated, it is allocated by this function.
23072**
23073** If the shared-memory region has already been allocated or is allocated by
23074** this call as described above, then it is mapped into this processes
23075** address space (if it is not already), *pp is set to point to the mapped
23076** memory and SQLITE_OK returned.
23077*/
23078static int os2ShmMap(
23079  sqlite3_file *id,               /* Handle open on database file */
23080  int iRegion,                    /* Region to retrieve */
23081  int szRegion,                   /* Size of regions */
23082  int bExtend,                    /* True to extend block if necessary */
23083  void volatile **pp              /* OUT: Mapped memory */
23084){
23085  PVOID pvTemp;
23086  void **apRegion;
23087  os2ShmNode *pNode;
23088  int n, rc = SQLITE_OK;
23089  char shmName[CCHMAXPATH];
23090  os2File *pFile = (os2File*)id;
23091
23092  *pp = NULL;
23093
23094  if( !pFile->pShmLink )
23095    rc = os2OpenSharedMemory( pFile, szRegion );
23096
23097  if( rc == SQLITE_OK ) {
23098    pNode = pFile->pShmLink->pShmNode ;
23099
23100    sqlite3_mutex_enter(pNode->mutex);
23101
23102    assert( szRegion==pNode->szRegion );
23103
23104    /* Unmapped region ? */
23105    if( iRegion >= pNode->nRegion ) {
23106      /* Prevent other processes from resizing the shared memory */
23107      os2ShmSystemLock(pNode, _SHM_WRLCK_WAIT, OS2_SHM_DMS, 1);
23108
23109      apRegion = sqlite3_realloc(
23110        pNode->apRegion, (iRegion + 1) * sizeof(apRegion[0]));
23111
23112      if( apRegion ) {
23113        pNode->apRegion = apRegion;
23114
23115        while( pNode->nRegion <= iRegion ) {
23116          sprintf(shmName, "%s-%u",
23117                  pNode->shmBaseName, pNode->nRegion);
23118
23119          if( DosGetNamedSharedMem(&pvTemp, (PSZ)shmName,
23120                PAG_READ | PAG_WRITE) != NO_ERROR ) {
23121            if( !bExtend )
23122              break;
23123
23124            if( DosAllocSharedMem(&pvTemp, (PSZ)shmName, szRegion,
23125                  PAG_READ | PAG_WRITE | PAG_COMMIT | OBJ_ANY) != NO_ERROR &&
23126                DosAllocSharedMem(&pvTemp, (PSZ)shmName, szRegion,
23127                  PAG_READ | PAG_WRITE | PAG_COMMIT) != NO_ERROR ) {
23128              rc = SQLITE_NOMEM;
23129              break;
23130            }
23131          }
23132
23133          apRegion[pNode->nRegion++] = pvTemp;
23134        }
23135
23136        /* zero out remaining entries */
23137        for( n = pNode->nRegion; n <= iRegion; n++ )
23138          pNode->apRegion[n] = NULL;
23139
23140        /* Return this region (maybe zero) */
23141        *pp = pNode->apRegion[iRegion];
23142      } else {
23143        rc = SQLITE_NOMEM;
23144      }
23145
23146      /* Allow other processes to resize the shared memory */
23147      os2ShmSystemLock(pNode, _SHM_UNLCK, OS2_SHM_DMS, 1);
23148
23149    } else {
23150      /* Region has been mapped previously */
23151      *pp = pNode->apRegion[iRegion];
23152    }
23153
23154    sqlite3_mutex_leave(pNode->mutex);
23155  }
23156
23157  ERR_TRACE(rc, ("os2ShmMap: %s iRgn = %d, szRgn = %d, bExt = %d : %d\n",
23158                 pFile->zFullPathCp, iRegion, szRegion, bExtend, rc))
23159
23160  return rc;
23161}
23162
23163/*
23164** Close a connection to shared-memory.  Delete the underlying
23165** storage if deleteFlag is true.
23166**
23167** If there is no shared memory associated with the connection then this
23168** routine is a harmless no-op.
23169*/
23170static int os2ShmUnmap(
23171  sqlite3_file *id,               /* The underlying database file */
23172  int deleteFlag                  /* Delete shared-memory if true */
23173){
23174  os2File *pFile = (os2File*)id;
23175  os2ShmLink *pLink = pFile->pShmLink;
23176
23177  if( pLink ) {
23178    int nRef = -1;
23179    os2ShmLink **ppLink;
23180    os2ShmNode *pNode = pLink->pShmNode;
23181
23182    sqlite3_mutex_enter(pNode->mutex);
23183
23184    for( ppLink = &pNode->pFirst;
23185         *ppLink && *ppLink != pLink;
23186         ppLink = &(*ppLink)->pNext )   ;
23187
23188    assert(*ppLink);
23189
23190    if( *ppLink ) {
23191      *ppLink = pLink->pNext;
23192      nRef = --pNode->nRef;
23193    } else {
23194      ERR_TRACE(1, ("os2ShmUnmap: link not found ! %s\n",
23195                    pNode->shmBaseName))
23196    }
23197
23198    pFile->pShmLink = NULL;
23199    sqlite3_free(pLink);
23200
23201    sqlite3_mutex_leave(pNode->mutex);
23202
23203    if( nRef == 0 )
23204      os2PurgeShmNodes( deleteFlag );
23205  }
23206
23207  return SQLITE_OK;
23208}
23209
23210/*
23211** Change the lock state for a shared-memory segment.
23212**
23213** Note that the relationship between SHAREd and EXCLUSIVE locks is a little
23214** different here than in posix.  In xShmLock(), one can go from unlocked
23215** to shared and back or from unlocked to exclusive and back.  But one may
23216** not go from shared to exclusive or from exclusive to shared.
23217*/
23218static int os2ShmLock(
23219  sqlite3_file *id,          /* Database file holding the shared memory */
23220  int ofst,                  /* First lock to acquire or release */
23221  int n,                     /* Number of locks to acquire or release */
23222  int flags                  /* What to do with the lock */
23223){
23224  u32 mask;                             /* Mask of locks to take or release */
23225  int rc = SQLITE_OK;                   /* Result code */
23226  os2File *pFile = (os2File*)id;
23227  os2ShmLink *p = pFile->pShmLink;      /* The shared memory being locked */
23228  os2ShmLink *pX;                       /* For looping over all siblings */
23229  os2ShmNode *pShmNode = p->pShmNode;   /* Our node */
23230
23231  assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
23232  assert( n>=1 );
23233  assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
23234       || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
23235       || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
23236       || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
23237  assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
23238
23239  mask = (u32)((1U<<(ofst+n)) - (1U<<ofst));
23240  assert( n>1 || mask==(1<<ofst) );
23241
23242
23243  sqlite3_mutex_enter(pShmNode->mutex);
23244
23245  if( flags & SQLITE_SHM_UNLOCK ){
23246    u32 allMask = 0; /* Mask of locks held by siblings */
23247
23248    /* See if any siblings hold this same lock */
23249    for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
23250      if( pX==p ) continue;
23251      assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
23252      allMask |= pX->sharedMask;
23253    }
23254
23255    /* Unlock the system-level locks */
23256    if( (mask & allMask)==0 ){
23257      rc = os2ShmSystemLock(pShmNode, _SHM_UNLCK, ofst+OS2_SHM_BASE, n);
23258    }else{
23259      rc = SQLITE_OK;
23260    }
23261
23262    /* Undo the local locks */
23263    if( rc==SQLITE_OK ){
23264      p->exclMask &= ~mask;
23265      p->sharedMask &= ~mask;
23266    }
23267  }else if( flags & SQLITE_SHM_SHARED ){
23268    u32 allShared = 0;  /* Union of locks held by connections other than "p" */
23269
23270    /* Find out which shared locks are already held by sibling connections.
23271    ** If any sibling already holds an exclusive lock, go ahead and return
23272    ** SQLITE_BUSY.
23273    */
23274    for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
23275      if( (pX->exclMask & mask)!=0 ){
23276        rc = SQLITE_BUSY;
23277        break;
23278      }
23279      allShared |= pX->sharedMask;
23280    }
23281
23282    /* Get shared locks at the system level, if necessary */
23283    if( rc==SQLITE_OK ){
23284      if( (allShared & mask)==0 ){
23285        rc = os2ShmSystemLock(pShmNode, _SHM_RDLCK, ofst+OS2_SHM_BASE, n);
23286      }else{
23287        rc = SQLITE_OK;
23288      }
23289    }
23290
23291    /* Get the local shared locks */
23292    if( rc==SQLITE_OK ){
23293      p->sharedMask |= mask;
23294    }
23295  }else{
23296    /* Make sure no sibling connections hold locks that will block this
23297    ** lock.  If any do, return SQLITE_BUSY right away.
23298    */
23299    for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
23300      if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
23301        rc = SQLITE_BUSY;
23302        break;
23303      }
23304    }
23305
23306    /* Get the exclusive locks at the system level.  Then if successful
23307    ** also mark the local connection as being locked.
23308    */
23309    if( rc==SQLITE_OK ){
23310      rc = os2ShmSystemLock(pShmNode, _SHM_WRLCK, ofst+OS2_SHM_BASE, n);
23311      if( rc==SQLITE_OK ){
23312        assert( (p->sharedMask & mask)==0 );
23313        p->exclMask |= mask;
23314      }
23315    }
23316  }
23317
23318  sqlite3_mutex_leave(pShmNode->mutex);
23319
23320  OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x %s\n",
23321           p->id, (int)GetCurrentProcessId(), p->sharedMask, p->exclMask,
23322           rc ? "failed" : "ok"));
23323
23324  ERR_TRACE(rc, ("os2ShmLock: ofst = %d, n = %d, flags = 0x%x -> %d \n",
23325                 ofst, n, flags, rc))
23326
23327  return rc;
23328}
23329
23330/*
23331** Implement a memory barrier or memory fence on shared memory.
23332**
23333** All loads and stores begun before the barrier must complete before
23334** any load or store begun after the barrier.
23335*/
23336static void os2ShmBarrier(
23337  sqlite3_file *id                /* Database file holding the shared memory */
23338){
23339  UNUSED_PARAMETER(id);
23340  os2ShmEnterMutex();
23341  os2ShmLeaveMutex();
23342}
23343
23344#else
23345# define os2ShmMap     0
23346# define os2ShmLock    0
23347# define os2ShmBarrier 0
23348# define os2ShmUnmap   0
23349#endif /* #ifndef SQLITE_OMIT_WAL */
23350
23351
23352/*
23353** This vector defines all the methods that can operate on an
23354** sqlite3_file for os2.
23355*/
23356static const sqlite3_io_methods os2IoMethod = {
23357  2,                              /* iVersion */
23358  os2Close,                       /* xClose */
23359  os2Read,                        /* xRead */
23360  os2Write,                       /* xWrite */
23361  os2Truncate,                    /* xTruncate */
23362  os2Sync,                        /* xSync */
23363  os2FileSize,                    /* xFileSize */
23364  os2Lock,                        /* xLock */
23365  os2Unlock,                      /* xUnlock */
23366  os2CheckReservedLock,           /* xCheckReservedLock */
23367  os2FileControl,                 /* xFileControl */
23368  os2SectorSize,                  /* xSectorSize */
23369  os2DeviceCharacteristics,       /* xDeviceCharacteristics */
23370  os2ShmMap,                      /* xShmMap */
23371  os2ShmLock,                     /* xShmLock */
23372  os2ShmBarrier,                  /* xShmBarrier */
23373  os2ShmUnmap                     /* xShmUnmap */
23374};
23375
23376
23377/***************************************************************************
23378** Here ends the I/O methods that form the sqlite3_io_methods object.
23379**
23380** The next block of code implements the VFS methods.
23381****************************************************************************/
23382
23383/*
23384** Create a temporary file name in zBuf.  zBuf must be big enough to
23385** hold at pVfs->mxPathname characters.
23386*/
23387static int getTempname(int nBuf, char *zBuf ){
23388  static const char zChars[] =
23389    "abcdefghijklmnopqrstuvwxyz"
23390    "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
23391    "0123456789";
23392  int i, j;
23393  PSZ zTempPathCp;
23394  char zTempPath[CCHMAXPATH];
23395  ULONG ulDriveNum, ulDriveMap;
23396
23397  /* It's odd to simulate an io-error here, but really this is just
23398  ** using the io-error infrastructure to test that SQLite handles this
23399  ** function failing.
23400  */
23401  SimulateIOError( return SQLITE_IOERR );
23402
23403  if( sqlite3_temp_directory ) {
23404    sqlite3_snprintf(CCHMAXPATH-30, zTempPath, "%s", sqlite3_temp_directory);
23405  } else if( DosScanEnv( (PSZ)"TEMP",   &zTempPathCp ) == NO_ERROR ||
23406             DosScanEnv( (PSZ)"TMP",    &zTempPathCp ) == NO_ERROR ||
23407             DosScanEnv( (PSZ)"TMPDIR", &zTempPathCp ) == NO_ERROR ) {
23408    char *zTempPathUTF = convertCpPathToUtf8( (char *)zTempPathCp );
23409    sqlite3_snprintf(CCHMAXPATH-30, zTempPath, "%s", zTempPathUTF);
23410    free( zTempPathUTF );
23411  } else if( DosQueryCurrentDisk( &ulDriveNum, &ulDriveMap ) == NO_ERROR ) {
23412    zTempPath[0] = (char)('A' + ulDriveNum - 1);
23413    zTempPath[1] = ':';
23414    zTempPath[2] = '\0';
23415  } else {
23416    zTempPath[0] = '\0';
23417  }
23418
23419  /* Strip off a trailing slashes or backslashes, otherwise we would get *
23420   * multiple (back)slashes which causes DosOpen() to fail.              *
23421   * Trailing spaces are not allowed, either.                            */
23422  j = sqlite3Strlen30(zTempPath);
23423  while( j > 0 && ( zTempPath[j-1] == '\\' || zTempPath[j-1] == '/' ||
23424                    zTempPath[j-1] == ' ' ) ){
23425    j--;
23426  }
23427  zTempPath[j] = '\0';
23428
23429  /* We use 20 bytes to randomize the name */
23430  sqlite3_snprintf(nBuf-22, zBuf,
23431                   "%s\\"SQLITE_TEMP_FILE_PREFIX, zTempPath);
23432  j = sqlite3Strlen30(zBuf);
23433  sqlite3_randomness( 20, &zBuf[j] );
23434  for( i = 0; i < 20; i++, j++ ){
23435    zBuf[j] = zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
23436  }
23437  zBuf[j] = 0;
23438
23439  OSTRACE(( "TEMP FILENAME: %s\n", zBuf ));
23440  return SQLITE_OK;
23441}
23442
23443
23444/*
23445** Turn a relative pathname into a full pathname.  Write the full
23446** pathname into zFull[].  zFull[] will be at least pVfs->mxPathname
23447** bytes in size.
23448*/
23449static int os2FullPathname(
23450  sqlite3_vfs *pVfs,          /* Pointer to vfs object */
23451  const char *zRelative,      /* Possibly relative input path */
23452  int nFull,                  /* Size of output buffer in bytes */
23453  char *zFull                 /* Output buffer */
23454){
23455  char *zRelativeCp = convertUtf8PathToCp( zRelative );
23456  char zFullCp[CCHMAXPATH] = "\0";
23457  char *zFullUTF;
23458  APIRET rc = DosQueryPathInfo( (PSZ)zRelativeCp, FIL_QUERYFULLNAME,
23459                                zFullCp, CCHMAXPATH );
23460  free( zRelativeCp );
23461  zFullUTF = convertCpPathToUtf8( zFullCp );
23462  sqlite3_snprintf( nFull, zFull, zFullUTF );
23463  free( zFullUTF );
23464  return rc == NO_ERROR ? SQLITE_OK : SQLITE_IOERR;
23465}
23466
23467
23468/*
23469** Open a file.
23470*/
23471static int os2Open(
23472  sqlite3_vfs *pVfs,            /* Not used */
23473  const char *zName,            /* Name of the file (UTF-8) */
23474  sqlite3_file *id,             /* Write the SQLite file handle here */
23475  int flags,                    /* Open mode flags */
23476  int *pOutFlags                /* Status return flags */
23477){
23478  HFILE h;
23479  ULONG ulOpenFlags = 0;
23480  ULONG ulOpenMode = 0;
23481  ULONG ulAction = 0;
23482  ULONG rc;
23483  os2File *pFile = (os2File*)id;
23484  const char *zUtf8Name = zName;
23485  char *zNameCp;
23486  char  zTmpname[CCHMAXPATH];
23487
23488  int isExclusive  = (flags & SQLITE_OPEN_EXCLUSIVE);
23489  int isCreate     = (flags & SQLITE_OPEN_CREATE);
23490  int isReadWrite  = (flags & SQLITE_OPEN_READWRITE);
23491#ifndef NDEBUG
23492  int isDelete     = (flags & SQLITE_OPEN_DELETEONCLOSE);
23493  int isReadonly   = (flags & SQLITE_OPEN_READONLY);
23494  int eType        = (flags & 0xFFFFFF00);
23495  int isOpenJournal = (isCreate && (
23496        eType==SQLITE_OPEN_MASTER_JOURNAL
23497     || eType==SQLITE_OPEN_MAIN_JOURNAL
23498     || eType==SQLITE_OPEN_WAL
23499  ));
23500#endif
23501
23502  UNUSED_PARAMETER(pVfs);
23503  assert( id!=0 );
23504
23505  /* Check the following statements are true:
23506  **
23507  **   (a) Exactly one of the READWRITE and READONLY flags must be set, and
23508  **   (b) if CREATE is set, then READWRITE must also be set, and
23509  **   (c) if EXCLUSIVE is set, then CREATE must also be set.
23510  **   (d) if DELETEONCLOSE is set, then CREATE must also be set.
23511  */
23512  assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
23513  assert(isCreate==0 || isReadWrite);
23514  assert(isExclusive==0 || isCreate);
23515  assert(isDelete==0 || isCreate);
23516
23517  /* The main DB, main journal, WAL file and master journal are never
23518  ** automatically deleted. Nor are they ever temporary files.  */
23519  assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
23520  assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
23521  assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
23522  assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
23523
23524  /* Assert that the upper layer has set one of the "file-type" flags. */
23525  assert( eType==SQLITE_OPEN_MAIN_DB      || eType==SQLITE_OPEN_TEMP_DB
23526       || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
23527       || eType==SQLITE_OPEN_SUBJOURNAL   || eType==SQLITE_OPEN_MASTER_JOURNAL
23528       || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
23529  );
23530
23531  memset( pFile, 0, sizeof(*pFile) );
23532  pFile->h = (HFILE)-1;
23533
23534  /* If the second argument to this function is NULL, generate a
23535  ** temporary file name to use
23536  */
23537  if( !zUtf8Name ){
23538    assert(isDelete && !isOpenJournal);
23539    rc = getTempname(CCHMAXPATH, zTmpname);
23540    if( rc!=SQLITE_OK ){
23541      return rc;
23542    }
23543    zUtf8Name = zTmpname;
23544  }
23545
23546  if( isReadWrite ){
23547    ulOpenMode |= OPEN_ACCESS_READWRITE;
23548  }else{
23549    ulOpenMode |= OPEN_ACCESS_READONLY;
23550  }
23551
23552  /* Open in random access mode for possibly better speed.  Allow full
23553  ** sharing because file locks will provide exclusive access when needed.
23554  ** The handle should not be inherited by child processes and we don't
23555  ** want popups from the critical error handler.
23556  */
23557  ulOpenMode |= OPEN_FLAGS_RANDOM | OPEN_SHARE_DENYNONE |
23558                OPEN_FLAGS_NOINHERIT | OPEN_FLAGS_FAIL_ON_ERROR;
23559
23560  /* SQLITE_OPEN_EXCLUSIVE is used to make sure that a new file is
23561  ** created. SQLite doesn't use it to indicate "exclusive access"
23562  ** as it is usually understood.
23563  */
23564  if( isExclusive ){
23565    /* Creates a new file, only if it does not already exist. */
23566    /* If the file exists, it fails. */
23567    ulOpenFlags |= OPEN_ACTION_CREATE_IF_NEW | OPEN_ACTION_FAIL_IF_EXISTS;
23568  }else if( isCreate ){
23569    /* Open existing file, or create if it doesn't exist */
23570    ulOpenFlags |= OPEN_ACTION_CREATE_IF_NEW | OPEN_ACTION_OPEN_IF_EXISTS;
23571  }else{
23572    /* Opens a file, only if it exists. */
23573    ulOpenFlags |= OPEN_ACTION_FAIL_IF_NEW | OPEN_ACTION_OPEN_IF_EXISTS;
23574  }
23575
23576  zNameCp = convertUtf8PathToCp( zUtf8Name );
23577  rc = DosOpen( (PSZ)zNameCp,
23578                &h,
23579                &ulAction,
23580                0L,
23581                FILE_NORMAL,
23582                ulOpenFlags,
23583                ulOpenMode,
23584                (PEAOP2)NULL );
23585  free( zNameCp );
23586
23587  if( rc != NO_ERROR ){
23588    OSTRACE(( "OPEN Invalid handle rc=%d: zName=%s, ulAction=%#lx, ulFlags=%#lx, ulMode=%#lx\n",
23589              rc, zUtf8Name, ulAction, ulOpenFlags, ulOpenMode ));
23590
23591    if( isReadWrite ){
23592      return os2Open( pVfs, zName, id,
23593                      ((flags|SQLITE_OPEN_READONLY)&~(SQLITE_OPEN_CREATE|SQLITE_OPEN_READWRITE)),
23594                      pOutFlags );
23595    }else{
23596      return SQLITE_CANTOPEN;
23597    }
23598  }
23599
23600  if( pOutFlags ){
23601    *pOutFlags = isReadWrite ? SQLITE_OPEN_READWRITE : SQLITE_OPEN_READONLY;
23602  }
23603
23604  os2FullPathname( pVfs, zUtf8Name, sizeof( zTmpname ), zTmpname );
23605  pFile->zFullPathCp = convertUtf8PathToCp( zTmpname );
23606  pFile->pMethod = &os2IoMethod;
23607  pFile->flags = flags;
23608  pFile->h = h;
23609
23610  OpenCounter(+1);
23611  OSTRACE(( "OPEN %d pOutFlags=%d\n", pFile->h, pOutFlags ));
23612  return SQLITE_OK;
23613}
23614
23615/*
23616** Delete the named file.
23617*/
23618static int os2Delete(
23619  sqlite3_vfs *pVfs,                     /* Not used on os2 */
23620  const char *zFilename,                 /* Name of file to delete */
23621  int syncDir                            /* Not used on os2 */
23622){
23623  APIRET rc;
23624  char *zFilenameCp;
23625  SimulateIOError( return SQLITE_IOERR_DELETE );
23626  zFilenameCp = convertUtf8PathToCp( zFilename );
23627  rc = DosDelete( (PSZ)zFilenameCp );
23628  free( zFilenameCp );
23629  OSTRACE(( "DELETE \"%s\"\n", zFilename ));
23630  return (rc == NO_ERROR ||
23631          rc == ERROR_FILE_NOT_FOUND ||
23632          rc == ERROR_PATH_NOT_FOUND ) ? SQLITE_OK : SQLITE_IOERR_DELETE;
23633}
23634
23635/*
23636** Check the existance and status of a file.
23637*/
23638static int os2Access(
23639  sqlite3_vfs *pVfs,        /* Not used on os2 */
23640  const char *zFilename,    /* Name of file to check */
23641  int flags,                /* Type of test to make on this file */
23642  int *pOut                 /* Write results here */
23643){
23644  APIRET rc;
23645  FILESTATUS3 fsts3ConfigInfo;
23646  char *zFilenameCp;
23647
23648  UNUSED_PARAMETER(pVfs);
23649  SimulateIOError( return SQLITE_IOERR_ACCESS; );
23650
23651  zFilenameCp = convertUtf8PathToCp( zFilename );
23652  rc = DosQueryPathInfo( (PSZ)zFilenameCp, FIL_STANDARD,
23653                         &fsts3ConfigInfo, sizeof(FILESTATUS3) );
23654  free( zFilenameCp );
23655  OSTRACE(( "ACCESS fsts3ConfigInfo.attrFile=%d flags=%d rc=%d\n",
23656            fsts3ConfigInfo.attrFile, flags, rc ));
23657
23658  switch( flags ){
23659    case SQLITE_ACCESS_EXISTS:
23660      /* For an SQLITE_ACCESS_EXISTS query, treat a zero-length file
23661      ** as if it does not exist.
23662      */
23663      if( fsts3ConfigInfo.cbFile == 0 )
23664        rc = ERROR_FILE_NOT_FOUND;
23665      break;
23666    case SQLITE_ACCESS_READ:
23667      break;
23668    case SQLITE_ACCESS_READWRITE:
23669      if( fsts3ConfigInfo.attrFile & FILE_READONLY )
23670        rc = ERROR_ACCESS_DENIED;
23671      break;
23672    default:
23673      rc = ERROR_FILE_NOT_FOUND;
23674      assert( !"Invalid flags argument" );
23675  }
23676
23677  *pOut = (rc == NO_ERROR);
23678  OSTRACE(( "ACCESS %s flags %d: rc=%d\n", zFilename, flags, *pOut ));
23679
23680  return SQLITE_OK;
23681}
23682
23683
23684#ifndef SQLITE_OMIT_LOAD_EXTENSION
23685/*
23686** Interfaces for opening a shared library, finding entry points
23687** within the shared library, and closing the shared library.
23688*/
23689/*
23690** Interfaces for opening a shared library, finding entry points
23691** within the shared library, and closing the shared library.
23692*/
23693static void *os2DlOpen(sqlite3_vfs *pVfs, const char *zFilename){
23694  HMODULE hmod;
23695  APIRET rc;
23696  char *zFilenameCp = convertUtf8PathToCp(zFilename);
23697  rc = DosLoadModule(NULL, 0, (PSZ)zFilenameCp, &hmod);
23698  free(zFilenameCp);
23699  return rc != NO_ERROR ? 0 : (void*)hmod;
23700}
23701/*
23702** A no-op since the error code is returned on the DosLoadModule call.
23703** os2Dlopen returns zero if DosLoadModule is not successful.
23704*/
23705static void os2DlError(sqlite3_vfs *pVfs, int nBuf, char *zBufOut){
23706/* no-op */
23707}
23708static void (*os2DlSym(sqlite3_vfs *pVfs, void *pHandle, const char *zSymbol))(void){
23709  PFN pfn;
23710  APIRET rc;
23711  rc = DosQueryProcAddr((HMODULE)pHandle, 0L, (PSZ)zSymbol, &pfn);
23712  if( rc != NO_ERROR ){
23713    /* if the symbol itself was not found, search again for the same
23714     * symbol with an extra underscore, that might be needed depending
23715     * on the calling convention */
23716    char _zSymbol[256] = "_";
23717    strncat(_zSymbol, zSymbol, 254);
23718    rc = DosQueryProcAddr((HMODULE)pHandle, 0L, (PSZ)_zSymbol, &pfn);
23719  }
23720  return rc != NO_ERROR ? 0 : (void(*)(void))pfn;
23721}
23722static void os2DlClose(sqlite3_vfs *pVfs, void *pHandle){
23723  DosFreeModule((HMODULE)pHandle);
23724}
23725#else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
23726  #define os2DlOpen 0
23727  #define os2DlError 0
23728  #define os2DlSym 0
23729  #define os2DlClose 0
23730#endif
23731
23732
23733/*
23734** Write up to nBuf bytes of randomness into zBuf.
23735*/
23736static int os2Randomness(sqlite3_vfs *pVfs, int nBuf, char *zBuf ){
23737  int n = 0;
23738#if defined(SQLITE_TEST)
23739  n = nBuf;
23740  memset(zBuf, 0, nBuf);
23741#else
23742  int i;
23743  PPIB ppib;
23744  PTIB ptib;
23745  DATETIME dt;
23746  static unsigned c = 0;
23747  /* Ordered by variation probability */
23748  static ULONG svIdx[6] = { QSV_MS_COUNT, QSV_TIME_LOW,
23749                            QSV_MAXPRMEM, QSV_MAXSHMEM,
23750                            QSV_TOTAVAILMEM, QSV_TOTRESMEM };
23751
23752  /* 8 bytes; timezone and weekday don't increase the randomness much */
23753  if( (int)sizeof(dt)-3 <= nBuf - n ){
23754    c += 0x0100;
23755    DosGetDateTime(&dt);
23756    dt.year = (USHORT)((dt.year - 1900) | c);
23757    memcpy(&zBuf[n], &dt, sizeof(dt)-3);
23758    n += sizeof(dt)-3;
23759  }
23760
23761  /* 4 bytes; PIDs and TIDs are 16 bit internally, so combine them */
23762  if( (int)sizeof(ULONG) <= nBuf - n ){
23763    DosGetInfoBlocks(&ptib, &ppib);
23764    *(PULONG)&zBuf[n] = MAKELONG(ppib->pib_ulpid,
23765                                 ptib->tib_ptib2->tib2_ultid);
23766    n += sizeof(ULONG);
23767  }
23768
23769  /* Up to 6 * 4 bytes; variables depend on the system state */
23770  for( i = 0; i < 6 && (int)sizeof(ULONG) <= nBuf - n; i++ ){
23771    DosQuerySysInfo(svIdx[i], svIdx[i],
23772                    (PULONG)&zBuf[n], sizeof(ULONG));
23773    n += sizeof(ULONG);
23774  }
23775#endif
23776
23777  return n;
23778}
23779
23780/*
23781** Sleep for a little while.  Return the amount of time slept.
23782** The argument is the number of microseconds we want to sleep.
23783** The return value is the number of microseconds of sleep actually
23784** requested from the underlying operating system, a number which
23785** might be greater than or equal to the argument, but not less
23786** than the argument.
23787*/
23788static int os2Sleep( sqlite3_vfs *pVfs, int microsec ){
23789  DosSleep( (microsec/1000) );
23790  return microsec;
23791}
23792
23793/*
23794** The following variable, if set to a non-zero value, becomes the result
23795** returned from sqlite3OsCurrentTime().  This is used for testing.
23796*/
23797#ifdef SQLITE_TEST
23798SQLITE_API int sqlite3_current_time = 0;
23799#endif
23800
23801/*
23802** Find the current time (in Universal Coordinated Time).  Write into *piNow
23803** the current time and date as a Julian Day number times 86_400_000.  In
23804** other words, write into *piNow the number of milliseconds since the Julian
23805** epoch of noon in Greenwich on November 24, 4714 B.C according to the
23806** proleptic Gregorian calendar.
23807**
23808** On success, return 0.  Return 1 if the time and date cannot be found.
23809*/
23810static int os2CurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *piNow){
23811#ifdef SQLITE_TEST
23812  static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
23813#endif
23814  int year, month, datepart, timepart;
23815
23816  DATETIME dt;
23817  DosGetDateTime( &dt );
23818
23819  year = dt.year;
23820  month = dt.month;
23821
23822  /* Calculations from http://www.astro.keele.ac.uk/~rno/Astronomy/hjd.html
23823  ** http://www.astro.keele.ac.uk/~rno/Astronomy/hjd-0.1.c
23824  ** Calculate the Julian days
23825  */
23826  datepart = (int)dt.day - 32076 +
23827    1461*(year + 4800 + (month - 14)/12)/4 +
23828    367*(month - 2 - (month - 14)/12*12)/12 -
23829    3*((year + 4900 + (month - 14)/12)/100)/4;
23830
23831  /* Time in milliseconds, hours to noon added */
23832  timepart = 12*3600*1000 + dt.hundredths*10 + dt.seconds*1000 +
23833    ((int)dt.minutes + dt.timezone)*60*1000 + dt.hours*3600*1000;
23834
23835  *piNow = (sqlite3_int64)datepart*86400*1000 + timepart;
23836
23837#ifdef SQLITE_TEST
23838  if( sqlite3_current_time ){
23839    *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
23840  }
23841#endif
23842
23843  UNUSED_PARAMETER(pVfs);
23844  return 0;
23845}
23846
23847/*
23848** Find the current time (in Universal Coordinated Time).  Write the
23849** current time and date as a Julian Day number into *prNow and
23850** return 0.  Return 1 if the time and date cannot be found.
23851*/
23852static int os2CurrentTime( sqlite3_vfs *pVfs, double *prNow ){
23853  int rc;
23854  sqlite3_int64 i;
23855  rc = os2CurrentTimeInt64(pVfs, &i);
23856  if( !rc ){
23857    *prNow = i/86400000.0;
23858  }
23859  return rc;
23860}
23861
23862/*
23863** The idea is that this function works like a combination of
23864** GetLastError() and FormatMessage() on windows (or errno and
23865** strerror_r() on unix). After an error is returned by an OS
23866** function, SQLite calls this function with zBuf pointing to
23867** a buffer of nBuf bytes. The OS layer should populate the
23868** buffer with a nul-terminated UTF-8 encoded error message
23869** describing the last IO error to have occurred within the calling
23870** thread.
23871**
23872** If the error message is too large for the supplied buffer,
23873** it should be truncated. The return value of xGetLastError
23874** is zero if the error message fits in the buffer, or non-zero
23875** otherwise (if the message was truncated). If non-zero is returned,
23876** then it is not necessary to include the nul-terminator character
23877** in the output buffer.
23878**
23879** Not supplying an error message will have no adverse effect
23880** on SQLite. It is fine to have an implementation that never
23881** returns an error message:
23882**
23883**   int xGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
23884**     assert(zBuf[0]=='\0');
23885**     return 0;
23886**   }
23887**
23888** However if an error message is supplied, it will be incorporated
23889** by sqlite into the error message available to the user using
23890** sqlite3_errmsg(), possibly making IO errors easier to debug.
23891*/
23892static int os2GetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
23893  assert(zBuf[0]=='\0');
23894  return 0;
23895}
23896
23897/*
23898** Initialize and deinitialize the operating system interface.
23899*/
23900SQLITE_API int sqlite3_os_init(void){
23901  static sqlite3_vfs os2Vfs = {
23902    3,                 /* iVersion */
23903    sizeof(os2File),   /* szOsFile */
23904    CCHMAXPATH,        /* mxPathname */
23905    0,                 /* pNext */
23906    "os2",             /* zName */
23907    0,                 /* pAppData */
23908
23909    os2Open,           /* xOpen */
23910    os2Delete,         /* xDelete */
23911    os2Access,         /* xAccess */
23912    os2FullPathname,   /* xFullPathname */
23913    os2DlOpen,         /* xDlOpen */
23914    os2DlError,        /* xDlError */
23915    os2DlSym,          /* xDlSym */
23916    os2DlClose,        /* xDlClose */
23917    os2Randomness,     /* xRandomness */
23918    os2Sleep,          /* xSleep */
23919    os2CurrentTime,    /* xCurrentTime */
23920    os2GetLastError,   /* xGetLastError */
23921    os2CurrentTimeInt64, /* xCurrentTimeInt64 */
23922    0,                 /* xSetSystemCall */
23923    0,                 /* xGetSystemCall */
23924    0                  /* xNextSystemCall */
23925  };
23926  sqlite3_vfs_register(&os2Vfs, 1);
23927  initUconvObjects();
23928/*  sqlite3OSTrace = 1; */
23929  return SQLITE_OK;
23930}
23931SQLITE_API int sqlite3_os_end(void){
23932  freeUconvObjects();
23933  return SQLITE_OK;
23934}
23935
23936#endif /* SQLITE_OS_OS2 */
23937
23938/************** End of os_os2.c **********************************************/
23939/************** Begin file os_unix.c *****************************************/
23940/*
23941** 2004 May 22
23942**
23943** The author disclaims copyright to this source code.  In place of
23944** a legal notice, here is a blessing:
23945**
23946**    May you do good and not evil.
23947**    May you find forgiveness for yourself and forgive others.
23948**    May you share freely, never taking more than you give.
23949**
23950******************************************************************************
23951**
23952** This file contains the VFS implementation for unix-like operating systems
23953** include Linux, MacOSX, *BSD, QNX, VxWorks, AIX, HPUX, and others.
23954**
23955** There are actually several different VFS implementations in this file.
23956** The differences are in the way that file locking is done.  The default
23957** implementation uses Posix Advisory Locks.  Alternative implementations
23958** use flock(), dot-files, various proprietary locking schemas, or simply
23959** skip locking all together.
23960**
23961** This source file is organized into divisions where the logic for various
23962** subfunctions is contained within the appropriate division.  PLEASE
23963** KEEP THE STRUCTURE OF THIS FILE INTACT.  New code should be placed
23964** in the correct division and should be clearly labeled.
23965**
23966** The layout of divisions is as follows:
23967**
23968**   *  General-purpose declarations and utility functions.
23969**   *  Unique file ID logic used by VxWorks.
23970**   *  Various locking primitive implementations (all except proxy locking):
23971**      + for Posix Advisory Locks
23972**      + for no-op locks
23973**      + for dot-file locks
23974**      + for flock() locking
23975**      + for named semaphore locks (VxWorks only)
23976**      + for AFP filesystem locks (MacOSX only)
23977**   *  sqlite3_file methods not associated with locking.
23978**   *  Definitions of sqlite3_io_methods objects for all locking
23979**      methods plus "finder" functions for each locking method.
23980**   *  sqlite3_vfs method implementations.
23981**   *  Locking primitives for the proxy uber-locking-method. (MacOSX only)
23982**   *  Definitions of sqlite3_vfs objects for all locking methods
23983**      plus implementations of sqlite3_os_init() and sqlite3_os_end().
23984*/
23985#if SQLITE_OS_UNIX              /* This file is used on unix only */
23986
23987/*
23988** There are various methods for file locking used for concurrency
23989** control:
23990**
23991**   1. POSIX locking (the default),
23992**   2. No locking,
23993**   3. Dot-file locking,
23994**   4. flock() locking,
23995**   5. AFP locking (OSX only),
23996**   6. Named POSIX semaphores (VXWorks only),
23997**   7. proxy locking. (OSX only)
23998**
23999** Styles 4, 5, and 7 are only available of SQLITE_ENABLE_LOCKING_STYLE
24000** is defined to 1.  The SQLITE_ENABLE_LOCKING_STYLE also enables automatic
24001** selection of the appropriate locking style based on the filesystem
24002** where the database is located.
24003*/
24004#if !defined(SQLITE_ENABLE_LOCKING_STYLE)
24005#  if defined(__APPLE__)
24006#    define SQLITE_ENABLE_LOCKING_STYLE 1
24007#  else
24008#    define SQLITE_ENABLE_LOCKING_STYLE 0
24009#  endif
24010#endif
24011
24012/*
24013** Define the OS_VXWORKS pre-processor macro to 1 if building on
24014** vxworks, or 0 otherwise.
24015*/
24016#ifndef OS_VXWORKS
24017#  if defined(__RTP__) || defined(_WRS_KERNEL)
24018#    define OS_VXWORKS 1
24019#  else
24020#    define OS_VXWORKS 0
24021#  endif
24022#endif
24023
24024/*
24025** These #defines should enable >2GB file support on Posix if the
24026** underlying operating system supports it.  If the OS lacks
24027** large file support, these should be no-ops.
24028**
24029** Large file support can be disabled using the -DSQLITE_DISABLE_LFS switch
24030** on the compiler command line.  This is necessary if you are compiling
24031** on a recent machine (ex: RedHat 7.2) but you want your code to work
24032** on an older machine (ex: RedHat 6.0).  If you compile on RedHat 7.2
24033** without this option, LFS is enable.  But LFS does not exist in the kernel
24034** in RedHat 6.0, so the code won't work.  Hence, for maximum binary
24035** portability you should omit LFS.
24036**
24037** The previous paragraph was written in 2005.  (This paragraph is written
24038** on 2008-11-28.) These days, all Linux kernels support large files, so
24039** you should probably leave LFS enabled.  But some embedded platforms might
24040** lack LFS in which case the SQLITE_DISABLE_LFS macro might still be useful.
24041*/
24042#ifndef SQLITE_DISABLE_LFS
24043# define _LARGE_FILE       1
24044# ifndef _FILE_OFFSET_BITS
24045#   define _FILE_OFFSET_BITS 64
24046# endif
24047# define _LARGEFILE_SOURCE 1
24048#endif
24049
24050/*
24051** standard include files.
24052*/
24053#include <sys/types.h>
24054#include <sys/stat.h>
24055#include <fcntl.h>
24056#include <unistd.h>
24057#include <sys/time.h>
24058#include <errno.h>
24059#ifndef SQLITE_OMIT_WAL
24060#include <sys/mman.h>
24061#endif
24062
24063#if SQLITE_ENABLE_LOCKING_STYLE
24064# include <sys/ioctl.h>
24065# if OS_VXWORKS
24066#  include <semaphore.h>
24067#  include <limits.h>
24068# else
24069#  include <sys/file.h>
24070#  include <sys/param.h>
24071# endif
24072#endif /* SQLITE_ENABLE_LOCKING_STYLE */
24073
24074#if defined(__APPLE__) || (SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS)
24075# include <sys/mount.h>
24076#endif
24077
24078/*
24079** Allowed values of unixFile.fsFlags
24080*/
24081#define SQLITE_FSFLAGS_IS_MSDOS     0x1
24082
24083/*
24084** If we are to be thread-safe, include the pthreads header and define
24085** the SQLITE_UNIX_THREADS macro.
24086*/
24087#if SQLITE_THREADSAFE
24088# define SQLITE_UNIX_THREADS 1
24089#endif
24090
24091/*
24092** Default permissions when creating a new file
24093*/
24094#ifndef SQLITE_DEFAULT_FILE_PERMISSIONS
24095# define SQLITE_DEFAULT_FILE_PERMISSIONS 0644
24096#endif
24097
24098/*
24099 ** Default permissions when creating auto proxy dir
24100 */
24101#ifndef SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
24102# define SQLITE_DEFAULT_PROXYDIR_PERMISSIONS 0755
24103#endif
24104
24105/*
24106** Maximum supported path-length.
24107*/
24108#define MAX_PATHNAME 512
24109
24110/*
24111** Only set the lastErrno if the error code is a real error and not
24112** a normal expected return code of SQLITE_BUSY or SQLITE_OK
24113*/
24114#define IS_LOCK_ERROR(x)  ((x != SQLITE_OK) && (x != SQLITE_BUSY))
24115
24116/* Forward references */
24117typedef struct unixShm unixShm;               /* Connection shared memory */
24118typedef struct unixShmNode unixShmNode;       /* Shared memory instance */
24119typedef struct unixInodeInfo unixInodeInfo;   /* An i-node */
24120typedef struct UnixUnusedFd UnixUnusedFd;     /* An unused file descriptor */
24121
24122/*
24123** Sometimes, after a file handle is closed by SQLite, the file descriptor
24124** cannot be closed immediately. In these cases, instances of the following
24125** structure are used to store the file descriptor while waiting for an
24126** opportunity to either close or reuse it.
24127*/
24128struct UnixUnusedFd {
24129  int fd;                   /* File descriptor to close */
24130  int flags;                /* Flags this file descriptor was opened with */
24131  UnixUnusedFd *pNext;      /* Next unused file descriptor on same file */
24132};
24133
24134/*
24135** The unixFile structure is subclass of sqlite3_file specific to the unix
24136** VFS implementations.
24137*/
24138typedef struct unixFile unixFile;
24139struct unixFile {
24140  sqlite3_io_methods const *pMethod;  /* Always the first entry */
24141  unixInodeInfo *pInode;              /* Info about locks on this inode */
24142  int h;                              /* The file descriptor */
24143  unsigned char eFileLock;            /* The type of lock held on this fd */
24144  unsigned char ctrlFlags;            /* Behavioral bits.  UNIXFILE_* flags */
24145  int lastErrno;                      /* The unix errno from last I/O error */
24146  void *lockingContext;               /* Locking style specific state */
24147  UnixUnusedFd *pUnused;              /* Pre-allocated UnixUnusedFd */
24148  const char *zPath;                  /* Name of the file */
24149  unixShm *pShm;                      /* Shared memory segment information */
24150  int szChunk;                        /* Configured by FCNTL_CHUNK_SIZE */
24151#if SQLITE_ENABLE_LOCKING_STYLE
24152  int openFlags;                      /* The flags specified at open() */
24153#endif
24154#if SQLITE_ENABLE_LOCKING_STYLE || defined(__APPLE__)
24155  unsigned fsFlags;                   /* cached details from statfs() */
24156#endif
24157#if OS_VXWORKS
24158  int isDelete;                       /* Delete on close if true */
24159  struct vxworksFileId *pId;          /* Unique file ID */
24160#endif
24161#ifndef NDEBUG
24162  /* The next group of variables are used to track whether or not the
24163  ** transaction counter in bytes 24-27 of database files are updated
24164  ** whenever any part of the database changes.  An assertion fault will
24165  ** occur if a file is updated without also updating the transaction
24166  ** counter.  This test is made to avoid new problems similar to the
24167  ** one described by ticket #3584.
24168  */
24169  unsigned char transCntrChng;   /* True if the transaction counter changed */
24170  unsigned char dbUpdate;        /* True if any part of database file changed */
24171  unsigned char inNormalWrite;   /* True if in a normal write operation */
24172#endif
24173#ifdef SQLITE_TEST
24174  /* In test mode, increase the size of this structure a bit so that
24175  ** it is larger than the struct CrashFile defined in test6.c.
24176  */
24177  char aPadding[32];
24178#endif
24179};
24180
24181/*
24182** Allowed values for the unixFile.ctrlFlags bitmask:
24183*/
24184#define UNIXFILE_EXCL   0x01     /* Connections from one process only */
24185#define UNIXFILE_RDONLY 0x02     /* Connection is read only */
24186#define UNIXFILE_DIRSYNC 0x04    /* Directory sync needed */
24187
24188/*
24189** Include code that is common to all os_*.c files
24190*/
24191/************** Include os_common.h in the middle of os_unix.c ***************/
24192/************** Begin file os_common.h ***************************************/
24193/*
24194** 2004 May 22
24195**
24196** The author disclaims copyright to this source code.  In place of
24197** a legal notice, here is a blessing:
24198**
24199**    May you do good and not evil.
24200**    May you find forgiveness for yourself and forgive others.
24201**    May you share freely, never taking more than you give.
24202**
24203******************************************************************************
24204**
24205** This file contains macros and a little bit of code that is common to
24206** all of the platform-specific files (os_*.c) and is #included into those
24207** files.
24208**
24209** This file should be #included by the os_*.c files only.  It is not a
24210** general purpose header file.
24211*/
24212#ifndef _OS_COMMON_H_
24213#define _OS_COMMON_H_
24214
24215/*
24216** At least two bugs have slipped in because we changed the MEMORY_DEBUG
24217** macro to SQLITE_DEBUG and some older makefiles have not yet made the
24218** switch.  The following code should catch this problem at compile-time.
24219*/
24220#ifdef MEMORY_DEBUG
24221# error "The MEMORY_DEBUG macro is obsolete.  Use SQLITE_DEBUG instead."
24222#endif
24223
24224#ifdef SQLITE_DEBUG
24225SQLITE_PRIVATE int sqlite3OSTrace = 0;
24226#define OSTRACE(X)          if( sqlite3OSTrace ) sqlite3DebugPrintf X
24227#else
24228#define OSTRACE(X)
24229#endif
24230
24231/*
24232** Macros for performance tracing.  Normally turned off.  Only works
24233** on i486 hardware.
24234*/
24235#ifdef SQLITE_PERFORMANCE_TRACE
24236
24237/*
24238** hwtime.h contains inline assembler code for implementing
24239** high-performance timing routines.
24240*/
24241/************** Include hwtime.h in the middle of os_common.h ****************/
24242/************** Begin file hwtime.h ******************************************/
24243/*
24244** 2008 May 27
24245**
24246** The author disclaims copyright to this source code.  In place of
24247** a legal notice, here is a blessing:
24248**
24249**    May you do good and not evil.
24250**    May you find forgiveness for yourself and forgive others.
24251**    May you share freely, never taking more than you give.
24252**
24253******************************************************************************
24254**
24255** This file contains inline asm code for retrieving "high-performance"
24256** counters for x86 class CPUs.
24257*/
24258#ifndef _HWTIME_H_
24259#define _HWTIME_H_
24260
24261/*
24262** The following routine only works on pentium-class (or newer) processors.
24263** It uses the RDTSC opcode to read the cycle count value out of the
24264** processor and returns that value.  This can be used for high-res
24265** profiling.
24266*/
24267#if (defined(__GNUC__) || defined(_MSC_VER)) && \
24268      (defined(i386) || defined(__i386__) || defined(_M_IX86))
24269
24270  #if defined(__GNUC__)
24271
24272  __inline__ sqlite_uint64 sqlite3Hwtime(void){
24273     unsigned int lo, hi;
24274     __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
24275     return (sqlite_uint64)hi << 32 | lo;
24276  }
24277
24278  #elif defined(_MSC_VER)
24279
24280  __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
24281     __asm {
24282        rdtsc
24283        ret       ; return value at EDX:EAX
24284     }
24285  }
24286
24287  #endif
24288
24289#elif (defined(__GNUC__) && defined(__x86_64__))
24290
24291  __inline__ sqlite_uint64 sqlite3Hwtime(void){
24292      unsigned long val;
24293      __asm__ __volatile__ ("rdtsc" : "=A" (val));
24294      return val;
24295  }
24296
24297#elif (defined(__GNUC__) && defined(__ppc__))
24298
24299  __inline__ sqlite_uint64 sqlite3Hwtime(void){
24300      unsigned long long retval;
24301      unsigned long junk;
24302      __asm__ __volatile__ ("\n\
24303          1:      mftbu   %1\n\
24304                  mftb    %L0\n\
24305                  mftbu   %0\n\
24306                  cmpw    %0,%1\n\
24307                  bne     1b"
24308                  : "=r" (retval), "=r" (junk));
24309      return retval;
24310  }
24311
24312#else
24313
24314  #error Need implementation of sqlite3Hwtime() for your platform.
24315
24316  /*
24317  ** To compile without implementing sqlite3Hwtime() for your platform,
24318  ** you can remove the above #error and use the following
24319  ** stub function.  You will lose timing support for many
24320  ** of the debugging and testing utilities, but it should at
24321  ** least compile and run.
24322  */
24323SQLITE_PRIVATE   sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
24324
24325#endif
24326
24327#endif /* !defined(_HWTIME_H_) */
24328
24329/************** End of hwtime.h **********************************************/
24330/************** Continuing where we left off in os_common.h ******************/
24331
24332static sqlite_uint64 g_start;
24333static sqlite_uint64 g_elapsed;
24334#define TIMER_START       g_start=sqlite3Hwtime()
24335#define TIMER_END         g_elapsed=sqlite3Hwtime()-g_start
24336#define TIMER_ELAPSED     g_elapsed
24337#else
24338#define TIMER_START
24339#define TIMER_END
24340#define TIMER_ELAPSED     ((sqlite_uint64)0)
24341#endif
24342
24343/*
24344** If we compile with the SQLITE_TEST macro set, then the following block
24345** of code will give us the ability to simulate a disk I/O error.  This
24346** is used for testing the I/O recovery logic.
24347*/
24348#ifdef SQLITE_TEST
24349SQLITE_API int sqlite3_io_error_hit = 0;            /* Total number of I/O Errors */
24350SQLITE_API int sqlite3_io_error_hardhit = 0;        /* Number of non-benign errors */
24351SQLITE_API int sqlite3_io_error_pending = 0;        /* Count down to first I/O error */
24352SQLITE_API int sqlite3_io_error_persist = 0;        /* True if I/O errors persist */
24353SQLITE_API int sqlite3_io_error_benign = 0;         /* True if errors are benign */
24354SQLITE_API int sqlite3_diskfull_pending = 0;
24355SQLITE_API int sqlite3_diskfull = 0;
24356#define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
24357#define SimulateIOError(CODE)  \
24358  if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
24359       || sqlite3_io_error_pending-- == 1 )  \
24360              { local_ioerr(); CODE; }
24361static void local_ioerr(){
24362  IOTRACE(("IOERR\n"));
24363  sqlite3_io_error_hit++;
24364  if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
24365}
24366#define SimulateDiskfullError(CODE) \
24367   if( sqlite3_diskfull_pending ){ \
24368     if( sqlite3_diskfull_pending == 1 ){ \
24369       local_ioerr(); \
24370       sqlite3_diskfull = 1; \
24371       sqlite3_io_error_hit = 1; \
24372       CODE; \
24373     }else{ \
24374       sqlite3_diskfull_pending--; \
24375     } \
24376   }
24377#else
24378#define SimulateIOErrorBenign(X)
24379#define SimulateIOError(A)
24380#define SimulateDiskfullError(A)
24381#endif
24382
24383/*
24384** When testing, keep a count of the number of open files.
24385*/
24386#ifdef SQLITE_TEST
24387SQLITE_API int sqlite3_open_file_count = 0;
24388#define OpenCounter(X)  sqlite3_open_file_count+=(X)
24389#else
24390#define OpenCounter(X)
24391#endif
24392
24393#endif /* !defined(_OS_COMMON_H_) */
24394
24395/************** End of os_common.h *******************************************/
24396/************** Continuing where we left off in os_unix.c ********************/
24397
24398/*
24399** Define various macros that are missing from some systems.
24400*/
24401#ifndef O_LARGEFILE
24402# define O_LARGEFILE 0
24403#endif
24404#ifdef SQLITE_DISABLE_LFS
24405# undef O_LARGEFILE
24406# define O_LARGEFILE 0
24407#endif
24408#ifndef O_NOFOLLOW
24409# define O_NOFOLLOW 0
24410#endif
24411#ifndef O_BINARY
24412# define O_BINARY 0
24413#endif
24414
24415/*
24416** The threadid macro resolves to the thread-id or to 0.  Used for
24417** testing and debugging only.
24418*/
24419#if SQLITE_THREADSAFE
24420#define threadid pthread_self()
24421#else
24422#define threadid 0
24423#endif
24424
24425/* Forward reference */
24426static int openDirectory(const char*, int*);
24427
24428/*
24429** Many system calls are accessed through pointer-to-functions so that
24430** they may be overridden at runtime to facilitate fault injection during
24431** testing and sandboxing.  The following array holds the names and pointers
24432** to all overrideable system calls.
24433*/
24434static struct unix_syscall {
24435  const char *zName;            /* Name of the sytem call */
24436  sqlite3_syscall_ptr pCurrent; /* Current value of the system call */
24437  sqlite3_syscall_ptr pDefault; /* Default value */
24438} aSyscall[] = {
24439  { "open",         (sqlite3_syscall_ptr)open,       0  },
24440#define osOpen      ((int(*)(const char*,int,...))aSyscall[0].pCurrent)
24441
24442  { "close",        (sqlite3_syscall_ptr)close,      0  },
24443#define osClose     ((int(*)(int))aSyscall[1].pCurrent)
24444
24445  { "access",       (sqlite3_syscall_ptr)access,     0  },
24446#define osAccess    ((int(*)(const char*,int))aSyscall[2].pCurrent)
24447
24448  { "getcwd",       (sqlite3_syscall_ptr)getcwd,     0  },
24449#define osGetcwd    ((char*(*)(char*,size_t))aSyscall[3].pCurrent)
24450
24451  { "stat",         (sqlite3_syscall_ptr)stat,       0  },
24452#define osStat      ((int(*)(const char*,struct stat*))aSyscall[4].pCurrent)
24453
24454/*
24455** The DJGPP compiler environment looks mostly like Unix, but it
24456** lacks the fcntl() system call.  So redefine fcntl() to be something
24457** that always succeeds.  This means that locking does not occur under
24458** DJGPP.  But it is DOS - what did you expect?
24459*/
24460#ifdef __DJGPP__
24461  { "fstat",        0,                 0  },
24462#define osFstat(a,b,c)    0
24463#else
24464  { "fstat",        (sqlite3_syscall_ptr)fstat,      0  },
24465#define osFstat     ((int(*)(int,struct stat*))aSyscall[5].pCurrent)
24466#endif
24467
24468  { "ftruncate",    (sqlite3_syscall_ptr)ftruncate,  0  },
24469#define osFtruncate ((int(*)(int,off_t))aSyscall[6].pCurrent)
24470
24471  { "fcntl",        (sqlite3_syscall_ptr)fcntl,      0  },
24472#define osFcntl     ((int(*)(int,int,...))aSyscall[7].pCurrent)
24473
24474  { "read",         (sqlite3_syscall_ptr)read,       0  },
24475#define osRead      ((ssize_t(*)(int,void*,size_t))aSyscall[8].pCurrent)
24476
24477#if defined(USE_PREAD) || defined(SQLITE_ENABLE_LOCKING_STYLE)
24478  { "pread",        (sqlite3_syscall_ptr)pread,      0  },
24479#else
24480  { "pread",        (sqlite3_syscall_ptr)0,          0  },
24481#endif
24482#define osPread     ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[9].pCurrent)
24483
24484#if defined(USE_PREAD64)
24485  { "pread64",      (sqlite3_syscall_ptr)pread64,    0  },
24486#else
24487  { "pread64",      (sqlite3_syscall_ptr)0,          0  },
24488#endif
24489#define osPread64   ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[10].pCurrent)
24490
24491  { "write",        (sqlite3_syscall_ptr)write,      0  },
24492#define osWrite     ((ssize_t(*)(int,const void*,size_t))aSyscall[11].pCurrent)
24493
24494#if defined(USE_PREAD) || defined(SQLITE_ENABLE_LOCKING_STYLE)
24495  { "pwrite",       (sqlite3_syscall_ptr)pwrite,     0  },
24496#else
24497  { "pwrite",       (sqlite3_syscall_ptr)0,          0  },
24498#endif
24499#define osPwrite    ((ssize_t(*)(int,const void*,size_t,off_t))\
24500                    aSyscall[12].pCurrent)
24501
24502#if defined(USE_PREAD64)
24503  { "pwrite64",     (sqlite3_syscall_ptr)pwrite64,   0  },
24504#else
24505  { "pwrite64",     (sqlite3_syscall_ptr)0,          0  },
24506#endif
24507#define osPwrite64  ((ssize_t(*)(int,const void*,size_t,off_t))\
24508                    aSyscall[13].pCurrent)
24509
24510#if SQLITE_ENABLE_LOCKING_STYLE
24511  { "fchmod",       (sqlite3_syscall_ptr)fchmod,     0  },
24512#else
24513  { "fchmod",       (sqlite3_syscall_ptr)0,          0  },
24514#endif
24515#define osFchmod    ((int(*)(int,mode_t))aSyscall[14].pCurrent)
24516
24517#if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
24518  { "fallocate",    (sqlite3_syscall_ptr)posix_fallocate,  0 },
24519#else
24520  { "fallocate",    (sqlite3_syscall_ptr)0,                0 },
24521#endif
24522#define osFallocate ((int(*)(int,off_t,off_t))aSyscall[15].pCurrent)
24523
24524  { "unlink",       (sqlite3_syscall_ptr)unlink,           0 },
24525#define osUnlink    ((int(*)(const char*))aSyscall[16].pCurrent)
24526
24527  { "openDirectory",    (sqlite3_syscall_ptr)openDirectory,      0 },
24528#define osOpenDirectory ((int(*)(const char*,int*))aSyscall[17].pCurrent)
24529
24530}; /* End of the overrideable system calls */
24531
24532/*
24533** This is the xSetSystemCall() method of sqlite3_vfs for all of the
24534** "unix" VFSes.  Return SQLITE_OK opon successfully updating the
24535** system call pointer, or SQLITE_NOTFOUND if there is no configurable
24536** system call named zName.
24537*/
24538static int unixSetSystemCall(
24539  sqlite3_vfs *pNotUsed,        /* The VFS pointer.  Not used */
24540  const char *zName,            /* Name of system call to override */
24541  sqlite3_syscall_ptr pNewFunc  /* Pointer to new system call value */
24542){
24543  unsigned int i;
24544  int rc = SQLITE_NOTFOUND;
24545
24546  UNUSED_PARAMETER(pNotUsed);
24547  if( zName==0 ){
24548    /* If no zName is given, restore all system calls to their default
24549    ** settings and return NULL
24550    */
24551    rc = SQLITE_OK;
24552    for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
24553      if( aSyscall[i].pDefault ){
24554        aSyscall[i].pCurrent = aSyscall[i].pDefault;
24555      }
24556    }
24557  }else{
24558    /* If zName is specified, operate on only the one system call
24559    ** specified.
24560    */
24561    for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
24562      if( strcmp(zName, aSyscall[i].zName)==0 ){
24563        if( aSyscall[i].pDefault==0 ){
24564          aSyscall[i].pDefault = aSyscall[i].pCurrent;
24565        }
24566        rc = SQLITE_OK;
24567        if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
24568        aSyscall[i].pCurrent = pNewFunc;
24569        break;
24570      }
24571    }
24572  }
24573  return rc;
24574}
24575
24576/*
24577** Return the value of a system call.  Return NULL if zName is not a
24578** recognized system call name.  NULL is also returned if the system call
24579** is currently undefined.
24580*/
24581static sqlite3_syscall_ptr unixGetSystemCall(
24582  sqlite3_vfs *pNotUsed,
24583  const char *zName
24584){
24585  unsigned int i;
24586
24587  UNUSED_PARAMETER(pNotUsed);
24588  for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
24589    if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;
24590  }
24591  return 0;
24592}
24593
24594/*
24595** Return the name of the first system call after zName.  If zName==NULL
24596** then return the name of the first system call.  Return NULL if zName
24597** is the last system call or if zName is not the name of a valid
24598** system call.
24599*/
24600static const char *unixNextSystemCall(sqlite3_vfs *p, const char *zName){
24601  int i = -1;
24602
24603  UNUSED_PARAMETER(p);
24604  if( zName ){
24605    for(i=0; i<ArraySize(aSyscall)-1; i++){
24606      if( strcmp(zName, aSyscall[i].zName)==0 ) break;
24607    }
24608  }
24609  for(i++; i<ArraySize(aSyscall); i++){
24610    if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName;
24611  }
24612  return 0;
24613}
24614
24615/*
24616** Retry open() calls that fail due to EINTR
24617*/
24618static int robust_open(const char *z, int f, int m){
24619  int rc;
24620  do{ rc = osOpen(z,f,m); }while( rc<0 && errno==EINTR );
24621  return rc;
24622}
24623
24624/*
24625** Helper functions to obtain and relinquish the global mutex. The
24626** global mutex is used to protect the unixInodeInfo and
24627** vxworksFileId objects used by this file, all of which may be
24628** shared by multiple threads.
24629**
24630** Function unixMutexHeld() is used to assert() that the global mutex
24631** is held when required. This function is only used as part of assert()
24632** statements. e.g.
24633**
24634**   unixEnterMutex()
24635**     assert( unixMutexHeld() );
24636**   unixEnterLeave()
24637*/
24638static void unixEnterMutex(void){
24639  sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
24640}
24641static void unixLeaveMutex(void){
24642  sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
24643}
24644#ifdef SQLITE_DEBUG
24645static int unixMutexHeld(void) {
24646  return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
24647}
24648#endif
24649
24650
24651#ifdef SQLITE_DEBUG
24652/*
24653** Helper function for printing out trace information from debugging
24654** binaries. This returns the string represetation of the supplied
24655** integer lock-type.
24656*/
24657static const char *azFileLock(int eFileLock){
24658  switch( eFileLock ){
24659    case NO_LOCK: return "NONE";
24660    case SHARED_LOCK: return "SHARED";
24661    case RESERVED_LOCK: return "RESERVED";
24662    case PENDING_LOCK: return "PENDING";
24663    case EXCLUSIVE_LOCK: return "EXCLUSIVE";
24664  }
24665  return "ERROR";
24666}
24667#endif
24668
24669#ifdef SQLITE_LOCK_TRACE
24670/*
24671** Print out information about all locking operations.
24672**
24673** This routine is used for troubleshooting locks on multithreaded
24674** platforms.  Enable by compiling with the -DSQLITE_LOCK_TRACE
24675** command-line option on the compiler.  This code is normally
24676** turned off.
24677*/
24678static int lockTrace(int fd, int op, struct flock *p){
24679  char *zOpName, *zType;
24680  int s;
24681  int savedErrno;
24682  if( op==F_GETLK ){
24683    zOpName = "GETLK";
24684  }else if( op==F_SETLK ){
24685    zOpName = "SETLK";
24686  }else{
24687    s = osFcntl(fd, op, p);
24688    sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
24689    return s;
24690  }
24691  if( p->l_type==F_RDLCK ){
24692    zType = "RDLCK";
24693  }else if( p->l_type==F_WRLCK ){
24694    zType = "WRLCK";
24695  }else if( p->l_type==F_UNLCK ){
24696    zType = "UNLCK";
24697  }else{
24698    assert( 0 );
24699  }
24700  assert( p->l_whence==SEEK_SET );
24701  s = osFcntl(fd, op, p);
24702  savedErrno = errno;
24703  sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
24704     threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
24705     (int)p->l_pid, s);
24706  if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
24707    struct flock l2;
24708    l2 = *p;
24709    osFcntl(fd, F_GETLK, &l2);
24710    if( l2.l_type==F_RDLCK ){
24711      zType = "RDLCK";
24712    }else if( l2.l_type==F_WRLCK ){
24713      zType = "WRLCK";
24714    }else if( l2.l_type==F_UNLCK ){
24715      zType = "UNLCK";
24716    }else{
24717      assert( 0 );
24718    }
24719    sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
24720       zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
24721  }
24722  errno = savedErrno;
24723  return s;
24724}
24725#undef osFcntl
24726#define osFcntl lockTrace
24727#endif /* SQLITE_LOCK_TRACE */
24728
24729/*
24730** Retry ftruncate() calls that fail due to EINTR
24731*/
24732static int robust_ftruncate(int h, sqlite3_int64 sz){
24733  int rc;
24734  do{ rc = osFtruncate(h,sz); }while( rc<0 && errno==EINTR );
24735  return rc;
24736}
24737
24738/*
24739** This routine translates a standard POSIX errno code into something
24740** useful to the clients of the sqlite3 functions.  Specifically, it is
24741** intended to translate a variety of "try again" errors into SQLITE_BUSY
24742** and a variety of "please close the file descriptor NOW" errors into
24743** SQLITE_IOERR
24744**
24745** Errors during initialization of locks, or file system support for locks,
24746** should handle ENOLCK, ENOTSUP, EOPNOTSUPP separately.
24747*/
24748static int sqliteErrorFromPosixError(int posixError, int sqliteIOErr) {
24749  switch (posixError) {
24750#if 0
24751  /* At one point this code was not commented out. In theory, this branch
24752  ** should never be hit, as this function should only be called after
24753  ** a locking-related function (i.e. fcntl()) has returned non-zero with
24754  ** the value of errno as the first argument. Since a system call has failed,
24755  ** errno should be non-zero.
24756  **
24757  ** Despite this, if errno really is zero, we still don't want to return
24758  ** SQLITE_OK. The system call failed, and *some* SQLite error should be
24759  ** propagated back to the caller. Commenting this branch out means errno==0
24760  ** will be handled by the "default:" case below.
24761  */
24762  case 0:
24763    return SQLITE_OK;
24764#endif
24765
24766  case EAGAIN:
24767  case ETIMEDOUT:
24768  case EBUSY:
24769  case EINTR:
24770  case ENOLCK:
24771    /* random NFS retry error, unless during file system support
24772     * introspection, in which it actually means what it says */
24773    return SQLITE_BUSY;
24774
24775  case EACCES:
24776    /* EACCES is like EAGAIN during locking operations, but not any other time*/
24777    if( (sqliteIOErr == SQLITE_IOERR_LOCK) ||
24778	(sqliteIOErr == SQLITE_IOERR_UNLOCK) ||
24779	(sqliteIOErr == SQLITE_IOERR_RDLOCK) ||
24780	(sqliteIOErr == SQLITE_IOERR_CHECKRESERVEDLOCK) ){
24781      return SQLITE_BUSY;
24782    }
24783    /* else fall through */
24784  case EPERM:
24785    return SQLITE_PERM;
24786
24787  /* EDEADLK is only possible if a call to fcntl(F_SETLKW) is made. And
24788  ** this module never makes such a call. And the code in SQLite itself
24789  ** asserts that SQLITE_IOERR_BLOCKED is never returned. For these reasons
24790  ** this case is also commented out. If the system does set errno to EDEADLK,
24791  ** the default SQLITE_IOERR_XXX code will be returned. */
24792#if 0
24793  case EDEADLK:
24794    return SQLITE_IOERR_BLOCKED;
24795#endif
24796
24797#if EOPNOTSUPP!=ENOTSUP
24798  case EOPNOTSUPP:
24799    /* something went terribly awry, unless during file system support
24800     * introspection, in which it actually means what it says */
24801#endif
24802#ifdef ENOTSUP
24803  case ENOTSUP:
24804    /* invalid fd, unless during file system support introspection, in which
24805     * it actually means what it says */
24806#endif
24807  case EIO:
24808  case EBADF:
24809  case EINVAL:
24810  case ENOTCONN:
24811  case ENODEV:
24812  case ENXIO:
24813  case ENOENT:
24814  case ESTALE:
24815  case ENOSYS:
24816    /* these should force the client to close the file and reconnect */
24817
24818  default:
24819    return sqliteIOErr;
24820  }
24821}
24822
24823
24824
24825/******************************************************************************
24826****************** Begin Unique File ID Utility Used By VxWorks ***************
24827**
24828** On most versions of unix, we can get a unique ID for a file by concatenating
24829** the device number and the inode number.  But this does not work on VxWorks.
24830** On VxWorks, a unique file id must be based on the canonical filename.
24831**
24832** A pointer to an instance of the following structure can be used as a
24833** unique file ID in VxWorks.  Each instance of this structure contains
24834** a copy of the canonical filename.  There is also a reference count.
24835** The structure is reclaimed when the number of pointers to it drops to
24836** zero.
24837**
24838** There are never very many files open at one time and lookups are not
24839** a performance-critical path, so it is sufficient to put these
24840** structures on a linked list.
24841*/
24842struct vxworksFileId {
24843  struct vxworksFileId *pNext;  /* Next in a list of them all */
24844  int nRef;                     /* Number of references to this one */
24845  int nName;                    /* Length of the zCanonicalName[] string */
24846  char *zCanonicalName;         /* Canonical filename */
24847};
24848
24849#if OS_VXWORKS
24850/*
24851** All unique filenames are held on a linked list headed by this
24852** variable:
24853*/
24854static struct vxworksFileId *vxworksFileList = 0;
24855
24856/*
24857** Simplify a filename into its canonical form
24858** by making the following changes:
24859**
24860**  * removing any trailing and duplicate /
24861**  * convert /./ into just /
24862**  * convert /A/../ where A is any simple name into just /
24863**
24864** Changes are made in-place.  Return the new name length.
24865**
24866** The original filename is in z[0..n-1].  Return the number of
24867** characters in the simplified name.
24868*/
24869static int vxworksSimplifyName(char *z, int n){
24870  int i, j;
24871  while( n>1 && z[n-1]=='/' ){ n--; }
24872  for(i=j=0; i<n; i++){
24873    if( z[i]=='/' ){
24874      if( z[i+1]=='/' ) continue;
24875      if( z[i+1]=='.' && i+2<n && z[i+2]=='/' ){
24876        i += 1;
24877        continue;
24878      }
24879      if( z[i+1]=='.' && i+3<n && z[i+2]=='.' && z[i+3]=='/' ){
24880        while( j>0 && z[j-1]!='/' ){ j--; }
24881        if( j>0 ){ j--; }
24882        i += 2;
24883        continue;
24884      }
24885    }
24886    z[j++] = z[i];
24887  }
24888  z[j] = 0;
24889  return j;
24890}
24891
24892/*
24893** Find a unique file ID for the given absolute pathname.  Return
24894** a pointer to the vxworksFileId object.  This pointer is the unique
24895** file ID.
24896**
24897** The nRef field of the vxworksFileId object is incremented before
24898** the object is returned.  A new vxworksFileId object is created
24899** and added to the global list if necessary.
24900**
24901** If a memory allocation error occurs, return NULL.
24902*/
24903static struct vxworksFileId *vxworksFindFileId(const char *zAbsoluteName){
24904  struct vxworksFileId *pNew;         /* search key and new file ID */
24905  struct vxworksFileId *pCandidate;   /* For looping over existing file IDs */
24906  int n;                              /* Length of zAbsoluteName string */
24907
24908  assert( zAbsoluteName[0]=='/' );
24909  n = (int)strlen(zAbsoluteName);
24910  pNew = sqlite3_malloc( sizeof(*pNew) + (n+1) );
24911  if( pNew==0 ) return 0;
24912  pNew->zCanonicalName = (char*)&pNew[1];
24913  memcpy(pNew->zCanonicalName, zAbsoluteName, n+1);
24914  n = vxworksSimplifyName(pNew->zCanonicalName, n);
24915
24916  /* Search for an existing entry that matching the canonical name.
24917  ** If found, increment the reference count and return a pointer to
24918  ** the existing file ID.
24919  */
24920  unixEnterMutex();
24921  for(pCandidate=vxworksFileList; pCandidate; pCandidate=pCandidate->pNext){
24922    if( pCandidate->nName==n
24923     && memcmp(pCandidate->zCanonicalName, pNew->zCanonicalName, n)==0
24924    ){
24925       sqlite3_free(pNew);
24926       pCandidate->nRef++;
24927       unixLeaveMutex();
24928       return pCandidate;
24929    }
24930  }
24931
24932  /* No match was found.  We will make a new file ID */
24933  pNew->nRef = 1;
24934  pNew->nName = n;
24935  pNew->pNext = vxworksFileList;
24936  vxworksFileList = pNew;
24937  unixLeaveMutex();
24938  return pNew;
24939}
24940
24941/*
24942** Decrement the reference count on a vxworksFileId object.  Free
24943** the object when the reference count reaches zero.
24944*/
24945static void vxworksReleaseFileId(struct vxworksFileId *pId){
24946  unixEnterMutex();
24947  assert( pId->nRef>0 );
24948  pId->nRef--;
24949  if( pId->nRef==0 ){
24950    struct vxworksFileId **pp;
24951    for(pp=&vxworksFileList; *pp && *pp!=pId; pp = &((*pp)->pNext)){}
24952    assert( *pp==pId );
24953    *pp = pId->pNext;
24954    sqlite3_free(pId);
24955  }
24956  unixLeaveMutex();
24957}
24958#endif /* OS_VXWORKS */
24959/*************** End of Unique File ID Utility Used By VxWorks ****************
24960******************************************************************************/
24961
24962
24963/******************************************************************************
24964*************************** Posix Advisory Locking ****************************
24965**
24966** POSIX advisory locks are broken by design.  ANSI STD 1003.1 (1996)
24967** section 6.5.2.2 lines 483 through 490 specify that when a process
24968** sets or clears a lock, that operation overrides any prior locks set
24969** by the same process.  It does not explicitly say so, but this implies
24970** that it overrides locks set by the same process using a different
24971** file descriptor.  Consider this test case:
24972**
24973**       int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
24974**       int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
24975**
24976** Suppose ./file1 and ./file2 are really the same file (because
24977** one is a hard or symbolic link to the other) then if you set
24978** an exclusive lock on fd1, then try to get an exclusive lock
24979** on fd2, it works.  I would have expected the second lock to
24980** fail since there was already a lock on the file due to fd1.
24981** But not so.  Since both locks came from the same process, the
24982** second overrides the first, even though they were on different
24983** file descriptors opened on different file names.
24984**
24985** This means that we cannot use POSIX locks to synchronize file access
24986** among competing threads of the same process.  POSIX locks will work fine
24987** to synchronize access for threads in separate processes, but not
24988** threads within the same process.
24989**
24990** To work around the problem, SQLite has to manage file locks internally
24991** on its own.  Whenever a new database is opened, we have to find the
24992** specific inode of the database file (the inode is determined by the
24993** st_dev and st_ino fields of the stat structure that fstat() fills in)
24994** and check for locks already existing on that inode.  When locks are
24995** created or removed, we have to look at our own internal record of the
24996** locks to see if another thread has previously set a lock on that same
24997** inode.
24998**
24999** (Aside: The use of inode numbers as unique IDs does not work on VxWorks.
25000** For VxWorks, we have to use the alternative unique ID system based on
25001** canonical filename and implemented in the previous division.)
25002**
25003** The sqlite3_file structure for POSIX is no longer just an integer file
25004** descriptor.  It is now a structure that holds the integer file
25005** descriptor and a pointer to a structure that describes the internal
25006** locks on the corresponding inode.  There is one locking structure
25007** per inode, so if the same inode is opened twice, both unixFile structures
25008** point to the same locking structure.  The locking structure keeps
25009** a reference count (so we will know when to delete it) and a "cnt"
25010** field that tells us its internal lock status.  cnt==0 means the
25011** file is unlocked.  cnt==-1 means the file has an exclusive lock.
25012** cnt>0 means there are cnt shared locks on the file.
25013**
25014** Any attempt to lock or unlock a file first checks the locking
25015** structure.  The fcntl() system call is only invoked to set a
25016** POSIX lock if the internal lock structure transitions between
25017** a locked and an unlocked state.
25018**
25019** But wait:  there are yet more problems with POSIX advisory locks.
25020**
25021** If you close a file descriptor that points to a file that has locks,
25022** all locks on that file that are owned by the current process are
25023** released.  To work around this problem, each unixInodeInfo object
25024** maintains a count of the number of pending locks on tha inode.
25025** When an attempt is made to close an unixFile, if there are
25026** other unixFile open on the same inode that are holding locks, the call
25027** to close() the file descriptor is deferred until all of the locks clear.
25028** The unixInodeInfo structure keeps a list of file descriptors that need to
25029** be closed and that list is walked (and cleared) when the last lock
25030** clears.
25031**
25032** Yet another problem:  LinuxThreads do not play well with posix locks.
25033**
25034** Many older versions of linux use the LinuxThreads library which is
25035** not posix compliant.  Under LinuxThreads, a lock created by thread
25036** A cannot be modified or overridden by a different thread B.
25037** Only thread A can modify the lock.  Locking behavior is correct
25038** if the appliation uses the newer Native Posix Thread Library (NPTL)
25039** on linux - with NPTL a lock created by thread A can override locks
25040** in thread B.  But there is no way to know at compile-time which
25041** threading library is being used.  So there is no way to know at
25042** compile-time whether or not thread A can override locks on thread B.
25043** One has to do a run-time check to discover the behavior of the
25044** current process.
25045**
25046** SQLite used to support LinuxThreads.  But support for LinuxThreads
25047** was dropped beginning with version 3.7.0.  SQLite will still work with
25048** LinuxThreads provided that (1) there is no more than one connection
25049** per database file in the same process and (2) database connections
25050** do not move across threads.
25051*/
25052
25053/*
25054** An instance of the following structure serves as the key used
25055** to locate a particular unixInodeInfo object.
25056*/
25057struct unixFileId {
25058  dev_t dev;                  /* Device number */
25059#if OS_VXWORKS
25060  struct vxworksFileId *pId;  /* Unique file ID for vxworks. */
25061#else
25062  ino_t ino;                  /* Inode number */
25063#endif
25064};
25065
25066/*
25067** An instance of the following structure is allocated for each open
25068** inode.  Or, on LinuxThreads, there is one of these structures for
25069** each inode opened by each thread.
25070**
25071** A single inode can have multiple file descriptors, so each unixFile
25072** structure contains a pointer to an instance of this object and this
25073** object keeps a count of the number of unixFile pointing to it.
25074*/
25075struct unixInodeInfo {
25076  struct unixFileId fileId;       /* The lookup key */
25077  int nShared;                    /* Number of SHARED locks held */
25078  unsigned char eFileLock;        /* One of SHARED_LOCK, RESERVED_LOCK etc. */
25079  unsigned char bProcessLock;     /* An exclusive process lock is held */
25080  int nRef;                       /* Number of pointers to this structure */
25081  unixShmNode *pShmNode;          /* Shared memory associated with this inode */
25082  int nLock;                      /* Number of outstanding file locks */
25083  UnixUnusedFd *pUnused;          /* Unused file descriptors to close */
25084  unixInodeInfo *pNext;           /* List of all unixInodeInfo objects */
25085  unixInodeInfo *pPrev;           /*    .... doubly linked */
25086#if defined(SQLITE_ENABLE_LOCKING_STYLE)
25087  unsigned long long sharedByte;  /* for AFP simulated shared lock */
25088#endif
25089#if OS_VXWORKS
25090  sem_t *pSem;                    /* Named POSIX semaphore */
25091  char aSemName[MAX_PATHNAME+2];  /* Name of that semaphore */
25092#endif
25093};
25094
25095/*
25096** A lists of all unixInodeInfo objects.
25097*/
25098static unixInodeInfo *inodeList = 0;
25099
25100/*
25101**
25102** This function - unixLogError_x(), is only ever called via the macro
25103** unixLogError().
25104**
25105** It is invoked after an error occurs in an OS function and errno has been
25106** set. It logs a message using sqlite3_log() containing the current value of
25107** errno and, if possible, the human-readable equivalent from strerror() or
25108** strerror_r().
25109**
25110** The first argument passed to the macro should be the error code that
25111** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN).
25112** The two subsequent arguments should be the name of the OS function that
25113** failed (e.g. "unlink", "open") and the the associated file-system path,
25114** if any.
25115*/
25116#define unixLogError(a,b,c)     unixLogErrorAtLine(a,b,c,__LINE__)
25117static int unixLogErrorAtLine(
25118  int errcode,                    /* SQLite error code */
25119  const char *zFunc,              /* Name of OS function that failed */
25120  const char *zPath,              /* File path associated with error */
25121  int iLine                       /* Source line number where error occurred */
25122){
25123  char *zErr;                     /* Message from strerror() or equivalent */
25124  int iErrno = errno;             /* Saved syscall error number */
25125
25126  /* If this is not a threadsafe build (SQLITE_THREADSAFE==0), then use
25127  ** the strerror() function to obtain the human-readable error message
25128  ** equivalent to errno. Otherwise, use strerror_r().
25129  */
25130#if SQLITE_THREADSAFE && defined(HAVE_STRERROR_R)
25131  char aErr[80];
25132  memset(aErr, 0, sizeof(aErr));
25133  zErr = aErr;
25134
25135  /* If STRERROR_R_CHAR_P (set by autoconf scripts) or __USE_GNU is defined,
25136  ** assume that the system provides the the GNU version of strerror_r() that
25137  ** returns a pointer to a buffer containing the error message. That pointer
25138  ** may point to aErr[], or it may point to some static storage somewhere.
25139  ** Otherwise, assume that the system provides the POSIX version of
25140  ** strerror_r(), which always writes an error message into aErr[].
25141  **
25142  ** If the code incorrectly assumes that it is the POSIX version that is
25143  ** available, the error message will often be an empty string. Not a
25144  ** huge problem. Incorrectly concluding that the GNU version is available
25145  ** could lead to a segfault though.
25146  */
25147#if defined(STRERROR_R_CHAR_P) || defined(__USE_GNU)
25148  zErr =
25149# endif
25150  strerror_r(iErrno, aErr, sizeof(aErr)-1);
25151
25152#elif SQLITE_THREADSAFE
25153  /* This is a threadsafe build, but strerror_r() is not available. */
25154  zErr = "";
25155#else
25156  /* Non-threadsafe build, use strerror(). */
25157  zErr = strerror(iErrno);
25158#endif
25159
25160  assert( errcode!=SQLITE_OK );
25161  if( zPath==0 ) zPath = "";
25162  sqlite3_log(errcode,
25163      "os_unix.c:%d: (%d) %s(%s) - %s",
25164      iLine, iErrno, zFunc, zPath, zErr
25165  );
25166
25167  return errcode;
25168}
25169
25170/*
25171** Close a file descriptor.
25172**
25173** We assume that close() almost always works, since it is only in a
25174** very sick application or on a very sick platform that it might fail.
25175** If it does fail, simply leak the file descriptor, but do log the
25176** error.
25177**
25178** Note that it is not safe to retry close() after EINTR since the
25179** file descriptor might have already been reused by another thread.
25180** So we don't even try to recover from an EINTR.  Just log the error
25181** and move on.
25182*/
25183static void robust_close(unixFile *pFile, int h, int lineno){
25184  if( osClose(h) ){
25185    unixLogErrorAtLine(SQLITE_IOERR_CLOSE, "close",
25186                       pFile ? pFile->zPath : 0, lineno);
25187  }
25188}
25189
25190/*
25191** Close all file descriptors accumuated in the unixInodeInfo->pUnused list.
25192*/
25193static void closePendingFds(unixFile *pFile){
25194  unixInodeInfo *pInode = pFile->pInode;
25195  UnixUnusedFd *p;
25196  UnixUnusedFd *pNext;
25197  for(p=pInode->pUnused; p; p=pNext){
25198    pNext = p->pNext;
25199    robust_close(pFile, p->fd, __LINE__);
25200    sqlite3_free(p);
25201  }
25202  pInode->pUnused = 0;
25203}
25204
25205/*
25206** Release a unixInodeInfo structure previously allocated by findInodeInfo().
25207**
25208** The mutex entered using the unixEnterMutex() function must be held
25209** when this function is called.
25210*/
25211static void releaseInodeInfo(unixFile *pFile){
25212  unixInodeInfo *pInode = pFile->pInode;
25213  assert( unixMutexHeld() );
25214  if( ALWAYS(pInode) ){
25215    pInode->nRef--;
25216    if( pInode->nRef==0 ){
25217      assert( pInode->pShmNode==0 );
25218      closePendingFds(pFile);
25219      if( pInode->pPrev ){
25220        assert( pInode->pPrev->pNext==pInode );
25221        pInode->pPrev->pNext = pInode->pNext;
25222      }else{
25223        assert( inodeList==pInode );
25224        inodeList = pInode->pNext;
25225      }
25226      if( pInode->pNext ){
25227        assert( pInode->pNext->pPrev==pInode );
25228        pInode->pNext->pPrev = pInode->pPrev;
25229      }
25230      sqlite3_free(pInode);
25231    }
25232  }
25233}
25234
25235/*
25236** Given a file descriptor, locate the unixInodeInfo object that
25237** describes that file descriptor.  Create a new one if necessary.  The
25238** return value might be uninitialized if an error occurs.
25239**
25240** The mutex entered using the unixEnterMutex() function must be held
25241** when this function is called.
25242**
25243** Return an appropriate error code.
25244*/
25245static int findInodeInfo(
25246  unixFile *pFile,               /* Unix file with file desc used in the key */
25247  unixInodeInfo **ppInode        /* Return the unixInodeInfo object here */
25248){
25249  int rc;                        /* System call return code */
25250  int fd;                        /* The file descriptor for pFile */
25251  struct unixFileId fileId;      /* Lookup key for the unixInodeInfo */
25252  struct stat statbuf;           /* Low-level file information */
25253  unixInodeInfo *pInode = 0;     /* Candidate unixInodeInfo object */
25254
25255  assert( unixMutexHeld() );
25256
25257  /* Get low-level information about the file that we can used to
25258  ** create a unique name for the file.
25259  */
25260  fd = pFile->h;
25261  rc = osFstat(fd, &statbuf);
25262  if( rc!=0 ){
25263    pFile->lastErrno = errno;
25264#ifdef EOVERFLOW
25265    if( pFile->lastErrno==EOVERFLOW ) return SQLITE_NOLFS;
25266#endif
25267    return SQLITE_IOERR;
25268  }
25269
25270#ifdef __APPLE__
25271  /* On OS X on an msdos filesystem, the inode number is reported
25272  ** incorrectly for zero-size files.  See ticket #3260.  To work
25273  ** around this problem (we consider it a bug in OS X, not SQLite)
25274  ** we always increase the file size to 1 by writing a single byte
25275  ** prior to accessing the inode number.  The one byte written is
25276  ** an ASCII 'S' character which also happens to be the first byte
25277  ** in the header of every SQLite database.  In this way, if there
25278  ** is a race condition such that another thread has already populated
25279  ** the first page of the database, no damage is done.
25280  */
25281  if( statbuf.st_size==0 && (pFile->fsFlags & SQLITE_FSFLAGS_IS_MSDOS)!=0 ){
25282    do{ rc = osWrite(fd, "S", 1); }while( rc<0 && errno==EINTR );
25283    if( rc!=1 ){
25284      pFile->lastErrno = errno;
25285      return SQLITE_IOERR;
25286    }
25287    rc = osFstat(fd, &statbuf);
25288    if( rc!=0 ){
25289      pFile->lastErrno = errno;
25290      return SQLITE_IOERR;
25291    }
25292  }
25293#endif
25294
25295  memset(&fileId, 0, sizeof(fileId));
25296  fileId.dev = statbuf.st_dev;
25297#if OS_VXWORKS
25298  fileId.pId = pFile->pId;
25299#else
25300  fileId.ino = statbuf.st_ino;
25301#endif
25302  pInode = inodeList;
25303  while( pInode && memcmp(&fileId, &pInode->fileId, sizeof(fileId)) ){
25304    pInode = pInode->pNext;
25305  }
25306  if( pInode==0 ){
25307    pInode = sqlite3_malloc( sizeof(*pInode) );
25308    if( pInode==0 ){
25309      return SQLITE_NOMEM;
25310    }
25311    memset(pInode, 0, sizeof(*pInode));
25312    memcpy(&pInode->fileId, &fileId, sizeof(fileId));
25313    pInode->nRef = 1;
25314    pInode->pNext = inodeList;
25315    pInode->pPrev = 0;
25316    if( inodeList ) inodeList->pPrev = pInode;
25317    inodeList = pInode;
25318  }else{
25319    pInode->nRef++;
25320  }
25321  *ppInode = pInode;
25322  return SQLITE_OK;
25323}
25324
25325
25326/*
25327** This routine checks if there is a RESERVED lock held on the specified
25328** file by this or any other process. If such a lock is held, set *pResOut
25329** to a non-zero value otherwise *pResOut is set to zero.  The return value
25330** is set to SQLITE_OK unless an I/O error occurs during lock checking.
25331*/
25332static int unixCheckReservedLock(sqlite3_file *id, int *pResOut){
25333  int rc = SQLITE_OK;
25334  int reserved = 0;
25335  unixFile *pFile = (unixFile*)id;
25336
25337  SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
25338
25339  assert( pFile );
25340  unixEnterMutex(); /* Because pFile->pInode is shared across threads */
25341
25342  /* Check if a thread in this process holds such a lock */
25343  if( pFile->pInode->eFileLock>SHARED_LOCK ){
25344    reserved = 1;
25345  }
25346
25347  /* Otherwise see if some other process holds it.
25348  */
25349#ifndef __DJGPP__
25350  if( !reserved && !pFile->pInode->bProcessLock ){
25351    struct flock lock;
25352    lock.l_whence = SEEK_SET;
25353    lock.l_start = RESERVED_BYTE;
25354    lock.l_len = 1;
25355    lock.l_type = F_WRLCK;
25356    if( osFcntl(pFile->h, F_GETLK, &lock) ){
25357      rc = SQLITE_IOERR_CHECKRESERVEDLOCK;
25358      pFile->lastErrno = errno;
25359    } else if( lock.l_type!=F_UNLCK ){
25360      reserved = 1;
25361    }
25362  }
25363#endif
25364
25365  unixLeaveMutex();
25366  OSTRACE(("TEST WR-LOCK %d %d %d (unix)\n", pFile->h, rc, reserved));
25367
25368  *pResOut = reserved;
25369  return rc;
25370}
25371
25372/*
25373** Attempt to set a system-lock on the file pFile.  The lock is
25374** described by pLock.
25375**
25376** If the pFile was opened read/write from unix-excl, then the only lock
25377** ever obtained is an exclusive lock, and it is obtained exactly once
25378** the first time any lock is attempted.  All subsequent system locking
25379** operations become no-ops.  Locking operations still happen internally,
25380** in order to coordinate access between separate database connections
25381** within this process, but all of that is handled in memory and the
25382** operating system does not participate.
25383**
25384** This function is a pass-through to fcntl(F_SETLK) if pFile is using
25385** any VFS other than "unix-excl" or if pFile is opened on "unix-excl"
25386** and is read-only.
25387**
25388** Zero is returned if the call completes successfully, or -1 if a call
25389** to fcntl() fails. In this case, errno is set appropriately (by fcntl()).
25390*/
25391static int unixFileLock(unixFile *pFile, struct flock *pLock){
25392  int rc;
25393  unixInodeInfo *pInode = pFile->pInode;
25394  assert( unixMutexHeld() );
25395  assert( pInode!=0 );
25396  if( ((pFile->ctrlFlags & UNIXFILE_EXCL)!=0 || pInode->bProcessLock)
25397   && ((pFile->ctrlFlags & UNIXFILE_RDONLY)==0)
25398  ){
25399    if( pInode->bProcessLock==0 ){
25400      struct flock lock;
25401      assert( pInode->nLock==0 );
25402      lock.l_whence = SEEK_SET;
25403      lock.l_start = SHARED_FIRST;
25404      lock.l_len = SHARED_SIZE;
25405      lock.l_type = F_WRLCK;
25406      rc = osFcntl(pFile->h, F_SETLK, &lock);
25407      if( rc<0 ) return rc;
25408      pInode->bProcessLock = 1;
25409      pInode->nLock++;
25410    }else{
25411      rc = 0;
25412    }
25413  }else{
25414    rc = osFcntl(pFile->h, F_SETLK, pLock);
25415  }
25416  return rc;
25417}
25418
25419/*
25420** Lock the file with the lock specified by parameter eFileLock - one
25421** of the following:
25422**
25423**     (1) SHARED_LOCK
25424**     (2) RESERVED_LOCK
25425**     (3) PENDING_LOCK
25426**     (4) EXCLUSIVE_LOCK
25427**
25428** Sometimes when requesting one lock state, additional lock states
25429** are inserted in between.  The locking might fail on one of the later
25430** transitions leaving the lock state different from what it started but
25431** still short of its goal.  The following chart shows the allowed
25432** transitions and the inserted intermediate states:
25433**
25434**    UNLOCKED -> SHARED
25435**    SHARED -> RESERVED
25436**    SHARED -> (PENDING) -> EXCLUSIVE
25437**    RESERVED -> (PENDING) -> EXCLUSIVE
25438**    PENDING -> EXCLUSIVE
25439**
25440** This routine will only increase a lock.  Use the sqlite3OsUnlock()
25441** routine to lower a locking level.
25442*/
25443static int unixLock(sqlite3_file *id, int eFileLock){
25444  /* The following describes the implementation of the various locks and
25445  ** lock transitions in terms of the POSIX advisory shared and exclusive
25446  ** lock primitives (called read-locks and write-locks below, to avoid
25447  ** confusion with SQLite lock names). The algorithms are complicated
25448  ** slightly in order to be compatible with windows systems simultaneously
25449  ** accessing the same database file, in case that is ever required.
25450  **
25451  ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
25452  ** byte', each single bytes at well known offsets, and the 'shared byte
25453  ** range', a range of 510 bytes at a well known offset.
25454  **
25455  ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
25456  ** byte'.  If this is successful, a random byte from the 'shared byte
25457  ** range' is read-locked and the lock on the 'pending byte' released.
25458  **
25459  ** A process may only obtain a RESERVED lock after it has a SHARED lock.
25460  ** A RESERVED lock is implemented by grabbing a write-lock on the
25461  ** 'reserved byte'.
25462  **
25463  ** A process may only obtain a PENDING lock after it has obtained a
25464  ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
25465  ** on the 'pending byte'. This ensures that no new SHARED locks can be
25466  ** obtained, but existing SHARED locks are allowed to persist. A process
25467  ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
25468  ** This property is used by the algorithm for rolling back a journal file
25469  ** after a crash.
25470  **
25471  ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
25472  ** implemented by obtaining a write-lock on the entire 'shared byte
25473  ** range'. Since all other locks require a read-lock on one of the bytes
25474  ** within this range, this ensures that no other locks are held on the
25475  ** database.
25476  **
25477  ** The reason a single byte cannot be used instead of the 'shared byte
25478  ** range' is that some versions of windows do not support read-locks. By
25479  ** locking a random byte from a range, concurrent SHARED locks may exist
25480  ** even if the locking primitive used is always a write-lock.
25481  */
25482  int rc = SQLITE_OK;
25483  unixFile *pFile = (unixFile*)id;
25484  unixInodeInfo *pInode = pFile->pInode;
25485  struct flock lock;
25486  int tErrno = 0;
25487
25488  assert( pFile );
25489  OSTRACE(("LOCK    %d %s was %s(%s,%d) pid=%d (unix)\n", pFile->h,
25490      azFileLock(eFileLock), azFileLock(pFile->eFileLock),
25491      azFileLock(pInode->eFileLock), pInode->nShared , getpid()));
25492
25493  /* If there is already a lock of this type or more restrictive on the
25494  ** unixFile, do nothing. Don't use the end_lock: exit path, as
25495  ** unixEnterMutex() hasn't been called yet.
25496  */
25497  if( pFile->eFileLock>=eFileLock ){
25498    OSTRACE(("LOCK    %d %s ok (already held) (unix)\n", pFile->h,
25499            azFileLock(eFileLock)));
25500    return SQLITE_OK;
25501  }
25502
25503  /* Make sure the locking sequence is correct.
25504  **  (1) We never move from unlocked to anything higher than shared lock.
25505  **  (2) SQLite never explicitly requests a pendig lock.
25506  **  (3) A shared lock is always held when a reserve lock is requested.
25507  */
25508  assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
25509  assert( eFileLock!=PENDING_LOCK );
25510  assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
25511
25512  /* This mutex is needed because pFile->pInode is shared across threads
25513  */
25514  unixEnterMutex();
25515  pInode = pFile->pInode;
25516
25517  /* If some thread using this PID has a lock via a different unixFile*
25518  ** handle that precludes the requested lock, return BUSY.
25519  */
25520  if( (pFile->eFileLock!=pInode->eFileLock &&
25521          (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
25522  ){
25523    rc = SQLITE_BUSY;
25524    goto end_lock;
25525  }
25526
25527  /* If a SHARED lock is requested, and some thread using this PID already
25528  ** has a SHARED or RESERVED lock, then increment reference counts and
25529  ** return SQLITE_OK.
25530  */
25531  if( eFileLock==SHARED_LOCK &&
25532      (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
25533    assert( eFileLock==SHARED_LOCK );
25534    assert( pFile->eFileLock==0 );
25535    assert( pInode->nShared>0 );
25536    pFile->eFileLock = SHARED_LOCK;
25537    pInode->nShared++;
25538    pInode->nLock++;
25539    goto end_lock;
25540  }
25541
25542
25543  /* A PENDING lock is needed before acquiring a SHARED lock and before
25544  ** acquiring an EXCLUSIVE lock.  For the SHARED lock, the PENDING will
25545  ** be released.
25546  */
25547  lock.l_len = 1L;
25548  lock.l_whence = SEEK_SET;
25549  if( eFileLock==SHARED_LOCK
25550      || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
25551  ){
25552    lock.l_type = (eFileLock==SHARED_LOCK?F_RDLCK:F_WRLCK);
25553    lock.l_start = PENDING_BYTE;
25554    if( unixFileLock(pFile, &lock) ){
25555      tErrno = errno;
25556      rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
25557      if( rc!=SQLITE_BUSY ){
25558        pFile->lastErrno = tErrno;
25559      }
25560      goto end_lock;
25561    }
25562  }
25563
25564
25565  /* If control gets to this point, then actually go ahead and make
25566  ** operating system calls for the specified lock.
25567  */
25568  if( eFileLock==SHARED_LOCK ){
25569    assert( pInode->nShared==0 );
25570    assert( pInode->eFileLock==0 );
25571    assert( rc==SQLITE_OK );
25572
25573    /* Now get the read-lock */
25574    lock.l_start = SHARED_FIRST;
25575    lock.l_len = SHARED_SIZE;
25576    if( unixFileLock(pFile, &lock) ){
25577      tErrno = errno;
25578      rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
25579    }
25580
25581    /* Drop the temporary PENDING lock */
25582    lock.l_start = PENDING_BYTE;
25583    lock.l_len = 1L;
25584    lock.l_type = F_UNLCK;
25585    if( unixFileLock(pFile, &lock) && rc==SQLITE_OK ){
25586      /* This could happen with a network mount */
25587      tErrno = errno;
25588      rc = SQLITE_IOERR_UNLOCK;
25589    }
25590
25591    if( rc ){
25592      if( rc!=SQLITE_BUSY ){
25593        pFile->lastErrno = tErrno;
25594      }
25595      goto end_lock;
25596    }else{
25597      pFile->eFileLock = SHARED_LOCK;
25598      pInode->nLock++;
25599      pInode->nShared = 1;
25600    }
25601  }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
25602    /* We are trying for an exclusive lock but another thread in this
25603    ** same process is still holding a shared lock. */
25604    rc = SQLITE_BUSY;
25605  }else{
25606    /* The request was for a RESERVED or EXCLUSIVE lock.  It is
25607    ** assumed that there is a SHARED or greater lock on the file
25608    ** already.
25609    */
25610    assert( 0!=pFile->eFileLock );
25611    lock.l_type = F_WRLCK;
25612
25613    assert( eFileLock==RESERVED_LOCK || eFileLock==EXCLUSIVE_LOCK );
25614    if( eFileLock==RESERVED_LOCK ){
25615      lock.l_start = RESERVED_BYTE;
25616      lock.l_len = 1L;
25617    }else{
25618      lock.l_start = SHARED_FIRST;
25619      lock.l_len = SHARED_SIZE;
25620    }
25621
25622    if( unixFileLock(pFile, &lock) ){
25623      tErrno = errno;
25624      rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
25625      if( rc!=SQLITE_BUSY ){
25626        pFile->lastErrno = tErrno;
25627      }
25628    }
25629  }
25630
25631
25632#ifndef NDEBUG
25633  /* Set up the transaction-counter change checking flags when
25634  ** transitioning from a SHARED to a RESERVED lock.  The change
25635  ** from SHARED to RESERVED marks the beginning of a normal
25636  ** write operation (not a hot journal rollback).
25637  */
25638  if( rc==SQLITE_OK
25639   && pFile->eFileLock<=SHARED_LOCK
25640   && eFileLock==RESERVED_LOCK
25641  ){
25642    pFile->transCntrChng = 0;
25643    pFile->dbUpdate = 0;
25644    pFile->inNormalWrite = 1;
25645  }
25646#endif
25647
25648
25649  if( rc==SQLITE_OK ){
25650    pFile->eFileLock = eFileLock;
25651    pInode->eFileLock = eFileLock;
25652  }else if( eFileLock==EXCLUSIVE_LOCK ){
25653    pFile->eFileLock = PENDING_LOCK;
25654    pInode->eFileLock = PENDING_LOCK;
25655  }
25656
25657end_lock:
25658  unixLeaveMutex();
25659  OSTRACE(("LOCK    %d %s %s (unix)\n", pFile->h, azFileLock(eFileLock),
25660      rc==SQLITE_OK ? "ok" : "failed"));
25661  return rc;
25662}
25663
25664/*
25665** Add the file descriptor used by file handle pFile to the corresponding
25666** pUnused list.
25667*/
25668static void setPendingFd(unixFile *pFile){
25669  unixInodeInfo *pInode = pFile->pInode;
25670  UnixUnusedFd *p = pFile->pUnused;
25671  p->pNext = pInode->pUnused;
25672  pInode->pUnused = p;
25673  pFile->h = -1;
25674  pFile->pUnused = 0;
25675}
25676
25677/*
25678** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
25679** must be either NO_LOCK or SHARED_LOCK.
25680**
25681** If the locking level of the file descriptor is already at or below
25682** the requested locking level, this routine is a no-op.
25683**
25684** If handleNFSUnlock is true, then on downgrading an EXCLUSIVE_LOCK to SHARED
25685** the byte range is divided into 2 parts and the first part is unlocked then
25686** set to a read lock, then the other part is simply unlocked.  This works
25687** around a bug in BSD NFS lockd (also seen on MacOSX 10.3+) that fails to
25688** remove the write lock on a region when a read lock is set.
25689*/
25690static int posixUnlock(sqlite3_file *id, int eFileLock, int handleNFSUnlock){
25691  unixFile *pFile = (unixFile*)id;
25692  unixInodeInfo *pInode;
25693  struct flock lock;
25694  int rc = SQLITE_OK;
25695  int h;
25696
25697  assert( pFile );
25698  OSTRACE(("UNLOCK  %d %d was %d(%d,%d) pid=%d (unix)\n", pFile->h, eFileLock,
25699      pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
25700      getpid()));
25701
25702  assert( eFileLock<=SHARED_LOCK );
25703  if( pFile->eFileLock<=eFileLock ){
25704    return SQLITE_OK;
25705  }
25706  unixEnterMutex();
25707  h = pFile->h;
25708  pInode = pFile->pInode;
25709  assert( pInode->nShared!=0 );
25710  if( pFile->eFileLock>SHARED_LOCK ){
25711    assert( pInode->eFileLock==pFile->eFileLock );
25712    SimulateIOErrorBenign(1);
25713    SimulateIOError( h=(-1) )
25714    SimulateIOErrorBenign(0);
25715
25716#ifndef NDEBUG
25717    /* When reducing a lock such that other processes can start
25718    ** reading the database file again, make sure that the
25719    ** transaction counter was updated if any part of the database
25720    ** file changed.  If the transaction counter is not updated,
25721    ** other connections to the same file might not realize that
25722    ** the file has changed and hence might not know to flush their
25723    ** cache.  The use of a stale cache can lead to database corruption.
25724    */
25725#if 0
25726    assert( pFile->inNormalWrite==0
25727         || pFile->dbUpdate==0
25728         || pFile->transCntrChng==1 );
25729#endif
25730    pFile->inNormalWrite = 0;
25731#endif
25732
25733    /* downgrading to a shared lock on NFS involves clearing the write lock
25734    ** before establishing the readlock - to avoid a race condition we downgrade
25735    ** the lock in 2 blocks, so that part of the range will be covered by a
25736    ** write lock until the rest is covered by a read lock:
25737    **  1:   [WWWWW]
25738    **  2:   [....W]
25739    **  3:   [RRRRW]
25740    **  4:   [RRRR.]
25741    */
25742    if( eFileLock==SHARED_LOCK ){
25743
25744#if !defined(__APPLE__) || !SQLITE_ENABLE_LOCKING_STYLE
25745      (void)handleNFSUnlock;
25746      assert( handleNFSUnlock==0 );
25747#endif
25748#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
25749      if( handleNFSUnlock ){
25750        int tErrno;               /* Error code from system call errors */
25751        off_t divSize = SHARED_SIZE - 1;
25752
25753        lock.l_type = F_UNLCK;
25754        lock.l_whence = SEEK_SET;
25755        lock.l_start = SHARED_FIRST;
25756        lock.l_len = divSize;
25757        if( unixFileLock(pFile, &lock)==(-1) ){
25758          tErrno = errno;
25759          rc = SQLITE_IOERR_UNLOCK;
25760          if( IS_LOCK_ERROR(rc) ){
25761            pFile->lastErrno = tErrno;
25762          }
25763          goto end_unlock;
25764        }
25765        lock.l_type = F_RDLCK;
25766        lock.l_whence = SEEK_SET;
25767        lock.l_start = SHARED_FIRST;
25768        lock.l_len = divSize;
25769        if( unixFileLock(pFile, &lock)==(-1) ){
25770          tErrno = errno;
25771          rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
25772          if( IS_LOCK_ERROR(rc) ){
25773            pFile->lastErrno = tErrno;
25774          }
25775          goto end_unlock;
25776        }
25777        lock.l_type = F_UNLCK;
25778        lock.l_whence = SEEK_SET;
25779        lock.l_start = SHARED_FIRST+divSize;
25780        lock.l_len = SHARED_SIZE-divSize;
25781        if( unixFileLock(pFile, &lock)==(-1) ){
25782          tErrno = errno;
25783          rc = SQLITE_IOERR_UNLOCK;
25784          if( IS_LOCK_ERROR(rc) ){
25785            pFile->lastErrno = tErrno;
25786          }
25787          goto end_unlock;
25788        }
25789      }else
25790#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
25791      {
25792        lock.l_type = F_RDLCK;
25793        lock.l_whence = SEEK_SET;
25794        lock.l_start = SHARED_FIRST;
25795        lock.l_len = SHARED_SIZE;
25796        if( unixFileLock(pFile, &lock) ){
25797          /* In theory, the call to unixFileLock() cannot fail because another
25798          ** process is holding an incompatible lock. If it does, this
25799          ** indicates that the other process is not following the locking
25800          ** protocol. If this happens, return SQLITE_IOERR_RDLOCK. Returning
25801          ** SQLITE_BUSY would confuse the upper layer (in practice it causes
25802          ** an assert to fail). */
25803          rc = SQLITE_IOERR_RDLOCK;
25804          pFile->lastErrno = errno;
25805          goto end_unlock;
25806        }
25807      }
25808    }
25809    lock.l_type = F_UNLCK;
25810    lock.l_whence = SEEK_SET;
25811    lock.l_start = PENDING_BYTE;
25812    lock.l_len = 2L;  assert( PENDING_BYTE+1==RESERVED_BYTE );
25813    if( unixFileLock(pFile, &lock)==0 ){
25814      pInode->eFileLock = SHARED_LOCK;
25815    }else{
25816      rc = SQLITE_IOERR_UNLOCK;
25817      pFile->lastErrno = errno;
25818      goto end_unlock;
25819    }
25820  }
25821  if( eFileLock==NO_LOCK ){
25822    /* Decrement the shared lock counter.  Release the lock using an
25823    ** OS call only when all threads in this same process have released
25824    ** the lock.
25825    */
25826    pInode->nShared--;
25827    if( pInode->nShared==0 ){
25828      lock.l_type = F_UNLCK;
25829      lock.l_whence = SEEK_SET;
25830      lock.l_start = lock.l_len = 0L;
25831      SimulateIOErrorBenign(1);
25832      SimulateIOError( h=(-1) )
25833      SimulateIOErrorBenign(0);
25834      if( unixFileLock(pFile, &lock)==0 ){
25835        pInode->eFileLock = NO_LOCK;
25836      }else{
25837        rc = SQLITE_IOERR_UNLOCK;
25838	pFile->lastErrno = errno;
25839        pInode->eFileLock = NO_LOCK;
25840        pFile->eFileLock = NO_LOCK;
25841      }
25842    }
25843
25844    /* Decrement the count of locks against this same file.  When the
25845    ** count reaches zero, close any other file descriptors whose close
25846    ** was deferred because of outstanding locks.
25847    */
25848    pInode->nLock--;
25849    assert( pInode->nLock>=0 );
25850    if( pInode->nLock==0 ){
25851      closePendingFds(pFile);
25852    }
25853  }
25854
25855end_unlock:
25856  unixLeaveMutex();
25857  if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
25858  return rc;
25859}
25860
25861/*
25862** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
25863** must be either NO_LOCK or SHARED_LOCK.
25864**
25865** If the locking level of the file descriptor is already at or below
25866** the requested locking level, this routine is a no-op.
25867*/
25868static int unixUnlock(sqlite3_file *id, int eFileLock){
25869  return posixUnlock(id, eFileLock, 0);
25870}
25871
25872/*
25873** This function performs the parts of the "close file" operation
25874** common to all locking schemes. It closes the directory and file
25875** handles, if they are valid, and sets all fields of the unixFile
25876** structure to 0.
25877**
25878** It is *not* necessary to hold the mutex when this routine is called,
25879** even on VxWorks.  A mutex will be acquired on VxWorks by the
25880** vxworksReleaseFileId() routine.
25881*/
25882static int closeUnixFile(sqlite3_file *id){
25883  unixFile *pFile = (unixFile*)id;
25884  if( pFile->h>=0 ){
25885    robust_close(pFile, pFile->h, __LINE__);
25886    pFile->h = -1;
25887  }
25888#if OS_VXWORKS
25889  if( pFile->pId ){
25890    if( pFile->isDelete ){
25891      osUnlink(pFile->pId->zCanonicalName);
25892    }
25893    vxworksReleaseFileId(pFile->pId);
25894    pFile->pId = 0;
25895  }
25896#endif
25897  OSTRACE(("CLOSE   %-3d\n", pFile->h));
25898  OpenCounter(-1);
25899  sqlite3_free(pFile->pUnused);
25900  memset(pFile, 0, sizeof(unixFile));
25901  return SQLITE_OK;
25902}
25903
25904/*
25905** Close a file.
25906*/
25907static int unixClose(sqlite3_file *id){
25908  int rc = SQLITE_OK;
25909  unixFile *pFile = (unixFile *)id;
25910  unixUnlock(id, NO_LOCK);
25911  unixEnterMutex();
25912
25913  /* unixFile.pInode is always valid here. Otherwise, a different close
25914  ** routine (e.g. nolockClose()) would be called instead.
25915  */
25916  assert( pFile->pInode->nLock>0 || pFile->pInode->bProcessLock==0 );
25917  if( ALWAYS(pFile->pInode) && pFile->pInode->nLock ){
25918    /* If there are outstanding locks, do not actually close the file just
25919    ** yet because that would clear those locks.  Instead, add the file
25920    ** descriptor to pInode->pUnused list.  It will be automatically closed
25921    ** when the last lock is cleared.
25922    */
25923    setPendingFd(pFile);
25924  }
25925  releaseInodeInfo(pFile);
25926  rc = closeUnixFile(id);
25927  unixLeaveMutex();
25928  return rc;
25929}
25930
25931/************** End of the posix advisory lock implementation *****************
25932******************************************************************************/
25933
25934/******************************************************************************
25935****************************** No-op Locking **********************************
25936**
25937** Of the various locking implementations available, this is by far the
25938** simplest:  locking is ignored.  No attempt is made to lock the database
25939** file for reading or writing.
25940**
25941** This locking mode is appropriate for use on read-only databases
25942** (ex: databases that are burned into CD-ROM, for example.)  It can
25943** also be used if the application employs some external mechanism to
25944** prevent simultaneous access of the same database by two or more
25945** database connections.  But there is a serious risk of database
25946** corruption if this locking mode is used in situations where multiple
25947** database connections are accessing the same database file at the same
25948** time and one or more of those connections are writing.
25949*/
25950
25951static int nolockCheckReservedLock(sqlite3_file *NotUsed, int *pResOut){
25952  UNUSED_PARAMETER(NotUsed);
25953  *pResOut = 0;
25954  return SQLITE_OK;
25955}
25956static int nolockLock(sqlite3_file *NotUsed, int NotUsed2){
25957  UNUSED_PARAMETER2(NotUsed, NotUsed2);
25958  return SQLITE_OK;
25959}
25960static int nolockUnlock(sqlite3_file *NotUsed, int NotUsed2){
25961  UNUSED_PARAMETER2(NotUsed, NotUsed2);
25962  return SQLITE_OK;
25963}
25964
25965/*
25966** Close the file.
25967*/
25968static int nolockClose(sqlite3_file *id) {
25969  return closeUnixFile(id);
25970}
25971
25972/******************* End of the no-op lock implementation *********************
25973******************************************************************************/
25974
25975/******************************************************************************
25976************************* Begin dot-file Locking ******************************
25977**
25978** The dotfile locking implementation uses the existance of separate lock
25979** files in order to control access to the database.  This works on just
25980** about every filesystem imaginable.  But there are serious downsides:
25981**
25982**    (1)  There is zero concurrency.  A single reader blocks all other
25983**         connections from reading or writing the database.
25984**
25985**    (2)  An application crash or power loss can leave stale lock files
25986**         sitting around that need to be cleared manually.
25987**
25988** Nevertheless, a dotlock is an appropriate locking mode for use if no
25989** other locking strategy is available.
25990**
25991** Dotfile locking works by creating a file in the same directory as the
25992** database and with the same name but with a ".lock" extension added.
25993** The existance of a lock file implies an EXCLUSIVE lock.  All other lock
25994** types (SHARED, RESERVED, PENDING) are mapped into EXCLUSIVE.
25995*/
25996
25997/*
25998** The file suffix added to the data base filename in order to create the
25999** lock file.
26000*/
26001#define DOTLOCK_SUFFIX ".lock"
26002
26003/*
26004** This routine checks if there is a RESERVED lock held on the specified
26005** file by this or any other process. If such a lock is held, set *pResOut
26006** to a non-zero value otherwise *pResOut is set to zero.  The return value
26007** is set to SQLITE_OK unless an I/O error occurs during lock checking.
26008**
26009** In dotfile locking, either a lock exists or it does not.  So in this
26010** variation of CheckReservedLock(), *pResOut is set to true if any lock
26011** is held on the file and false if the file is unlocked.
26012*/
26013static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) {
26014  int rc = SQLITE_OK;
26015  int reserved = 0;
26016  unixFile *pFile = (unixFile*)id;
26017
26018  SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
26019
26020  assert( pFile );
26021
26022  /* Check if a thread in this process holds such a lock */
26023  if( pFile->eFileLock>SHARED_LOCK ){
26024    /* Either this connection or some other connection in the same process
26025    ** holds a lock on the file.  No need to check further. */
26026    reserved = 1;
26027  }else{
26028    /* The lock is held if and only if the lockfile exists */
26029    const char *zLockFile = (const char*)pFile->lockingContext;
26030    reserved = osAccess(zLockFile, 0)==0;
26031  }
26032  OSTRACE(("TEST WR-LOCK %d %d %d (dotlock)\n", pFile->h, rc, reserved));
26033  *pResOut = reserved;
26034  return rc;
26035}
26036
26037/*
26038** Lock the file with the lock specified by parameter eFileLock - one
26039** of the following:
26040**
26041**     (1) SHARED_LOCK
26042**     (2) RESERVED_LOCK
26043**     (3) PENDING_LOCK
26044**     (4) EXCLUSIVE_LOCK
26045**
26046** Sometimes when requesting one lock state, additional lock states
26047** are inserted in between.  The locking might fail on one of the later
26048** transitions leaving the lock state different from what it started but
26049** still short of its goal.  The following chart shows the allowed
26050** transitions and the inserted intermediate states:
26051**
26052**    UNLOCKED -> SHARED
26053**    SHARED -> RESERVED
26054**    SHARED -> (PENDING) -> EXCLUSIVE
26055**    RESERVED -> (PENDING) -> EXCLUSIVE
26056**    PENDING -> EXCLUSIVE
26057**
26058** This routine will only increase a lock.  Use the sqlite3OsUnlock()
26059** routine to lower a locking level.
26060**
26061** With dotfile locking, we really only support state (4): EXCLUSIVE.
26062** But we track the other locking levels internally.
26063*/
26064static int dotlockLock(sqlite3_file *id, int eFileLock) {
26065  unixFile *pFile = (unixFile*)id;
26066  int fd;
26067  char *zLockFile = (char *)pFile->lockingContext;
26068  int rc = SQLITE_OK;
26069
26070
26071  /* If we have any lock, then the lock file already exists.  All we have
26072  ** to do is adjust our internal record of the lock level.
26073  */
26074  if( pFile->eFileLock > NO_LOCK ){
26075    pFile->eFileLock = eFileLock;
26076#if !OS_VXWORKS
26077    /* Always update the timestamp on the old file */
26078    utimes(zLockFile, NULL);
26079#endif
26080    return SQLITE_OK;
26081  }
26082
26083  /* grab an exclusive lock */
26084  fd = robust_open(zLockFile,O_RDONLY|O_CREAT|O_EXCL,0600);
26085  if( fd<0 ){
26086    /* failed to open/create the file, someone else may have stolen the lock */
26087    int tErrno = errno;
26088    if( EEXIST == tErrno ){
26089      rc = SQLITE_BUSY;
26090    } else {
26091      rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
26092      if( IS_LOCK_ERROR(rc) ){
26093        pFile->lastErrno = tErrno;
26094      }
26095    }
26096    return rc;
26097  }
26098  robust_close(pFile, fd, __LINE__);
26099
26100  /* got it, set the type and return ok */
26101  pFile->eFileLock = eFileLock;
26102  return rc;
26103}
26104
26105/*
26106** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
26107** must be either NO_LOCK or SHARED_LOCK.
26108**
26109** If the locking level of the file descriptor is already at or below
26110** the requested locking level, this routine is a no-op.
26111**
26112** When the locking level reaches NO_LOCK, delete the lock file.
26113*/
26114static int dotlockUnlock(sqlite3_file *id, int eFileLock) {
26115  unixFile *pFile = (unixFile*)id;
26116  char *zLockFile = (char *)pFile->lockingContext;
26117
26118  assert( pFile );
26119  OSTRACE(("UNLOCK  %d %d was %d pid=%d (dotlock)\n", pFile->h, eFileLock,
26120	   pFile->eFileLock, getpid()));
26121  assert( eFileLock<=SHARED_LOCK );
26122
26123  /* no-op if possible */
26124  if( pFile->eFileLock==eFileLock ){
26125    return SQLITE_OK;
26126  }
26127
26128  /* To downgrade to shared, simply update our internal notion of the
26129  ** lock state.  No need to mess with the file on disk.
26130  */
26131  if( eFileLock==SHARED_LOCK ){
26132    pFile->eFileLock = SHARED_LOCK;
26133    return SQLITE_OK;
26134  }
26135
26136  /* To fully unlock the database, delete the lock file */
26137  assert( eFileLock==NO_LOCK );
26138  if( osUnlink(zLockFile) ){
26139    int rc = 0;
26140    int tErrno = errno;
26141    if( ENOENT != tErrno ){
26142      rc = SQLITE_IOERR_UNLOCK;
26143    }
26144    if( IS_LOCK_ERROR(rc) ){
26145      pFile->lastErrno = tErrno;
26146    }
26147    return rc;
26148  }
26149  pFile->eFileLock = NO_LOCK;
26150  return SQLITE_OK;
26151}
26152
26153/*
26154** Close a file.  Make sure the lock has been released before closing.
26155*/
26156static int dotlockClose(sqlite3_file *id) {
26157  int rc;
26158  if( id ){
26159    unixFile *pFile = (unixFile*)id;
26160    dotlockUnlock(id, NO_LOCK);
26161    sqlite3_free(pFile->lockingContext);
26162  }
26163  rc = closeUnixFile(id);
26164  return rc;
26165}
26166/****************** End of the dot-file lock implementation *******************
26167******************************************************************************/
26168
26169/******************************************************************************
26170************************** Begin flock Locking ********************************
26171**
26172** Use the flock() system call to do file locking.
26173**
26174** flock() locking is like dot-file locking in that the various
26175** fine-grain locking levels supported by SQLite are collapsed into
26176** a single exclusive lock.  In other words, SHARED, RESERVED, and
26177** PENDING locks are the same thing as an EXCLUSIVE lock.  SQLite
26178** still works when you do this, but concurrency is reduced since
26179** only a single process can be reading the database at a time.
26180**
26181** Omit this section if SQLITE_ENABLE_LOCKING_STYLE is turned off or if
26182** compiling for VXWORKS.
26183*/
26184#if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
26185
26186/*
26187** Retry flock() calls that fail with EINTR
26188*/
26189#ifdef EINTR
26190static int robust_flock(int fd, int op){
26191  int rc;
26192  do{ rc = flock(fd,op); }while( rc<0 && errno==EINTR );
26193  return rc;
26194}
26195#else
26196# define robust_flock(a,b) flock(a,b)
26197#endif
26198
26199
26200/*
26201** This routine checks if there is a RESERVED lock held on the specified
26202** file by this or any other process. If such a lock is held, set *pResOut
26203** to a non-zero value otherwise *pResOut is set to zero.  The return value
26204** is set to SQLITE_OK unless an I/O error occurs during lock checking.
26205*/
26206static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){
26207  int rc = SQLITE_OK;
26208  int reserved = 0;
26209  unixFile *pFile = (unixFile*)id;
26210
26211  SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
26212
26213  assert( pFile );
26214
26215  /* Check if a thread in this process holds such a lock */
26216  if( pFile->eFileLock>SHARED_LOCK ){
26217    reserved = 1;
26218  }
26219
26220  /* Otherwise see if some other process holds it. */
26221  if( !reserved ){
26222    /* attempt to get the lock */
26223    int lrc = robust_flock(pFile->h, LOCK_EX | LOCK_NB);
26224    if( !lrc ){
26225      /* got the lock, unlock it */
26226      lrc = robust_flock(pFile->h, LOCK_UN);
26227      if ( lrc ) {
26228        int tErrno = errno;
26229        /* unlock failed with an error */
26230        lrc = SQLITE_IOERR_UNLOCK;
26231        if( IS_LOCK_ERROR(lrc) ){
26232          pFile->lastErrno = tErrno;
26233          rc = lrc;
26234        }
26235      }
26236    } else {
26237      int tErrno = errno;
26238      reserved = 1;
26239      /* someone else might have it reserved */
26240      lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
26241      if( IS_LOCK_ERROR(lrc) ){
26242        pFile->lastErrno = tErrno;
26243        rc = lrc;
26244      }
26245    }
26246  }
26247  OSTRACE(("TEST WR-LOCK %d %d %d (flock)\n", pFile->h, rc, reserved));
26248
26249#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
26250  if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
26251    rc = SQLITE_OK;
26252    reserved=1;
26253  }
26254#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
26255  *pResOut = reserved;
26256  return rc;
26257}
26258
26259/*
26260** Lock the file with the lock specified by parameter eFileLock - one
26261** of the following:
26262**
26263**     (1) SHARED_LOCK
26264**     (2) RESERVED_LOCK
26265**     (3) PENDING_LOCK
26266**     (4) EXCLUSIVE_LOCK
26267**
26268** Sometimes when requesting one lock state, additional lock states
26269** are inserted in between.  The locking might fail on one of the later
26270** transitions leaving the lock state different from what it started but
26271** still short of its goal.  The following chart shows the allowed
26272** transitions and the inserted intermediate states:
26273**
26274**    UNLOCKED -> SHARED
26275**    SHARED -> RESERVED
26276**    SHARED -> (PENDING) -> EXCLUSIVE
26277**    RESERVED -> (PENDING) -> EXCLUSIVE
26278**    PENDING -> EXCLUSIVE
26279**
26280** flock() only really support EXCLUSIVE locks.  We track intermediate
26281** lock states in the sqlite3_file structure, but all locks SHARED or
26282** above are really EXCLUSIVE locks and exclude all other processes from
26283** access the file.
26284**
26285** This routine will only increase a lock.  Use the sqlite3OsUnlock()
26286** routine to lower a locking level.
26287*/
26288static int flockLock(sqlite3_file *id, int eFileLock) {
26289  int rc = SQLITE_OK;
26290  unixFile *pFile = (unixFile*)id;
26291
26292  assert( pFile );
26293
26294  /* if we already have a lock, it is exclusive.
26295  ** Just adjust level and punt on outta here. */
26296  if (pFile->eFileLock > NO_LOCK) {
26297    pFile->eFileLock = eFileLock;
26298    return SQLITE_OK;
26299  }
26300
26301  /* grab an exclusive lock */
26302
26303  if (robust_flock(pFile->h, LOCK_EX | LOCK_NB)) {
26304    int tErrno = errno;
26305    /* didn't get, must be busy */
26306    rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
26307    if( IS_LOCK_ERROR(rc) ){
26308      pFile->lastErrno = tErrno;
26309    }
26310  } else {
26311    /* got it, set the type and return ok */
26312    pFile->eFileLock = eFileLock;
26313  }
26314  OSTRACE(("LOCK    %d %s %s (flock)\n", pFile->h, azFileLock(eFileLock),
26315           rc==SQLITE_OK ? "ok" : "failed"));
26316#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
26317  if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
26318    rc = SQLITE_BUSY;
26319  }
26320#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
26321  return rc;
26322}
26323
26324
26325/*
26326** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
26327** must be either NO_LOCK or SHARED_LOCK.
26328**
26329** If the locking level of the file descriptor is already at or below
26330** the requested locking level, this routine is a no-op.
26331*/
26332static int flockUnlock(sqlite3_file *id, int eFileLock) {
26333  unixFile *pFile = (unixFile*)id;
26334
26335  assert( pFile );
26336  OSTRACE(("UNLOCK  %d %d was %d pid=%d (flock)\n", pFile->h, eFileLock,
26337           pFile->eFileLock, getpid()));
26338  assert( eFileLock<=SHARED_LOCK );
26339
26340  /* no-op if possible */
26341  if( pFile->eFileLock==eFileLock ){
26342    return SQLITE_OK;
26343  }
26344
26345  /* shared can just be set because we always have an exclusive */
26346  if (eFileLock==SHARED_LOCK) {
26347    pFile->eFileLock = eFileLock;
26348    return SQLITE_OK;
26349  }
26350
26351  /* no, really, unlock. */
26352  if( robust_flock(pFile->h, LOCK_UN) ){
26353#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
26354    return SQLITE_OK;
26355#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
26356    return SQLITE_IOERR_UNLOCK;
26357  }else{
26358    pFile->eFileLock = NO_LOCK;
26359    return SQLITE_OK;
26360  }
26361}
26362
26363/*
26364** Close a file.
26365*/
26366static int flockClose(sqlite3_file *id) {
26367  if( id ){
26368    flockUnlock(id, NO_LOCK);
26369  }
26370  return closeUnixFile(id);
26371}
26372
26373#endif /* SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORK */
26374
26375/******************* End of the flock lock implementation *********************
26376******************************************************************************/
26377
26378/******************************************************************************
26379************************ Begin Named Semaphore Locking ************************
26380**
26381** Named semaphore locking is only supported on VxWorks.
26382**
26383** Semaphore locking is like dot-lock and flock in that it really only
26384** supports EXCLUSIVE locking.  Only a single process can read or write
26385** the database file at a time.  This reduces potential concurrency, but
26386** makes the lock implementation much easier.
26387*/
26388#if OS_VXWORKS
26389
26390/*
26391** This routine checks if there is a RESERVED lock held on the specified
26392** file by this or any other process. If such a lock is held, set *pResOut
26393** to a non-zero value otherwise *pResOut is set to zero.  The return value
26394** is set to SQLITE_OK unless an I/O error occurs during lock checking.
26395*/
26396static int semCheckReservedLock(sqlite3_file *id, int *pResOut) {
26397  int rc = SQLITE_OK;
26398  int reserved = 0;
26399  unixFile *pFile = (unixFile*)id;
26400
26401  SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
26402
26403  assert( pFile );
26404
26405  /* Check if a thread in this process holds such a lock */
26406  if( pFile->eFileLock>SHARED_LOCK ){
26407    reserved = 1;
26408  }
26409
26410  /* Otherwise see if some other process holds it. */
26411  if( !reserved ){
26412    sem_t *pSem = pFile->pInode->pSem;
26413    struct stat statBuf;
26414
26415    if( sem_trywait(pSem)==-1 ){
26416      int tErrno = errno;
26417      if( EAGAIN != tErrno ){
26418        rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
26419        pFile->lastErrno = tErrno;
26420      } else {
26421        /* someone else has the lock when we are in NO_LOCK */
26422        reserved = (pFile->eFileLock < SHARED_LOCK);
26423      }
26424    }else{
26425      /* we could have it if we want it */
26426      sem_post(pSem);
26427    }
26428  }
26429  OSTRACE(("TEST WR-LOCK %d %d %d (sem)\n", pFile->h, rc, reserved));
26430
26431  *pResOut = reserved;
26432  return rc;
26433}
26434
26435/*
26436** Lock the file with the lock specified by parameter eFileLock - one
26437** of the following:
26438**
26439**     (1) SHARED_LOCK
26440**     (2) RESERVED_LOCK
26441**     (3) PENDING_LOCK
26442**     (4) EXCLUSIVE_LOCK
26443**
26444** Sometimes when requesting one lock state, additional lock states
26445** are inserted in between.  The locking might fail on one of the later
26446** transitions leaving the lock state different from what it started but
26447** still short of its goal.  The following chart shows the allowed
26448** transitions and the inserted intermediate states:
26449**
26450**    UNLOCKED -> SHARED
26451**    SHARED -> RESERVED
26452**    SHARED -> (PENDING) -> EXCLUSIVE
26453**    RESERVED -> (PENDING) -> EXCLUSIVE
26454**    PENDING -> EXCLUSIVE
26455**
26456** Semaphore locks only really support EXCLUSIVE locks.  We track intermediate
26457** lock states in the sqlite3_file structure, but all locks SHARED or
26458** above are really EXCLUSIVE locks and exclude all other processes from
26459** access the file.
26460**
26461** This routine will only increase a lock.  Use the sqlite3OsUnlock()
26462** routine to lower a locking level.
26463*/
26464static int semLock(sqlite3_file *id, int eFileLock) {
26465  unixFile *pFile = (unixFile*)id;
26466  int fd;
26467  sem_t *pSem = pFile->pInode->pSem;
26468  int rc = SQLITE_OK;
26469
26470  /* if we already have a lock, it is exclusive.
26471  ** Just adjust level and punt on outta here. */
26472  if (pFile->eFileLock > NO_LOCK) {
26473    pFile->eFileLock = eFileLock;
26474    rc = SQLITE_OK;
26475    goto sem_end_lock;
26476  }
26477
26478  /* lock semaphore now but bail out when already locked. */
26479  if( sem_trywait(pSem)==-1 ){
26480    rc = SQLITE_BUSY;
26481    goto sem_end_lock;
26482  }
26483
26484  /* got it, set the type and return ok */
26485  pFile->eFileLock = eFileLock;
26486
26487 sem_end_lock:
26488  return rc;
26489}
26490
26491/*
26492** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
26493** must be either NO_LOCK or SHARED_LOCK.
26494**
26495** If the locking level of the file descriptor is already at or below
26496** the requested locking level, this routine is a no-op.
26497*/
26498static int semUnlock(sqlite3_file *id, int eFileLock) {
26499  unixFile *pFile = (unixFile*)id;
26500  sem_t *pSem = pFile->pInode->pSem;
26501
26502  assert( pFile );
26503  assert( pSem );
26504  OSTRACE(("UNLOCK  %d %d was %d pid=%d (sem)\n", pFile->h, eFileLock,
26505	   pFile->eFileLock, getpid()));
26506  assert( eFileLock<=SHARED_LOCK );
26507
26508  /* no-op if possible */
26509  if( pFile->eFileLock==eFileLock ){
26510    return SQLITE_OK;
26511  }
26512
26513  /* shared can just be set because we always have an exclusive */
26514  if (eFileLock==SHARED_LOCK) {
26515    pFile->eFileLock = eFileLock;
26516    return SQLITE_OK;
26517  }
26518
26519  /* no, really unlock. */
26520  if ( sem_post(pSem)==-1 ) {
26521    int rc, tErrno = errno;
26522    rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
26523    if( IS_LOCK_ERROR(rc) ){
26524      pFile->lastErrno = tErrno;
26525    }
26526    return rc;
26527  }
26528  pFile->eFileLock = NO_LOCK;
26529  return SQLITE_OK;
26530}
26531
26532/*
26533 ** Close a file.
26534 */
26535static int semClose(sqlite3_file *id) {
26536  if( id ){
26537    unixFile *pFile = (unixFile*)id;
26538    semUnlock(id, NO_LOCK);
26539    assert( pFile );
26540    unixEnterMutex();
26541    releaseInodeInfo(pFile);
26542    unixLeaveMutex();
26543    closeUnixFile(id);
26544  }
26545  return SQLITE_OK;
26546}
26547
26548#endif /* OS_VXWORKS */
26549/*
26550** Named semaphore locking is only available on VxWorks.
26551**
26552*************** End of the named semaphore lock implementation ****************
26553******************************************************************************/
26554
26555
26556/******************************************************************************
26557*************************** Begin AFP Locking *********************************
26558**
26559** AFP is the Apple Filing Protocol.  AFP is a network filesystem found
26560** on Apple Macintosh computers - both OS9 and OSX.
26561**
26562** Third-party implementations of AFP are available.  But this code here
26563** only works on OSX.
26564*/
26565
26566#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
26567/*
26568** The afpLockingContext structure contains all afp lock specific state
26569*/
26570typedef struct afpLockingContext afpLockingContext;
26571struct afpLockingContext {
26572  int reserved;
26573  const char *dbPath;             /* Name of the open file */
26574};
26575
26576struct ByteRangeLockPB2
26577{
26578  unsigned long long offset;        /* offset to first byte to lock */
26579  unsigned long long length;        /* nbr of bytes to lock */
26580  unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
26581  unsigned char unLockFlag;         /* 1 = unlock, 0 = lock */
26582  unsigned char startEndFlag;       /* 1=rel to end of fork, 0=rel to start */
26583  int fd;                           /* file desc to assoc this lock with */
26584};
26585
26586#define afpfsByteRangeLock2FSCTL        _IOWR('z', 23, struct ByteRangeLockPB2)
26587
26588/*
26589** This is a utility for setting or clearing a bit-range lock on an
26590** AFP filesystem.
26591**
26592** Return SQLITE_OK on success, SQLITE_BUSY on failure.
26593*/
26594static int afpSetLock(
26595  const char *path,              /* Name of the file to be locked or unlocked */
26596  unixFile *pFile,               /* Open file descriptor on path */
26597  unsigned long long offset,     /* First byte to be locked */
26598  unsigned long long length,     /* Number of bytes to lock */
26599  int setLockFlag                /* True to set lock.  False to clear lock */
26600){
26601  struct ByteRangeLockPB2 pb;
26602  int err;
26603
26604  pb.unLockFlag = setLockFlag ? 0 : 1;
26605  pb.startEndFlag = 0;
26606  pb.offset = offset;
26607  pb.length = length;
26608  pb.fd = pFile->h;
26609
26610  OSTRACE(("AFPSETLOCK [%s] for %d%s in range %llx:%llx\n",
26611    (setLockFlag?"ON":"OFF"), pFile->h, (pb.fd==-1?"[testval-1]":""),
26612    offset, length));
26613  err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
26614  if ( err==-1 ) {
26615    int rc;
26616    int tErrno = errno;
26617    OSTRACE(("AFPSETLOCK failed to fsctl() '%s' %d %s\n",
26618             path, tErrno, strerror(tErrno)));
26619#ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
26620    rc = SQLITE_BUSY;
26621#else
26622    rc = sqliteErrorFromPosixError(tErrno,
26623                    setLockFlag ? SQLITE_IOERR_LOCK : SQLITE_IOERR_UNLOCK);
26624#endif /* SQLITE_IGNORE_AFP_LOCK_ERRORS */
26625    if( IS_LOCK_ERROR(rc) ){
26626      pFile->lastErrno = tErrno;
26627    }
26628    return rc;
26629  } else {
26630    return SQLITE_OK;
26631  }
26632}
26633
26634/*
26635** This routine checks if there is a RESERVED lock held on the specified
26636** file by this or any other process. If such a lock is held, set *pResOut
26637** to a non-zero value otherwise *pResOut is set to zero.  The return value
26638** is set to SQLITE_OK unless an I/O error occurs during lock checking.
26639*/
26640static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){
26641  int rc = SQLITE_OK;
26642  int reserved = 0;
26643  unixFile *pFile = (unixFile*)id;
26644
26645  SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
26646
26647  assert( pFile );
26648  afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
26649  if( context->reserved ){
26650    *pResOut = 1;
26651    return SQLITE_OK;
26652  }
26653  unixEnterMutex(); /* Because pFile->pInode is shared across threads */
26654
26655  /* Check if a thread in this process holds such a lock */
26656  if( pFile->pInode->eFileLock>SHARED_LOCK ){
26657    reserved = 1;
26658  }
26659
26660  /* Otherwise see if some other process holds it.
26661   */
26662  if( !reserved ){
26663    /* lock the RESERVED byte */
26664    int lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
26665    if( SQLITE_OK==lrc ){
26666      /* if we succeeded in taking the reserved lock, unlock it to restore
26667      ** the original state */
26668      lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
26669    } else {
26670      /* if we failed to get the lock then someone else must have it */
26671      reserved = 1;
26672    }
26673    if( IS_LOCK_ERROR(lrc) ){
26674      rc=lrc;
26675    }
26676  }
26677
26678  unixLeaveMutex();
26679  OSTRACE(("TEST WR-LOCK %d %d %d (afp)\n", pFile->h, rc, reserved));
26680
26681  *pResOut = reserved;
26682  return rc;
26683}
26684
26685/*
26686** Lock the file with the lock specified by parameter eFileLock - one
26687** of the following:
26688**
26689**     (1) SHARED_LOCK
26690**     (2) RESERVED_LOCK
26691**     (3) PENDING_LOCK
26692**     (4) EXCLUSIVE_LOCK
26693**
26694** Sometimes when requesting one lock state, additional lock states
26695** are inserted in between.  The locking might fail on one of the later
26696** transitions leaving the lock state different from what it started but
26697** still short of its goal.  The following chart shows the allowed
26698** transitions and the inserted intermediate states:
26699**
26700**    UNLOCKED -> SHARED
26701**    SHARED -> RESERVED
26702**    SHARED -> (PENDING) -> EXCLUSIVE
26703**    RESERVED -> (PENDING) -> EXCLUSIVE
26704**    PENDING -> EXCLUSIVE
26705**
26706** This routine will only increase a lock.  Use the sqlite3OsUnlock()
26707** routine to lower a locking level.
26708*/
26709static int afpLock(sqlite3_file *id, int eFileLock){
26710  int rc = SQLITE_OK;
26711  unixFile *pFile = (unixFile*)id;
26712  unixInodeInfo *pInode = pFile->pInode;
26713  afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
26714
26715  assert( pFile );
26716  OSTRACE(("LOCK    %d %s was %s(%s,%d) pid=%d (afp)\n", pFile->h,
26717           azFileLock(eFileLock), azFileLock(pFile->eFileLock),
26718           azFileLock(pInode->eFileLock), pInode->nShared , getpid()));
26719
26720  /* If there is already a lock of this type or more restrictive on the
26721  ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
26722  ** unixEnterMutex() hasn't been called yet.
26723  */
26724  if( pFile->eFileLock>=eFileLock ){
26725    OSTRACE(("LOCK    %d %s ok (already held) (afp)\n", pFile->h,
26726           azFileLock(eFileLock)));
26727    return SQLITE_OK;
26728  }
26729
26730  /* Make sure the locking sequence is correct
26731  **  (1) We never move from unlocked to anything higher than shared lock.
26732  **  (2) SQLite never explicitly requests a pendig lock.
26733  **  (3) A shared lock is always held when a reserve lock is requested.
26734  */
26735  assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
26736  assert( eFileLock!=PENDING_LOCK );
26737  assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
26738
26739  /* This mutex is needed because pFile->pInode is shared across threads
26740  */
26741  unixEnterMutex();
26742  pInode = pFile->pInode;
26743
26744  /* If some thread using this PID has a lock via a different unixFile*
26745  ** handle that precludes the requested lock, return BUSY.
26746  */
26747  if( (pFile->eFileLock!=pInode->eFileLock &&
26748       (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
26749     ){
26750    rc = SQLITE_BUSY;
26751    goto afp_end_lock;
26752  }
26753
26754  /* If a SHARED lock is requested, and some thread using this PID already
26755  ** has a SHARED or RESERVED lock, then increment reference counts and
26756  ** return SQLITE_OK.
26757  */
26758  if( eFileLock==SHARED_LOCK &&
26759     (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
26760    assert( eFileLock==SHARED_LOCK );
26761    assert( pFile->eFileLock==0 );
26762    assert( pInode->nShared>0 );
26763    pFile->eFileLock = SHARED_LOCK;
26764    pInode->nShared++;
26765    pInode->nLock++;
26766    goto afp_end_lock;
26767  }
26768
26769  /* A PENDING lock is needed before acquiring a SHARED lock and before
26770  ** acquiring an EXCLUSIVE lock.  For the SHARED lock, the PENDING will
26771  ** be released.
26772  */
26773  if( eFileLock==SHARED_LOCK
26774      || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
26775  ){
26776    int failed;
26777    failed = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 1);
26778    if (failed) {
26779      rc = failed;
26780      goto afp_end_lock;
26781    }
26782  }
26783
26784  /* If control gets to this point, then actually go ahead and make
26785  ** operating system calls for the specified lock.
26786  */
26787  if( eFileLock==SHARED_LOCK ){
26788    int lrc1, lrc2, lrc1Errno;
26789    long lk, mask;
26790
26791    assert( pInode->nShared==0 );
26792    assert( pInode->eFileLock==0 );
26793
26794    mask = (sizeof(long)==8) ? LARGEST_INT64 : 0x7fffffff;
26795    /* Now get the read-lock SHARED_LOCK */
26796    /* note that the quality of the randomness doesn't matter that much */
26797    lk = random();
26798    pInode->sharedByte = (lk & mask)%(SHARED_SIZE - 1);
26799    lrc1 = afpSetLock(context->dbPath, pFile,
26800          SHARED_FIRST+pInode->sharedByte, 1, 1);
26801    if( IS_LOCK_ERROR(lrc1) ){
26802      lrc1Errno = pFile->lastErrno;
26803    }
26804    /* Drop the temporary PENDING lock */
26805    lrc2 = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
26806
26807    if( IS_LOCK_ERROR(lrc1) ) {
26808      pFile->lastErrno = lrc1Errno;
26809      rc = lrc1;
26810      goto afp_end_lock;
26811    } else if( IS_LOCK_ERROR(lrc2) ){
26812      rc = lrc2;
26813      goto afp_end_lock;
26814    } else if( lrc1 != SQLITE_OK ) {
26815      rc = lrc1;
26816    } else {
26817      pFile->eFileLock = SHARED_LOCK;
26818      pInode->nLock++;
26819      pInode->nShared = 1;
26820    }
26821  }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
26822    /* We are trying for an exclusive lock but another thread in this
26823     ** same process is still holding a shared lock. */
26824    rc = SQLITE_BUSY;
26825  }else{
26826    /* The request was for a RESERVED or EXCLUSIVE lock.  It is
26827    ** assumed that there is a SHARED or greater lock on the file
26828    ** already.
26829    */
26830    int failed = 0;
26831    assert( 0!=pFile->eFileLock );
26832    if (eFileLock >= RESERVED_LOCK && pFile->eFileLock < RESERVED_LOCK) {
26833        /* Acquire a RESERVED lock */
26834        failed = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
26835      if( !failed ){
26836        context->reserved = 1;
26837      }
26838    }
26839    if (!failed && eFileLock == EXCLUSIVE_LOCK) {
26840      /* Acquire an EXCLUSIVE lock */
26841
26842      /* Remove the shared lock before trying the range.  we'll need to
26843      ** reestablish the shared lock if we can't get the  afpUnlock
26844      */
26845      if( !(failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST +
26846                         pInode->sharedByte, 1, 0)) ){
26847        int failed2 = SQLITE_OK;
26848        /* now attemmpt to get the exclusive lock range */
26849        failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST,
26850                               SHARED_SIZE, 1);
26851        if( failed && (failed2 = afpSetLock(context->dbPath, pFile,
26852                       SHARED_FIRST + pInode->sharedByte, 1, 1)) ){
26853          /* Can't reestablish the shared lock.  Sqlite can't deal, this is
26854          ** a critical I/O error
26855          */
26856          rc = ((failed & SQLITE_IOERR) == SQLITE_IOERR) ? failed2 :
26857               SQLITE_IOERR_LOCK;
26858          goto afp_end_lock;
26859        }
26860      }else{
26861        rc = failed;
26862      }
26863    }
26864    if( failed ){
26865      rc = failed;
26866    }
26867  }
26868
26869  if( rc==SQLITE_OK ){
26870    pFile->eFileLock = eFileLock;
26871    pInode->eFileLock = eFileLock;
26872  }else if( eFileLock==EXCLUSIVE_LOCK ){
26873    pFile->eFileLock = PENDING_LOCK;
26874    pInode->eFileLock = PENDING_LOCK;
26875  }
26876
26877afp_end_lock:
26878  unixLeaveMutex();
26879  OSTRACE(("LOCK    %d %s %s (afp)\n", pFile->h, azFileLock(eFileLock),
26880         rc==SQLITE_OK ? "ok" : "failed"));
26881  return rc;
26882}
26883
26884/*
26885** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
26886** must be either NO_LOCK or SHARED_LOCK.
26887**
26888** If the locking level of the file descriptor is already at or below
26889** the requested locking level, this routine is a no-op.
26890*/
26891static int afpUnlock(sqlite3_file *id, int eFileLock) {
26892  int rc = SQLITE_OK;
26893  unixFile *pFile = (unixFile*)id;
26894  unixInodeInfo *pInode;
26895  afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
26896  int skipShared = 0;
26897#ifdef SQLITE_TEST
26898  int h = pFile->h;
26899#endif
26900
26901  assert( pFile );
26902  OSTRACE(("UNLOCK  %d %d was %d(%d,%d) pid=%d (afp)\n", pFile->h, eFileLock,
26903           pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
26904           getpid()));
26905
26906  assert( eFileLock<=SHARED_LOCK );
26907  if( pFile->eFileLock<=eFileLock ){
26908    return SQLITE_OK;
26909  }
26910  unixEnterMutex();
26911  pInode = pFile->pInode;
26912  assert( pInode->nShared!=0 );
26913  if( pFile->eFileLock>SHARED_LOCK ){
26914    assert( pInode->eFileLock==pFile->eFileLock );
26915    SimulateIOErrorBenign(1);
26916    SimulateIOError( h=(-1) )
26917    SimulateIOErrorBenign(0);
26918
26919#ifndef NDEBUG
26920    /* When reducing a lock such that other processes can start
26921    ** reading the database file again, make sure that the
26922    ** transaction counter was updated if any part of the database
26923    ** file changed.  If the transaction counter is not updated,
26924    ** other connections to the same file might not realize that
26925    ** the file has changed and hence might not know to flush their
26926    ** cache.  The use of a stale cache can lead to database corruption.
26927    */
26928    assert( pFile->inNormalWrite==0
26929           || pFile->dbUpdate==0
26930           || pFile->transCntrChng==1 );
26931    pFile->inNormalWrite = 0;
26932#endif
26933
26934    if( pFile->eFileLock==EXCLUSIVE_LOCK ){
26935      rc = afpSetLock(context->dbPath, pFile, SHARED_FIRST, SHARED_SIZE, 0);
26936      if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1) ){
26937        /* only re-establish the shared lock if necessary */
26938        int sharedLockByte = SHARED_FIRST+pInode->sharedByte;
26939        rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 1);
26940      } else {
26941        skipShared = 1;
26942      }
26943    }
26944    if( rc==SQLITE_OK && pFile->eFileLock>=PENDING_LOCK ){
26945      rc = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
26946    }
26947    if( rc==SQLITE_OK && pFile->eFileLock>=RESERVED_LOCK && context->reserved ){
26948      rc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
26949      if( !rc ){
26950        context->reserved = 0;
26951      }
26952    }
26953    if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1)){
26954      pInode->eFileLock = SHARED_LOCK;
26955    }
26956  }
26957  if( rc==SQLITE_OK && eFileLock==NO_LOCK ){
26958
26959    /* Decrement the shared lock counter.  Release the lock using an
26960    ** OS call only when all threads in this same process have released
26961    ** the lock.
26962    */
26963    unsigned long long sharedLockByte = SHARED_FIRST+pInode->sharedByte;
26964    pInode->nShared--;
26965    if( pInode->nShared==0 ){
26966      SimulateIOErrorBenign(1);
26967      SimulateIOError( h=(-1) )
26968      SimulateIOErrorBenign(0);
26969      if( !skipShared ){
26970        rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 0);
26971      }
26972      if( !rc ){
26973        pInode->eFileLock = NO_LOCK;
26974        pFile->eFileLock = NO_LOCK;
26975      }
26976    }
26977    if( rc==SQLITE_OK ){
26978      pInode->nLock--;
26979      assert( pInode->nLock>=0 );
26980      if( pInode->nLock==0 ){
26981        closePendingFds(pFile);
26982      }
26983    }
26984  }
26985
26986  unixLeaveMutex();
26987  if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
26988  return rc;
26989}
26990
26991/*
26992** Close a file & cleanup AFP specific locking context
26993*/
26994static int afpClose(sqlite3_file *id) {
26995  int rc = SQLITE_OK;
26996  if( id ){
26997    unixFile *pFile = (unixFile*)id;
26998    afpUnlock(id, NO_LOCK);
26999    unixEnterMutex();
27000    if( pFile->pInode && pFile->pInode->nLock ){
27001      /* If there are outstanding locks, do not actually close the file just
27002      ** yet because that would clear those locks.  Instead, add the file
27003      ** descriptor to pInode->aPending.  It will be automatically closed when
27004      ** the last lock is cleared.
27005      */
27006      setPendingFd(pFile);
27007    }
27008    releaseInodeInfo(pFile);
27009    sqlite3_free(pFile->lockingContext);
27010    rc = closeUnixFile(id);
27011    unixLeaveMutex();
27012  }
27013  return rc;
27014}
27015
27016#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
27017/*
27018** The code above is the AFP lock implementation.  The code is specific
27019** to MacOSX and does not work on other unix platforms.  No alternative
27020** is available.  If you don't compile for a mac, then the "unix-afp"
27021** VFS is not available.
27022**
27023********************* End of the AFP lock implementation **********************
27024******************************************************************************/
27025
27026/******************************************************************************
27027*************************** Begin NFS Locking ********************************/
27028
27029#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
27030/*
27031 ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
27032 ** must be either NO_LOCK or SHARED_LOCK.
27033 **
27034 ** If the locking level of the file descriptor is already at or below
27035 ** the requested locking level, this routine is a no-op.
27036 */
27037static int nfsUnlock(sqlite3_file *id, int eFileLock){
27038  return posixUnlock(id, eFileLock, 1);
27039}
27040
27041#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
27042/*
27043** The code above is the NFS lock implementation.  The code is specific
27044** to MacOSX and does not work on other unix platforms.  No alternative
27045** is available.
27046**
27047********************* End of the NFS lock implementation **********************
27048******************************************************************************/
27049
27050/******************************************************************************
27051**************** Non-locking sqlite3_file methods *****************************
27052**
27053** The next division contains implementations for all methods of the
27054** sqlite3_file object other than the locking methods.  The locking
27055** methods were defined in divisions above (one locking method per
27056** division).  Those methods that are common to all locking modes
27057** are gather together into this division.
27058*/
27059
27060/*
27061** Seek to the offset passed as the second argument, then read cnt
27062** bytes into pBuf. Return the number of bytes actually read.
27063**
27064** NB:  If you define USE_PREAD or USE_PREAD64, then it might also
27065** be necessary to define _XOPEN_SOURCE to be 500.  This varies from
27066** one system to another.  Since SQLite does not define USE_PREAD
27067** any any form by default, we will not attempt to define _XOPEN_SOURCE.
27068** See tickets #2741 and #2681.
27069**
27070** To avoid stomping the errno value on a failed read the lastErrno value
27071** is set before returning.
27072*/
27073static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
27074  int got;
27075#if (!defined(USE_PREAD) && !defined(USE_PREAD64))
27076  i64 newOffset;
27077#endif
27078  TIMER_START;
27079#if defined(USE_PREAD)
27080  do{ got = osPread(id->h, pBuf, cnt, offset); }while( got<0 && errno==EINTR );
27081  SimulateIOError( got = -1 );
27082#elif defined(USE_PREAD64)
27083  do{ got = osPread64(id->h, pBuf, cnt, offset); }while( got<0 && errno==EINTR);
27084  SimulateIOError( got = -1 );
27085#else
27086  newOffset = lseek(id->h, offset, SEEK_SET);
27087  SimulateIOError( newOffset-- );
27088  if( newOffset!=offset ){
27089    if( newOffset == -1 ){
27090      ((unixFile*)id)->lastErrno = errno;
27091    }else{
27092      ((unixFile*)id)->lastErrno = 0;
27093    }
27094    return -1;
27095  }
27096  do{ got = osRead(id->h, pBuf, cnt); }while( got<0 && errno==EINTR );
27097#endif
27098  TIMER_END;
27099  if( got<0 ){
27100    ((unixFile*)id)->lastErrno = errno;
27101  }
27102  OSTRACE(("READ    %-3d %5d %7lld %llu\n", id->h, got, offset, TIMER_ELAPSED));
27103  return got;
27104}
27105
27106/*
27107** Read data from a file into a buffer.  Return SQLITE_OK if all
27108** bytes were read successfully and SQLITE_IOERR if anything goes
27109** wrong.
27110*/
27111static int unixRead(
27112  sqlite3_file *id,
27113  void *pBuf,
27114  int amt,
27115  sqlite3_int64 offset
27116){
27117  unixFile *pFile = (unixFile *)id;
27118  int got;
27119  assert( id );
27120
27121  /* If this is a database file (not a journal, master-journal or temp
27122  ** file), the bytes in the locking range should never be read or written. */
27123#if 0
27124  assert( pFile->pUnused==0
27125       || offset>=PENDING_BYTE+512
27126       || offset+amt<=PENDING_BYTE
27127  );
27128#endif
27129
27130  got = seekAndRead(pFile, offset, pBuf, amt);
27131  if( got==amt ){
27132    return SQLITE_OK;
27133  }else if( got<0 ){
27134    /* lastErrno set by seekAndRead */
27135    return SQLITE_IOERR_READ;
27136  }else{
27137    pFile->lastErrno = 0; /* not a system error */
27138    /* Unread parts of the buffer must be zero-filled */
27139    memset(&((char*)pBuf)[got], 0, amt-got);
27140    return SQLITE_IOERR_SHORT_READ;
27141  }
27142}
27143
27144/*
27145** Seek to the offset in id->offset then read cnt bytes into pBuf.
27146** Return the number of bytes actually read.  Update the offset.
27147**
27148** To avoid stomping the errno value on a failed write the lastErrno value
27149** is set before returning.
27150*/
27151static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
27152  int got;
27153#if (!defined(USE_PREAD) && !defined(USE_PREAD64))
27154  i64 newOffset;
27155#endif
27156  TIMER_START;
27157#if defined(USE_PREAD)
27158  do{ got = osPwrite(id->h, pBuf, cnt, offset); }while( got<0 && errno==EINTR );
27159#elif defined(USE_PREAD64)
27160  do{ got = osPwrite64(id->h, pBuf, cnt, offset);}while( got<0 && errno==EINTR);
27161#else
27162  newOffset = lseek(id->h, offset, SEEK_SET);
27163  SimulateIOError( newOffset-- );
27164  if( newOffset!=offset ){
27165    if( newOffset == -1 ){
27166      ((unixFile*)id)->lastErrno = errno;
27167    }else{
27168      ((unixFile*)id)->lastErrno = 0;
27169    }
27170    return -1;
27171  }
27172  do{ got = osWrite(id->h, pBuf, cnt); }while( got<0 && errno==EINTR );
27173#endif
27174  TIMER_END;
27175  if( got<0 ){
27176    ((unixFile*)id)->lastErrno = errno;
27177  }
27178
27179  OSTRACE(("WRITE   %-3d %5d %7lld %llu\n", id->h, got, offset, TIMER_ELAPSED));
27180  return got;
27181}
27182
27183
27184/*
27185** Write data from a buffer into a file.  Return SQLITE_OK on success
27186** or some other error code on failure.
27187*/
27188static int unixWrite(
27189  sqlite3_file *id,
27190  const void *pBuf,
27191  int amt,
27192  sqlite3_int64 offset
27193){
27194  unixFile *pFile = (unixFile*)id;
27195  int wrote = 0;
27196  assert( id );
27197  assert( amt>0 );
27198
27199  /* If this is a database file (not a journal, master-journal or temp
27200  ** file), the bytes in the locking range should never be read or written. */
27201#if 0
27202  assert( pFile->pUnused==0
27203       || offset>=PENDING_BYTE+512
27204       || offset+amt<=PENDING_BYTE
27205  );
27206#endif
27207
27208#ifndef NDEBUG
27209  /* If we are doing a normal write to a database file (as opposed to
27210  ** doing a hot-journal rollback or a write to some file other than a
27211  ** normal database file) then record the fact that the database
27212  ** has changed.  If the transaction counter is modified, record that
27213  ** fact too.
27214  */
27215  if( pFile->inNormalWrite ){
27216    pFile->dbUpdate = 1;  /* The database has been modified */
27217    if( offset<=24 && offset+amt>=27 ){
27218      int rc;
27219      char oldCntr[4];
27220      SimulateIOErrorBenign(1);
27221      rc = seekAndRead(pFile, 24, oldCntr, 4);
27222      SimulateIOErrorBenign(0);
27223      if( rc!=4 || memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){
27224        pFile->transCntrChng = 1;  /* The transaction counter has changed */
27225      }
27226    }
27227  }
27228#endif
27229
27230  while( amt>0 && (wrote = seekAndWrite(pFile, offset, pBuf, amt))>0 ){
27231    amt -= wrote;
27232    offset += wrote;
27233    pBuf = &((char*)pBuf)[wrote];
27234  }
27235  SimulateIOError(( wrote=(-1), amt=1 ));
27236  SimulateDiskfullError(( wrote=0, amt=1 ));
27237
27238  if( amt>0 ){
27239    if( wrote<0 ){
27240      /* lastErrno set by seekAndWrite */
27241      return SQLITE_IOERR_WRITE;
27242    }else{
27243      pFile->lastErrno = 0; /* not a system error */
27244      return SQLITE_FULL;
27245    }
27246  }
27247
27248  return SQLITE_OK;
27249}
27250
27251#ifdef SQLITE_TEST
27252/*
27253** Count the number of fullsyncs and normal syncs.  This is used to test
27254** that syncs and fullsyncs are occurring at the right times.
27255*/
27256SQLITE_API int sqlite3_sync_count = 0;
27257SQLITE_API int sqlite3_fullsync_count = 0;
27258#endif
27259
27260/*
27261** We do not trust systems to provide a working fdatasync().  Some do.
27262** Others do no.  To be safe, we will stick with the (slower) fsync().
27263** If you know that your system does support fdatasync() correctly,
27264** then simply compile with -Dfdatasync=fdatasync
27265*/
27266#if !defined(fdatasync) && !defined(__linux__)
27267# define fdatasync fsync
27268#endif
27269
27270/*
27271** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
27272** the F_FULLFSYNC macro is defined.  F_FULLFSYNC is currently
27273** only available on Mac OS X.  But that could change.
27274*/
27275#ifdef F_FULLFSYNC
27276# define HAVE_FULLFSYNC 1
27277#else
27278# define HAVE_FULLFSYNC 0
27279#endif
27280
27281
27282/*
27283** The fsync() system call does not work as advertised on many
27284** unix systems.  The following procedure is an attempt to make
27285** it work better.
27286**
27287** The SQLITE_NO_SYNC macro disables all fsync()s.  This is useful
27288** for testing when we want to run through the test suite quickly.
27289** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
27290** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
27291** or power failure will likely corrupt the database file.
27292**
27293** SQLite sets the dataOnly flag if the size of the file is unchanged.
27294** The idea behind dataOnly is that it should only write the file content
27295** to disk, not the inode.  We only set dataOnly if the file size is
27296** unchanged since the file size is part of the inode.  However,
27297** Ted Ts'o tells us that fdatasync() will also write the inode if the
27298** file size has changed.  The only real difference between fdatasync()
27299** and fsync(), Ted tells us, is that fdatasync() will not flush the
27300** inode if the mtime or owner or other inode attributes have changed.
27301** We only care about the file size, not the other file attributes, so
27302** as far as SQLite is concerned, an fdatasync() is always adequate.
27303** So, we always use fdatasync() if it is available, regardless of
27304** the value of the dataOnly flag.
27305*/
27306static int full_fsync(int fd, int fullSync, int dataOnly){
27307  int rc;
27308
27309  /* The following "ifdef/elif/else/" block has the same structure as
27310  ** the one below. It is replicated here solely to avoid cluttering
27311  ** up the real code with the UNUSED_PARAMETER() macros.
27312  */
27313#ifdef SQLITE_NO_SYNC
27314  UNUSED_PARAMETER(fd);
27315  UNUSED_PARAMETER(fullSync);
27316  UNUSED_PARAMETER(dataOnly);
27317#elif HAVE_FULLFSYNC
27318  UNUSED_PARAMETER(dataOnly);
27319#else
27320  UNUSED_PARAMETER(fullSync);
27321  UNUSED_PARAMETER(dataOnly);
27322#endif
27323
27324  /* Record the number of times that we do a normal fsync() and
27325  ** FULLSYNC.  This is used during testing to verify that this procedure
27326  ** gets called with the correct arguments.
27327  */
27328#ifdef SQLITE_TEST
27329  if( fullSync ) sqlite3_fullsync_count++;
27330  sqlite3_sync_count++;
27331#endif
27332
27333  /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
27334  ** no-op
27335  */
27336#ifdef SQLITE_NO_SYNC
27337  rc = SQLITE_OK;
27338#elif HAVE_FULLFSYNC
27339  if( fullSync ){
27340    rc = osFcntl(fd, F_FULLFSYNC, 0);
27341  }else{
27342    rc = 1;
27343  }
27344  /* If the FULLFSYNC failed, fall back to attempting an fsync().
27345  ** It shouldn't be possible for fullfsync to fail on the local
27346  ** file system (on OSX), so failure indicates that FULLFSYNC
27347  ** isn't supported for this file system. So, attempt an fsync
27348  ** and (for now) ignore the overhead of a superfluous fcntl call.
27349  ** It'd be better to detect fullfsync support once and avoid
27350  ** the fcntl call every time sync is called.
27351  */
27352  if( rc ) rc = fsync(fd);
27353
27354#elif defined(__APPLE__)
27355  /* fdatasync() on HFS+ doesn't yet flush the file size if it changed correctly
27356  ** so currently we default to the macro that redefines fdatasync to fsync
27357  */
27358  rc = fsync(fd);
27359#else
27360  rc = fdatasync(fd);
27361#if OS_VXWORKS
27362  if( rc==-1 && errno==ENOTSUP ){
27363    rc = fsync(fd);
27364  }
27365#endif /* OS_VXWORKS */
27366#endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */
27367
27368  if( OS_VXWORKS && rc!= -1 ){
27369    rc = 0;
27370  }
27371  return rc;
27372}
27373
27374/*
27375** Open a file descriptor to the directory containing file zFilename.
27376** If successful, *pFd is set to the opened file descriptor and
27377** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
27378** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
27379** value.
27380**
27381** The directory file descriptor is used for only one thing - to
27382** fsync() a directory to make sure file creation and deletion events
27383** are flushed to disk.  Such fsyncs are not needed on newer
27384** journaling filesystems, but are required on older filesystems.
27385**
27386** This routine can be overridden using the xSetSysCall interface.
27387** The ability to override this routine was added in support of the
27388** chromium sandbox.  Opening a directory is a security risk (we are
27389** told) so making it overrideable allows the chromium sandbox to
27390** replace this routine with a harmless no-op.  To make this routine
27391** a no-op, replace it with a stub that returns SQLITE_OK but leaves
27392** *pFd set to a negative number.
27393**
27394** If SQLITE_OK is returned, the caller is responsible for closing
27395** the file descriptor *pFd using close().
27396*/
27397static int openDirectory(const char *zFilename, int *pFd){
27398  int ii;
27399  int fd = -1;
27400  char zDirname[MAX_PATHNAME+1];
27401
27402  sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
27403  for(ii=(int)strlen(zDirname); ii>1 && zDirname[ii]!='/'; ii--);
27404  if( ii>0 ){
27405    zDirname[ii] = '\0';
27406    fd = robust_open(zDirname, O_RDONLY|O_BINARY, 0);
27407    if( fd>=0 ){
27408#ifdef FD_CLOEXEC
27409      osFcntl(fd, F_SETFD, osFcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
27410#endif
27411      OSTRACE(("OPENDIR %-3d %s\n", fd, zDirname));
27412    }
27413  }
27414  *pFd = fd;
27415  return (fd>=0?SQLITE_OK:unixLogError(SQLITE_CANTOPEN_BKPT, "open", zDirname));
27416}
27417
27418/*
27419** Make sure all writes to a particular file are committed to disk.
27420**
27421** If dataOnly==0 then both the file itself and its metadata (file
27422** size, access time, etc) are synced.  If dataOnly!=0 then only the
27423** file data is synced.
27424**
27425** Under Unix, also make sure that the directory entry for the file
27426** has been created by fsync-ing the directory that contains the file.
27427** If we do not do this and we encounter a power failure, the directory
27428** entry for the journal might not exist after we reboot.  The next
27429** SQLite to access the file will not know that the journal exists (because
27430** the directory entry for the journal was never created) and the transaction
27431** will not roll back - possibly leading to database corruption.
27432*/
27433static int unixSync(sqlite3_file *id, int flags){
27434  int rc;
27435  unixFile *pFile = (unixFile*)id;
27436
27437  int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
27438  int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
27439
27440  /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
27441  assert((flags&0x0F)==SQLITE_SYNC_NORMAL
27442      || (flags&0x0F)==SQLITE_SYNC_FULL
27443  );
27444
27445  /* Unix cannot, but some systems may return SQLITE_FULL from here. This
27446  ** line is to test that doing so does not cause any problems.
27447  */
27448  SimulateDiskfullError( return SQLITE_FULL );
27449
27450  assert( pFile );
27451  OSTRACE(("SYNC    %-3d\n", pFile->h));
27452  rc = full_fsync(pFile->h, isFullsync, isDataOnly);
27453  SimulateIOError( rc=1 );
27454  if( rc ){
27455    pFile->lastErrno = errno;
27456    return unixLogError(SQLITE_IOERR_FSYNC, "full_fsync", pFile->zPath);
27457  }
27458
27459  /* Also fsync the directory containing the file if the DIRSYNC flag
27460  ** is set.  This is a one-time occurrance.  Many systems (examples: AIX)
27461  ** are unable to fsync a directory, so ignore errors on the fsync.
27462  */
27463  if( pFile->ctrlFlags & UNIXFILE_DIRSYNC ){
27464    int dirfd;
27465    OSTRACE(("DIRSYNC %s (have_fullfsync=%d fullsync=%d)\n", pFile->zPath,
27466            HAVE_FULLFSYNC, isFullsync));
27467    rc = osOpenDirectory(pFile->zPath, &dirfd);
27468    if( rc==SQLITE_OK && dirfd>=0 ){
27469      full_fsync(dirfd, 0, 0);
27470      robust_close(pFile, dirfd, __LINE__);
27471    }else if( rc==SQLITE_CANTOPEN ){
27472      rc = SQLITE_OK;
27473    }
27474    pFile->ctrlFlags &= ~UNIXFILE_DIRSYNC;
27475  }
27476  return rc;
27477}
27478
27479/*
27480** Truncate an open file to a specified size
27481*/
27482static int unixTruncate(sqlite3_file *id, i64 nByte){
27483  unixFile *pFile = (unixFile *)id;
27484  int rc;
27485  assert( pFile );
27486  SimulateIOError( return SQLITE_IOERR_TRUNCATE );
27487
27488  /* If the user has configured a chunk-size for this file, truncate the
27489  ** file so that it consists of an integer number of chunks (i.e. the
27490  ** actual file size after the operation may be larger than the requested
27491  ** size).
27492  */
27493  if( pFile->szChunk ){
27494    nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
27495  }
27496
27497  rc = robust_ftruncate(pFile->h, (off_t)nByte);
27498  if( rc ){
27499    pFile->lastErrno = errno;
27500    return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
27501  }else{
27502#ifndef NDEBUG
27503    /* If we are doing a normal write to a database file (as opposed to
27504    ** doing a hot-journal rollback or a write to some file other than a
27505    ** normal database file) and we truncate the file to zero length,
27506    ** that effectively updates the change counter.  This might happen
27507    ** when restoring a database using the backup API from a zero-length
27508    ** source.
27509    */
27510    if( pFile->inNormalWrite && nByte==0 ){
27511      pFile->transCntrChng = 1;
27512    }
27513#endif
27514
27515    return SQLITE_OK;
27516  }
27517}
27518
27519/*
27520** Determine the current size of a file in bytes
27521*/
27522static int unixFileSize(sqlite3_file *id, i64 *pSize){
27523  int rc;
27524  struct stat buf;
27525  assert( id );
27526  rc = osFstat(((unixFile*)id)->h, &buf);
27527  SimulateIOError( rc=1 );
27528  if( rc!=0 ){
27529    ((unixFile*)id)->lastErrno = errno;
27530    return SQLITE_IOERR_FSTAT;
27531  }
27532  *pSize = buf.st_size;
27533
27534  /* When opening a zero-size database, the findInodeInfo() procedure
27535  ** writes a single byte into that file in order to work around a bug
27536  ** in the OS-X msdos filesystem.  In order to avoid problems with upper
27537  ** layers, we need to report this file size as zero even though it is
27538  ** really 1.   Ticket #3260.
27539  */
27540  if( *pSize==1 ) *pSize = 0;
27541
27542
27543  return SQLITE_OK;
27544}
27545
27546#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
27547/*
27548** Handler for proxy-locking file-control verbs.  Defined below in the
27549** proxying locking division.
27550*/
27551static int proxyFileControl(sqlite3_file*,int,void*);
27552#endif
27553
27554/*
27555** This function is called to handle the SQLITE_FCNTL_SIZE_HINT
27556** file-control operation.
27557**
27558** If the user has configured a chunk-size for this file, it could be
27559** that the file needs to be extended at this point. Otherwise, the
27560** SQLITE_FCNTL_SIZE_HINT operation is a no-op for Unix.
27561*/
27562static int fcntlSizeHint(unixFile *pFile, i64 nByte){
27563  if( pFile->szChunk ){
27564    i64 nSize;                    /* Required file size */
27565    struct stat buf;              /* Used to hold return values of fstat() */
27566
27567    if( osFstat(pFile->h, &buf) ) return SQLITE_IOERR_FSTAT;
27568
27569    nSize = ((nByte+pFile->szChunk-1) / pFile->szChunk) * pFile->szChunk;
27570    if( nSize>(i64)buf.st_size ){
27571
27572#if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
27573      /* The code below is handling the return value of osFallocate()
27574      ** correctly. posix_fallocate() is defined to "returns zero on success,
27575      ** or an error number on  failure". See the manpage for details. */
27576      int err;
27577      do{
27578        err = osFallocate(pFile->h, buf.st_size, nSize-buf.st_size);
27579      }while( err==EINTR );
27580      if( err ) return SQLITE_IOERR_WRITE;
27581#else
27582      /* If the OS does not have posix_fallocate(), fake it. First use
27583      ** ftruncate() to set the file size, then write a single byte to
27584      ** the last byte in each block within the extended region. This
27585      ** is the same technique used by glibc to implement posix_fallocate()
27586      ** on systems that do not have a real fallocate() system call.
27587      */
27588      int nBlk = buf.st_blksize;  /* File-system block size */
27589      i64 iWrite;                 /* Next offset to write to */
27590
27591      if( robust_ftruncate(pFile->h, nSize) ){
27592        pFile->lastErrno = errno;
27593        return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
27594      }
27595      iWrite = ((buf.st_size + 2*nBlk - 1)/nBlk)*nBlk-1;
27596      while( iWrite<nSize ){
27597        int nWrite = seekAndWrite(pFile, iWrite, "", 1);
27598        if( nWrite!=1 ) return SQLITE_IOERR_WRITE;
27599        iWrite += nBlk;
27600      }
27601#endif
27602    }
27603  }
27604
27605  return SQLITE_OK;
27606}
27607
27608/*
27609** Information and control of an open file handle.
27610*/
27611static int unixFileControl(sqlite3_file *id, int op, void *pArg){
27612  switch( op ){
27613    case SQLITE_FCNTL_LOCKSTATE: {
27614      *(int*)pArg = ((unixFile*)id)->eFileLock;
27615      return SQLITE_OK;
27616    }
27617    case SQLITE_LAST_ERRNO: {
27618      *(int*)pArg = ((unixFile*)id)->lastErrno;
27619      return SQLITE_OK;
27620    }
27621    case SQLITE_FCNTL_CHUNK_SIZE: {
27622      ((unixFile*)id)->szChunk = *(int *)pArg;
27623      return SQLITE_OK;
27624    }
27625    case SQLITE_FCNTL_SIZE_HINT: {
27626      return fcntlSizeHint((unixFile *)id, *(i64 *)pArg);
27627    }
27628#ifndef NDEBUG
27629    /* The pager calls this method to signal that it has done
27630    ** a rollback and that the database is therefore unchanged and
27631    ** it hence it is OK for the transaction change counter to be
27632    ** unchanged.
27633    */
27634    case SQLITE_FCNTL_DB_UNCHANGED: {
27635      ((unixFile*)id)->dbUpdate = 0;
27636      return SQLITE_OK;
27637    }
27638#endif
27639#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
27640    case SQLITE_SET_LOCKPROXYFILE:
27641    case SQLITE_GET_LOCKPROXYFILE: {
27642      return proxyFileControl(id,op,pArg);
27643    }
27644#endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */
27645    case SQLITE_FCNTL_SYNC_OMITTED: {
27646      return SQLITE_OK;  /* A no-op */
27647    }
27648  }
27649  return SQLITE_NOTFOUND;
27650}
27651
27652/*
27653** Return the sector size in bytes of the underlying block device for
27654** the specified file. This is almost always 512 bytes, but may be
27655** larger for some devices.
27656**
27657** SQLite code assumes this function cannot fail. It also assumes that
27658** if two files are created in the same file-system directory (i.e.
27659** a database and its journal file) that the sector size will be the
27660** same for both.
27661*/
27662static int unixSectorSize(sqlite3_file *NotUsed){
27663  UNUSED_PARAMETER(NotUsed);
27664  return SQLITE_DEFAULT_SECTOR_SIZE;
27665}
27666
27667/*
27668** Return the device characteristics for the file. This is always 0 for unix.
27669*/
27670static int unixDeviceCharacteristics(sqlite3_file *NotUsed){
27671  UNUSED_PARAMETER(NotUsed);
27672  return 0;
27673}
27674
27675#ifndef SQLITE_OMIT_WAL
27676
27677
27678/*
27679** Object used to represent an shared memory buffer.
27680**
27681** When multiple threads all reference the same wal-index, each thread
27682** has its own unixShm object, but they all point to a single instance
27683** of this unixShmNode object.  In other words, each wal-index is opened
27684** only once per process.
27685**
27686** Each unixShmNode object is connected to a single unixInodeInfo object.
27687** We could coalesce this object into unixInodeInfo, but that would mean
27688** every open file that does not use shared memory (in other words, most
27689** open files) would have to carry around this extra information.  So
27690** the unixInodeInfo object contains a pointer to this unixShmNode object
27691** and the unixShmNode object is created only when needed.
27692**
27693** unixMutexHeld() must be true when creating or destroying
27694** this object or while reading or writing the following fields:
27695**
27696**      nRef
27697**
27698** The following fields are read-only after the object is created:
27699**
27700**      fid
27701**      zFilename
27702**
27703** Either unixShmNode.mutex must be held or unixShmNode.nRef==0 and
27704** unixMutexHeld() is true when reading or writing any other field
27705** in this structure.
27706*/
27707struct unixShmNode {
27708  unixInodeInfo *pInode;     /* unixInodeInfo that owns this SHM node */
27709  sqlite3_mutex *mutex;      /* Mutex to access this object */
27710  char *zFilename;           /* Name of the mmapped file */
27711  int h;                     /* Open file descriptor */
27712  int szRegion;              /* Size of shared-memory regions */
27713  int nRegion;               /* Size of array apRegion */
27714  char **apRegion;           /* Array of mapped shared-memory regions */
27715  int nRef;                  /* Number of unixShm objects pointing to this */
27716  unixShm *pFirst;           /* All unixShm objects pointing to this */
27717#ifdef SQLITE_DEBUG
27718  u8 exclMask;               /* Mask of exclusive locks held */
27719  u8 sharedMask;             /* Mask of shared locks held */
27720  u8 nextShmId;              /* Next available unixShm.id value */
27721#endif
27722};
27723
27724/*
27725** Structure used internally by this VFS to record the state of an
27726** open shared memory connection.
27727**
27728** The following fields are initialized when this object is created and
27729** are read-only thereafter:
27730**
27731**    unixShm.pFile
27732**    unixShm.id
27733**
27734** All other fields are read/write.  The unixShm.pFile->mutex must be held
27735** while accessing any read/write fields.
27736*/
27737struct unixShm {
27738  unixShmNode *pShmNode;     /* The underlying unixShmNode object */
27739  unixShm *pNext;            /* Next unixShm with the same unixShmNode */
27740  u8 hasMutex;               /* True if holding the unixShmNode mutex */
27741  u16 sharedMask;            /* Mask of shared locks held */
27742  u16 exclMask;              /* Mask of exclusive locks held */
27743#ifdef SQLITE_DEBUG
27744  u8 id;                     /* Id of this connection within its unixShmNode */
27745#endif
27746};
27747
27748/*
27749** Constants used for locking
27750*/
27751#define UNIX_SHM_BASE   ((22+SQLITE_SHM_NLOCK)*4)         /* first lock byte */
27752#define UNIX_SHM_DMS    (UNIX_SHM_BASE+SQLITE_SHM_NLOCK)  /* deadman switch */
27753
27754/*
27755** Apply posix advisory locks for all bytes from ofst through ofst+n-1.
27756**
27757** Locks block if the mask is exactly UNIX_SHM_C and are non-blocking
27758** otherwise.
27759*/
27760static int unixShmSystemLock(
27761  unixShmNode *pShmNode, /* Apply locks to this open shared-memory segment */
27762  int lockType,          /* F_UNLCK, F_RDLCK, or F_WRLCK */
27763  int ofst,              /* First byte of the locking range */
27764  int n                  /* Number of bytes to lock */
27765){
27766  struct flock f;       /* The posix advisory locking structure */
27767  int rc = SQLITE_OK;   /* Result code form fcntl() */
27768
27769  /* Access to the unixShmNode object is serialized by the caller */
27770  assert( sqlite3_mutex_held(pShmNode->mutex) || pShmNode->nRef==0 );
27771
27772  /* Shared locks never span more than one byte */
27773  assert( n==1 || lockType!=F_RDLCK );
27774
27775  /* Locks are within range */
27776  assert( n>=1 && n<SQLITE_SHM_NLOCK );
27777
27778  if( pShmNode->h>=0 ){
27779    /* Initialize the locking parameters */
27780    memset(&f, 0, sizeof(f));
27781    f.l_type = lockType;
27782    f.l_whence = SEEK_SET;
27783    f.l_start = ofst;
27784    f.l_len = n;
27785
27786    rc = osFcntl(pShmNode->h, F_SETLK, &f);
27787    rc = (rc!=(-1)) ? SQLITE_OK : SQLITE_BUSY;
27788  }
27789
27790  /* Update the global lock state and do debug tracing */
27791#ifdef SQLITE_DEBUG
27792  { u16 mask;
27793  OSTRACE(("SHM-LOCK "));
27794  mask = (1<<(ofst+n)) - (1<<ofst);
27795  if( rc==SQLITE_OK ){
27796    if( lockType==F_UNLCK ){
27797      OSTRACE(("unlock %d ok", ofst));
27798      pShmNode->exclMask &= ~mask;
27799      pShmNode->sharedMask &= ~mask;
27800    }else if( lockType==F_RDLCK ){
27801      OSTRACE(("read-lock %d ok", ofst));
27802      pShmNode->exclMask &= ~mask;
27803      pShmNode->sharedMask |= mask;
27804    }else{
27805      assert( lockType==F_WRLCK );
27806      OSTRACE(("write-lock %d ok", ofst));
27807      pShmNode->exclMask |= mask;
27808      pShmNode->sharedMask &= ~mask;
27809    }
27810  }else{
27811    if( lockType==F_UNLCK ){
27812      OSTRACE(("unlock %d failed", ofst));
27813    }else if( lockType==F_RDLCK ){
27814      OSTRACE(("read-lock failed"));
27815    }else{
27816      assert( lockType==F_WRLCK );
27817      OSTRACE(("write-lock %d failed", ofst));
27818    }
27819  }
27820  OSTRACE((" - afterwards %03x,%03x\n",
27821           pShmNode->sharedMask, pShmNode->exclMask));
27822  }
27823#endif
27824
27825  return rc;
27826}
27827
27828
27829/*
27830** Purge the unixShmNodeList list of all entries with unixShmNode.nRef==0.
27831**
27832** This is not a VFS shared-memory method; it is a utility function called
27833** by VFS shared-memory methods.
27834*/
27835static void unixShmPurge(unixFile *pFd){
27836  unixShmNode *p = pFd->pInode->pShmNode;
27837  assert( unixMutexHeld() );
27838  if( p && p->nRef==0 ){
27839    int i;
27840    assert( p->pInode==pFd->pInode );
27841    if( p->mutex ) sqlite3_mutex_free(p->mutex);
27842    for(i=0; i<p->nRegion; i++){
27843      if( p->h>=0 ){
27844        munmap(p->apRegion[i], p->szRegion);
27845      }else{
27846        sqlite3_free(p->apRegion[i]);
27847      }
27848    }
27849    sqlite3_free(p->apRegion);
27850    if( p->h>=0 ){
27851      robust_close(pFd, p->h, __LINE__);
27852      p->h = -1;
27853    }
27854    p->pInode->pShmNode = 0;
27855    sqlite3_free(p);
27856  }
27857}
27858
27859/*
27860** Open a shared-memory area associated with open database file pDbFd.
27861** This particular implementation uses mmapped files.
27862**
27863** The file used to implement shared-memory is in the same directory
27864** as the open database file and has the same name as the open database
27865** file with the "-shm" suffix added.  For example, if the database file
27866** is "/home/user1/config.db" then the file that is created and mmapped
27867** for shared memory will be called "/home/user1/config.db-shm".
27868**
27869** Another approach to is to use files in /dev/shm or /dev/tmp or an
27870** some other tmpfs mount. But if a file in a different directory
27871** from the database file is used, then differing access permissions
27872** or a chroot() might cause two different processes on the same
27873** database to end up using different files for shared memory -
27874** meaning that their memory would not really be shared - resulting
27875** in database corruption.  Nevertheless, this tmpfs file usage
27876** can be enabled at compile-time using -DSQLITE_SHM_DIRECTORY="/dev/shm"
27877** or the equivalent.  The use of the SQLITE_SHM_DIRECTORY compile-time
27878** option results in an incompatible build of SQLite;  builds of SQLite
27879** that with differing SQLITE_SHM_DIRECTORY settings attempt to use the
27880** same database file at the same time, database corruption will likely
27881** result. The SQLITE_SHM_DIRECTORY compile-time option is considered
27882** "unsupported" and may go away in a future SQLite release.
27883**
27884** When opening a new shared-memory file, if no other instances of that
27885** file are currently open, in this process or in other processes, then
27886** the file must be truncated to zero length or have its header cleared.
27887**
27888** If the original database file (pDbFd) is using the "unix-excl" VFS
27889** that means that an exclusive lock is held on the database file and
27890** that no other processes are able to read or write the database.  In
27891** that case, we do not really need shared memory.  No shared memory
27892** file is created.  The shared memory will be simulated with heap memory.
27893*/
27894static int unixOpenSharedMemory(unixFile *pDbFd){
27895  struct unixShm *p = 0;          /* The connection to be opened */
27896  struct unixShmNode *pShmNode;   /* The underlying mmapped file */
27897  int rc;                         /* Result code */
27898  unixInodeInfo *pInode;          /* The inode of fd */
27899  char *zShmFilename;             /* Name of the file used for SHM */
27900  int nShmFilename;               /* Size of the SHM filename in bytes */
27901
27902  /* Allocate space for the new unixShm object. */
27903  p = sqlite3_malloc( sizeof(*p) );
27904  if( p==0 ) return SQLITE_NOMEM;
27905  memset(p, 0, sizeof(*p));
27906  assert( pDbFd->pShm==0 );
27907
27908  /* Check to see if a unixShmNode object already exists. Reuse an existing
27909  ** one if present. Create a new one if necessary.
27910  */
27911  unixEnterMutex();
27912  pInode = pDbFd->pInode;
27913  pShmNode = pInode->pShmNode;
27914  if( pShmNode==0 ){
27915    struct stat sStat;                 /* fstat() info for database file */
27916
27917    /* Call fstat() to figure out the permissions on the database file. If
27918    ** a new *-shm file is created, an attempt will be made to create it
27919    ** with the same permissions. The actual permissions the file is created
27920    ** with are subject to the current umask setting.
27921    */
27922    if( osFstat(pDbFd->h, &sStat) && pInode->bProcessLock==0 ){
27923      rc = SQLITE_IOERR_FSTAT;
27924      goto shm_open_err;
27925    }
27926
27927#ifdef SQLITE_SHM_DIRECTORY
27928    nShmFilename = sizeof(SQLITE_SHM_DIRECTORY) + 30;
27929#else
27930    nShmFilename = 5 + (int)strlen(pDbFd->zPath);
27931#endif
27932    pShmNode = sqlite3_malloc( sizeof(*pShmNode) + nShmFilename );
27933    if( pShmNode==0 ){
27934      rc = SQLITE_NOMEM;
27935      goto shm_open_err;
27936    }
27937    memset(pShmNode, 0, sizeof(*pShmNode));
27938    zShmFilename = pShmNode->zFilename = (char*)&pShmNode[1];
27939#ifdef SQLITE_SHM_DIRECTORY
27940    sqlite3_snprintf(nShmFilename, zShmFilename,
27941                     SQLITE_SHM_DIRECTORY "/sqlite-shm-%x-%x",
27942                     (u32)sStat.st_ino, (u32)sStat.st_dev);
27943#else
27944    sqlite3_snprintf(nShmFilename, zShmFilename, "%s-shm", pDbFd->zPath);
27945#endif
27946    pShmNode->h = -1;
27947    pDbFd->pInode->pShmNode = pShmNode;
27948    pShmNode->pInode = pDbFd->pInode;
27949    pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
27950    if( pShmNode->mutex==0 ){
27951      rc = SQLITE_NOMEM;
27952      goto shm_open_err;
27953    }
27954
27955    if( pInode->bProcessLock==0 ){
27956      pShmNode->h = robust_open(zShmFilename, O_RDWR|O_CREAT,
27957                               (sStat.st_mode & 0777));
27958      if( pShmNode->h<0 ){
27959        rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zShmFilename);
27960        goto shm_open_err;
27961      }
27962
27963      /* Check to see if another process is holding the dead-man switch.
27964      ** If not, truncate the file to zero length.
27965      */
27966      rc = SQLITE_OK;
27967      if( unixShmSystemLock(pShmNode, F_WRLCK, UNIX_SHM_DMS, 1)==SQLITE_OK ){
27968        if( robust_ftruncate(pShmNode->h, 0) ){
27969          rc = unixLogError(SQLITE_IOERR_SHMOPEN, "ftruncate", zShmFilename);
27970        }
27971      }
27972      if( rc==SQLITE_OK ){
27973        rc = unixShmSystemLock(pShmNode, F_RDLCK, UNIX_SHM_DMS, 1);
27974      }
27975      if( rc ) goto shm_open_err;
27976    }
27977  }
27978
27979  /* Make the new connection a child of the unixShmNode */
27980  p->pShmNode = pShmNode;
27981#ifdef SQLITE_DEBUG
27982  p->id = pShmNode->nextShmId++;
27983#endif
27984  pShmNode->nRef++;
27985  pDbFd->pShm = p;
27986  unixLeaveMutex();
27987
27988  /* The reference count on pShmNode has already been incremented under
27989  ** the cover of the unixEnterMutex() mutex and the pointer from the
27990  ** new (struct unixShm) object to the pShmNode has been set. All that is
27991  ** left to do is to link the new object into the linked list starting
27992  ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex
27993  ** mutex.
27994  */
27995  sqlite3_mutex_enter(pShmNode->mutex);
27996  p->pNext = pShmNode->pFirst;
27997  pShmNode->pFirst = p;
27998  sqlite3_mutex_leave(pShmNode->mutex);
27999  return SQLITE_OK;
28000
28001  /* Jump here on any error */
28002shm_open_err:
28003  unixShmPurge(pDbFd);       /* This call frees pShmNode if required */
28004  sqlite3_free(p);
28005  unixLeaveMutex();
28006  return rc;
28007}
28008
28009/*
28010** This function is called to obtain a pointer to region iRegion of the
28011** shared-memory associated with the database file fd. Shared-memory regions
28012** are numbered starting from zero. Each shared-memory region is szRegion
28013** bytes in size.
28014**
28015** If an error occurs, an error code is returned and *pp is set to NULL.
28016**
28017** Otherwise, if the bExtend parameter is 0 and the requested shared-memory
28018** region has not been allocated (by any client, including one running in a
28019** separate process), then *pp is set to NULL and SQLITE_OK returned. If
28020** bExtend is non-zero and the requested shared-memory region has not yet
28021** been allocated, it is allocated by this function.
28022**
28023** If the shared-memory region has already been allocated or is allocated by
28024** this call as described above, then it is mapped into this processes
28025** address space (if it is not already), *pp is set to point to the mapped
28026** memory and SQLITE_OK returned.
28027*/
28028static int unixShmMap(
28029  sqlite3_file *fd,               /* Handle open on database file */
28030  int iRegion,                    /* Region to retrieve */
28031  int szRegion,                   /* Size of regions */
28032  int bExtend,                    /* True to extend file if necessary */
28033  void volatile **pp              /* OUT: Mapped memory */
28034){
28035  unixFile *pDbFd = (unixFile*)fd;
28036  unixShm *p;
28037  unixShmNode *pShmNode;
28038  int rc = SQLITE_OK;
28039
28040  /* If the shared-memory file has not yet been opened, open it now. */
28041  if( pDbFd->pShm==0 ){
28042    rc = unixOpenSharedMemory(pDbFd);
28043    if( rc!=SQLITE_OK ) return rc;
28044  }
28045
28046  p = pDbFd->pShm;
28047  pShmNode = p->pShmNode;
28048  sqlite3_mutex_enter(pShmNode->mutex);
28049  assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
28050  assert( pShmNode->pInode==pDbFd->pInode );
28051  assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
28052  assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
28053
28054  if( pShmNode->nRegion<=iRegion ){
28055    char **apNew;                      /* New apRegion[] array */
28056    int nByte = (iRegion+1)*szRegion;  /* Minimum required file size */
28057    struct stat sStat;                 /* Used by fstat() */
28058
28059    pShmNode->szRegion = szRegion;
28060
28061    if( pShmNode->h>=0 ){
28062      /* The requested region is not mapped into this processes address space.
28063      ** Check to see if it has been allocated (i.e. if the wal-index file is
28064      ** large enough to contain the requested region).
28065      */
28066      if( osFstat(pShmNode->h, &sStat) ){
28067        rc = SQLITE_IOERR_SHMSIZE;
28068        goto shmpage_out;
28069      }
28070
28071      if( sStat.st_size<nByte ){
28072        /* The requested memory region does not exist. If bExtend is set to
28073        ** false, exit early. *pp will be set to NULL and SQLITE_OK returned.
28074        **
28075        ** Alternatively, if bExtend is true, use ftruncate() to allocate
28076        ** the requested memory region.
28077        */
28078        if( !bExtend ) goto shmpage_out;
28079        if( robust_ftruncate(pShmNode->h, nByte) ){
28080          rc = unixLogError(SQLITE_IOERR_SHMSIZE, "ftruncate",
28081                            pShmNode->zFilename);
28082          goto shmpage_out;
28083        }
28084      }
28085    }
28086
28087    /* Map the requested memory region into this processes address space. */
28088    apNew = (char **)sqlite3_realloc(
28089        pShmNode->apRegion, (iRegion+1)*sizeof(char *)
28090    );
28091    if( !apNew ){
28092      rc = SQLITE_IOERR_NOMEM;
28093      goto shmpage_out;
28094    }
28095    pShmNode->apRegion = apNew;
28096    while(pShmNode->nRegion<=iRegion){
28097      void *pMem;
28098      if( pShmNode->h>=0 ){
28099        pMem = mmap(0, szRegion, PROT_READ|PROT_WRITE,
28100            MAP_SHARED, pShmNode->h, pShmNode->nRegion*szRegion
28101        );
28102        if( pMem==MAP_FAILED ){
28103          rc = SQLITE_IOERR;
28104          goto shmpage_out;
28105        }
28106      }else{
28107        pMem = sqlite3_malloc(szRegion);
28108        if( pMem==0 ){
28109          rc = SQLITE_NOMEM;
28110          goto shmpage_out;
28111        }
28112        memset(pMem, 0, szRegion);
28113      }
28114      pShmNode->apRegion[pShmNode->nRegion] = pMem;
28115      pShmNode->nRegion++;
28116    }
28117  }
28118
28119shmpage_out:
28120  if( pShmNode->nRegion>iRegion ){
28121    *pp = pShmNode->apRegion[iRegion];
28122  }else{
28123    *pp = 0;
28124  }
28125  sqlite3_mutex_leave(pShmNode->mutex);
28126  return rc;
28127}
28128
28129/*
28130** Change the lock state for a shared-memory segment.
28131**
28132** Note that the relationship between SHAREd and EXCLUSIVE locks is a little
28133** different here than in posix.  In xShmLock(), one can go from unlocked
28134** to shared and back or from unlocked to exclusive and back.  But one may
28135** not go from shared to exclusive or from exclusive to shared.
28136*/
28137static int unixShmLock(
28138  sqlite3_file *fd,          /* Database file holding the shared memory */
28139  int ofst,                  /* First lock to acquire or release */
28140  int n,                     /* Number of locks to acquire or release */
28141  int flags                  /* What to do with the lock */
28142){
28143  unixFile *pDbFd = (unixFile*)fd;      /* Connection holding shared memory */
28144  unixShm *p = pDbFd->pShm;             /* The shared memory being locked */
28145  unixShm *pX;                          /* For looping over all siblings */
28146  unixShmNode *pShmNode = p->pShmNode;  /* The underlying file iNode */
28147  int rc = SQLITE_OK;                   /* Result code */
28148  u16 mask;                             /* Mask of locks to take or release */
28149
28150  assert( pShmNode==pDbFd->pInode->pShmNode );
28151  assert( pShmNode->pInode==pDbFd->pInode );
28152  assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
28153  assert( n>=1 );
28154  assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
28155       || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
28156       || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
28157       || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
28158  assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
28159  assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
28160  assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
28161
28162  mask = (1<<(ofst+n)) - (1<<ofst);
28163  assert( n>1 || mask==(1<<ofst) );
28164  sqlite3_mutex_enter(pShmNode->mutex);
28165  if( flags & SQLITE_SHM_UNLOCK ){
28166    u16 allMask = 0; /* Mask of locks held by siblings */
28167
28168    /* See if any siblings hold this same lock */
28169    for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
28170      if( pX==p ) continue;
28171      assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
28172      allMask |= pX->sharedMask;
28173    }
28174
28175    /* Unlock the system-level locks */
28176    if( (mask & allMask)==0 ){
28177      rc = unixShmSystemLock(pShmNode, F_UNLCK, ofst+UNIX_SHM_BASE, n);
28178    }else{
28179      rc = SQLITE_OK;
28180    }
28181
28182    /* Undo the local locks */
28183    if( rc==SQLITE_OK ){
28184      p->exclMask &= ~mask;
28185      p->sharedMask &= ~mask;
28186    }
28187  }else if( flags & SQLITE_SHM_SHARED ){
28188    u16 allShared = 0;  /* Union of locks held by connections other than "p" */
28189
28190    /* Find out which shared locks are already held by sibling connections.
28191    ** If any sibling already holds an exclusive lock, go ahead and return
28192    ** SQLITE_BUSY.
28193    */
28194    for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
28195      if( (pX->exclMask & mask)!=0 ){
28196        rc = SQLITE_BUSY;
28197        break;
28198      }
28199      allShared |= pX->sharedMask;
28200    }
28201
28202    /* Get shared locks at the system level, if necessary */
28203    if( rc==SQLITE_OK ){
28204      if( (allShared & mask)==0 ){
28205        rc = unixShmSystemLock(pShmNode, F_RDLCK, ofst+UNIX_SHM_BASE, n);
28206      }else{
28207        rc = SQLITE_OK;
28208      }
28209    }
28210
28211    /* Get the local shared locks */
28212    if( rc==SQLITE_OK ){
28213      p->sharedMask |= mask;
28214    }
28215  }else{
28216    /* Make sure no sibling connections hold locks that will block this
28217    ** lock.  If any do, return SQLITE_BUSY right away.
28218    */
28219    for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
28220      if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
28221        rc = SQLITE_BUSY;
28222        break;
28223      }
28224    }
28225
28226    /* Get the exclusive locks at the system level.  Then if successful
28227    ** also mark the local connection as being locked.
28228    */
28229    if( rc==SQLITE_OK ){
28230      rc = unixShmSystemLock(pShmNode, F_WRLCK, ofst+UNIX_SHM_BASE, n);
28231      if( rc==SQLITE_OK ){
28232        assert( (p->sharedMask & mask)==0 );
28233        p->exclMask |= mask;
28234      }
28235    }
28236  }
28237  sqlite3_mutex_leave(pShmNode->mutex);
28238  OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x\n",
28239           p->id, getpid(), p->sharedMask, p->exclMask));
28240  return rc;
28241}
28242
28243/*
28244** Implement a memory barrier or memory fence on shared memory.
28245**
28246** All loads and stores begun before the barrier must complete before
28247** any load or store begun after the barrier.
28248*/
28249static void unixShmBarrier(
28250  sqlite3_file *fd                /* Database file holding the shared memory */
28251){
28252  UNUSED_PARAMETER(fd);
28253  unixEnterMutex();
28254  unixLeaveMutex();
28255}
28256
28257/*
28258** Close a connection to shared-memory.  Delete the underlying
28259** storage if deleteFlag is true.
28260**
28261** If there is no shared memory associated with the connection then this
28262** routine is a harmless no-op.
28263*/
28264static int unixShmUnmap(
28265  sqlite3_file *fd,               /* The underlying database file */
28266  int deleteFlag                  /* Delete shared-memory if true */
28267){
28268  unixShm *p;                     /* The connection to be closed */
28269  unixShmNode *pShmNode;          /* The underlying shared-memory file */
28270  unixShm **pp;                   /* For looping over sibling connections */
28271  unixFile *pDbFd;                /* The underlying database file */
28272
28273  pDbFd = (unixFile*)fd;
28274  p = pDbFd->pShm;
28275  if( p==0 ) return SQLITE_OK;
28276  pShmNode = p->pShmNode;
28277
28278  assert( pShmNode==pDbFd->pInode->pShmNode );
28279  assert( pShmNode->pInode==pDbFd->pInode );
28280
28281  /* Remove connection p from the set of connections associated
28282  ** with pShmNode */
28283  sqlite3_mutex_enter(pShmNode->mutex);
28284  for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
28285  *pp = p->pNext;
28286
28287  /* Free the connection p */
28288  sqlite3_free(p);
28289  pDbFd->pShm = 0;
28290  sqlite3_mutex_leave(pShmNode->mutex);
28291
28292  /* If pShmNode->nRef has reached 0, then close the underlying
28293  ** shared-memory file, too */
28294  unixEnterMutex();
28295  assert( pShmNode->nRef>0 );
28296  pShmNode->nRef--;
28297  if( pShmNode->nRef==0 ){
28298    if( deleteFlag && pShmNode->h>=0 ) osUnlink(pShmNode->zFilename);
28299    unixShmPurge(pDbFd);
28300  }
28301  unixLeaveMutex();
28302
28303  return SQLITE_OK;
28304}
28305
28306
28307#else
28308# define unixShmMap     0
28309# define unixShmLock    0
28310# define unixShmBarrier 0
28311# define unixShmUnmap   0
28312#endif /* #ifndef SQLITE_OMIT_WAL */
28313
28314/*
28315** Here ends the implementation of all sqlite3_file methods.
28316**
28317********************** End sqlite3_file Methods *******************************
28318******************************************************************************/
28319
28320/*
28321** This division contains definitions of sqlite3_io_methods objects that
28322** implement various file locking strategies.  It also contains definitions
28323** of "finder" functions.  A finder-function is used to locate the appropriate
28324** sqlite3_io_methods object for a particular database file.  The pAppData
28325** field of the sqlite3_vfs VFS objects are initialized to be pointers to
28326** the correct finder-function for that VFS.
28327**
28328** Most finder functions return a pointer to a fixed sqlite3_io_methods
28329** object.  The only interesting finder-function is autolockIoFinder, which
28330** looks at the filesystem type and tries to guess the best locking
28331** strategy from that.
28332**
28333** For finder-funtion F, two objects are created:
28334**
28335**    (1) The real finder-function named "FImpt()".
28336**
28337**    (2) A constant pointer to this function named just "F".
28338**
28339**
28340** A pointer to the F pointer is used as the pAppData value for VFS
28341** objects.  We have to do this instead of letting pAppData point
28342** directly at the finder-function since C90 rules prevent a void*
28343** from be cast into a function pointer.
28344**
28345**
28346** Each instance of this macro generates two objects:
28347**
28348**   *  A constant sqlite3_io_methods object call METHOD that has locking
28349**      methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
28350**
28351**   *  An I/O method finder function called FINDER that returns a pointer
28352**      to the METHOD object in the previous bullet.
28353*/
28354#define IOMETHODS(FINDER, METHOD, VERSION, CLOSE, LOCK, UNLOCK, CKLOCK)      \
28355static const sqlite3_io_methods METHOD = {                                   \
28356   VERSION,                    /* iVersion */                                \
28357   CLOSE,                      /* xClose */                                  \
28358   unixRead,                   /* xRead */                                   \
28359   unixWrite,                  /* xWrite */                                  \
28360   unixTruncate,               /* xTruncate */                               \
28361   unixSync,                   /* xSync */                                   \
28362   unixFileSize,               /* xFileSize */                               \
28363   LOCK,                       /* xLock */                                   \
28364   UNLOCK,                     /* xUnlock */                                 \
28365   CKLOCK,                     /* xCheckReservedLock */                      \
28366   unixFileControl,            /* xFileControl */                            \
28367   unixSectorSize,             /* xSectorSize */                             \
28368   unixDeviceCharacteristics,  /* xDeviceCapabilities */                     \
28369   unixShmMap,                 /* xShmMap */                                 \
28370   unixShmLock,                /* xShmLock */                                \
28371   unixShmBarrier,             /* xShmBarrier */                             \
28372   unixShmUnmap                /* xShmUnmap */                               \
28373};                                                                           \
28374static const sqlite3_io_methods *FINDER##Impl(const char *z, unixFile *p){   \
28375  UNUSED_PARAMETER(z); UNUSED_PARAMETER(p);                                  \
28376  return &METHOD;                                                            \
28377}                                                                            \
28378static const sqlite3_io_methods *(*const FINDER)(const char*,unixFile *p)    \
28379    = FINDER##Impl;
28380
28381/*
28382** Here are all of the sqlite3_io_methods objects for each of the
28383** locking strategies.  Functions that return pointers to these methods
28384** are also created.
28385*/
28386IOMETHODS(
28387  posixIoFinder,            /* Finder function name */
28388  posixIoMethods,           /* sqlite3_io_methods object name */
28389  2,                        /* shared memory is enabled */
28390  unixClose,                /* xClose method */
28391  unixLock,                 /* xLock method */
28392  unixUnlock,               /* xUnlock method */
28393  unixCheckReservedLock     /* xCheckReservedLock method */
28394)
28395IOMETHODS(
28396  nolockIoFinder,           /* Finder function name */
28397  nolockIoMethods,          /* sqlite3_io_methods object name */
28398  1,                        /* shared memory is disabled */
28399  nolockClose,              /* xClose method */
28400  nolockLock,               /* xLock method */
28401  nolockUnlock,             /* xUnlock method */
28402  nolockCheckReservedLock   /* xCheckReservedLock method */
28403)
28404IOMETHODS(
28405  dotlockIoFinder,          /* Finder function name */
28406  dotlockIoMethods,         /* sqlite3_io_methods object name */
28407  1,                        /* shared memory is disabled */
28408  dotlockClose,             /* xClose method */
28409  dotlockLock,              /* xLock method */
28410  dotlockUnlock,            /* xUnlock method */
28411  dotlockCheckReservedLock  /* xCheckReservedLock method */
28412)
28413
28414#if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
28415IOMETHODS(
28416  flockIoFinder,            /* Finder function name */
28417  flockIoMethods,           /* sqlite3_io_methods object name */
28418  1,                        /* shared memory is disabled */
28419  flockClose,               /* xClose method */
28420  flockLock,                /* xLock method */
28421  flockUnlock,              /* xUnlock method */
28422  flockCheckReservedLock    /* xCheckReservedLock method */
28423)
28424#endif
28425
28426#if OS_VXWORKS
28427IOMETHODS(
28428  semIoFinder,              /* Finder function name */
28429  semIoMethods,             /* sqlite3_io_methods object name */
28430  1,                        /* shared memory is disabled */
28431  semClose,                 /* xClose method */
28432  semLock,                  /* xLock method */
28433  semUnlock,                /* xUnlock method */
28434  semCheckReservedLock      /* xCheckReservedLock method */
28435)
28436#endif
28437
28438#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
28439IOMETHODS(
28440  afpIoFinder,              /* Finder function name */
28441  afpIoMethods,             /* sqlite3_io_methods object name */
28442  1,                        /* shared memory is disabled */
28443  afpClose,                 /* xClose method */
28444  afpLock,                  /* xLock method */
28445  afpUnlock,                /* xUnlock method */
28446  afpCheckReservedLock      /* xCheckReservedLock method */
28447)
28448#endif
28449
28450/*
28451** The proxy locking method is a "super-method" in the sense that it
28452** opens secondary file descriptors for the conch and lock files and
28453** it uses proxy, dot-file, AFP, and flock() locking methods on those
28454** secondary files.  For this reason, the division that implements
28455** proxy locking is located much further down in the file.  But we need
28456** to go ahead and define the sqlite3_io_methods and finder function
28457** for proxy locking here.  So we forward declare the I/O methods.
28458*/
28459#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
28460static int proxyClose(sqlite3_file*);
28461static int proxyLock(sqlite3_file*, int);
28462static int proxyUnlock(sqlite3_file*, int);
28463static int proxyCheckReservedLock(sqlite3_file*, int*);
28464IOMETHODS(
28465  proxyIoFinder,            /* Finder function name */
28466  proxyIoMethods,           /* sqlite3_io_methods object name */
28467  1,                        /* shared memory is disabled */
28468  proxyClose,               /* xClose method */
28469  proxyLock,                /* xLock method */
28470  proxyUnlock,              /* xUnlock method */
28471  proxyCheckReservedLock    /* xCheckReservedLock method */
28472)
28473#endif
28474
28475/* nfs lockd on OSX 10.3+ doesn't clear write locks when a read lock is set */
28476#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
28477IOMETHODS(
28478  nfsIoFinder,               /* Finder function name */
28479  nfsIoMethods,              /* sqlite3_io_methods object name */
28480  1,                         /* shared memory is disabled */
28481  unixClose,                 /* xClose method */
28482  unixLock,                  /* xLock method */
28483  nfsUnlock,                 /* xUnlock method */
28484  unixCheckReservedLock      /* xCheckReservedLock method */
28485)
28486#endif
28487
28488#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
28489/*
28490** This "finder" function attempts to determine the best locking strategy
28491** for the database file "filePath".  It then returns the sqlite3_io_methods
28492** object that implements that strategy.
28493**
28494** This is for MacOSX only.
28495*/
28496static const sqlite3_io_methods *autolockIoFinderImpl(
28497  const char *filePath,    /* name of the database file */
28498  unixFile *pNew           /* open file object for the database file */
28499){
28500  static const struct Mapping {
28501    const char *zFilesystem;              /* Filesystem type name */
28502    const sqlite3_io_methods *pMethods;   /* Appropriate locking method */
28503  } aMap[] = {
28504    { "hfs",    &posixIoMethods },
28505    { "ufs",    &posixIoMethods },
28506    { "afpfs",  &afpIoMethods },
28507    { "smbfs",  &afpIoMethods },
28508    { "webdav", &nolockIoMethods },
28509    { 0, 0 }
28510  };
28511  int i;
28512  struct statfs fsInfo;
28513  struct flock lockInfo;
28514
28515  if( !filePath ){
28516    /* If filePath==NULL that means we are dealing with a transient file
28517    ** that does not need to be locked. */
28518    return &nolockIoMethods;
28519  }
28520  if( statfs(filePath, &fsInfo) != -1 ){
28521    if( fsInfo.f_flags & MNT_RDONLY ){
28522      return &nolockIoMethods;
28523    }
28524    for(i=0; aMap[i].zFilesystem; i++){
28525      if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){
28526        return aMap[i].pMethods;
28527      }
28528    }
28529  }
28530
28531  /* Default case. Handles, amongst others, "nfs".
28532  ** Test byte-range lock using fcntl(). If the call succeeds,
28533  ** assume that the file-system supports POSIX style locks.
28534  */
28535  lockInfo.l_len = 1;
28536  lockInfo.l_start = 0;
28537  lockInfo.l_whence = SEEK_SET;
28538  lockInfo.l_type = F_RDLCK;
28539  if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
28540    if( strcmp(fsInfo.f_fstypename, "nfs")==0 ){
28541      return &nfsIoMethods;
28542    } else {
28543      return &posixIoMethods;
28544    }
28545  }else{
28546    return &dotlockIoMethods;
28547  }
28548}
28549static const sqlite3_io_methods
28550  *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
28551
28552#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
28553
28554#if OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE
28555/*
28556** This "finder" function attempts to determine the best locking strategy
28557** for the database file "filePath".  It then returns the sqlite3_io_methods
28558** object that implements that strategy.
28559**
28560** This is for VXWorks only.
28561*/
28562static const sqlite3_io_methods *autolockIoFinderImpl(
28563  const char *filePath,    /* name of the database file */
28564  unixFile *pNew           /* the open file object */
28565){
28566  struct flock lockInfo;
28567
28568  if( !filePath ){
28569    /* If filePath==NULL that means we are dealing with a transient file
28570    ** that does not need to be locked. */
28571    return &nolockIoMethods;
28572  }
28573
28574  /* Test if fcntl() is supported and use POSIX style locks.
28575  ** Otherwise fall back to the named semaphore method.
28576  */
28577  lockInfo.l_len = 1;
28578  lockInfo.l_start = 0;
28579  lockInfo.l_whence = SEEK_SET;
28580  lockInfo.l_type = F_RDLCK;
28581  if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
28582    return &posixIoMethods;
28583  }else{
28584    return &semIoMethods;
28585  }
28586}
28587static const sqlite3_io_methods
28588  *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
28589
28590#endif /* OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE */
28591
28592/*
28593** An abstract type for a pointer to a IO method finder function:
28594*/
28595typedef const sqlite3_io_methods *(*finder_type)(const char*,unixFile*);
28596
28597
28598/****************************************************************************
28599**************************** sqlite3_vfs methods ****************************
28600**
28601** This division contains the implementation of methods on the
28602** sqlite3_vfs object.
28603*/
28604
28605/*
28606** Initializes a unixFile structure with zeros.
28607*/
28608void initUnixFile(sqlite3_file* file) {
28609  memset(file, 0, sizeof(unixFile));
28610}
28611
28612/*
28613** Initialize the contents of the unixFile structure pointed to by pId.
28614*/
28615int fillInUnixFile(
28616  sqlite3_vfs *pVfs,      /* Pointer to vfs object */
28617  int h,                  /* Open file descriptor of file being opened */
28618  int syncDir,            /* True to sync directory on first sync */
28619  sqlite3_file *pId,      /* Write to the unixFile structure here */
28620  const char *zFilename,  /* Name of the file being opened */
28621  int noLock,             /* Omit locking if true */
28622  int isDelete,           /* Delete on close if true */
28623  int isReadOnly          /* True if the file is opened read-only */
28624){
28625  const sqlite3_io_methods *pLockingStyle;
28626  unixFile *pNew = (unixFile *)pId;
28627  int rc = SQLITE_OK;
28628
28629  assert( pNew->pInode==NULL );
28630
28631  /* Parameter isDelete is only used on vxworks. Express this explicitly
28632  ** here to prevent compiler warnings about unused parameters.
28633  */
28634  UNUSED_PARAMETER(isDelete);
28635
28636  /* Usually the path zFilename should not be a relative pathname. The
28637  ** exception is when opening the proxy "conch" file in builds that
28638  ** include the special Apple locking styles.
28639  */
28640#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
28641  assert( zFilename==0 || zFilename[0]=='/'
28642    || pVfs->pAppData==(void*)&autolockIoFinder );
28643#else
28644  assert( zFilename==0 || zFilename[0]=='/' );
28645#endif
28646
28647  OSTRACE(("OPEN    %-3d %s\n", h, zFilename));
28648  pNew->h = h;
28649  pNew->zPath = zFilename;
28650  if( strcmp(pVfs->zName,"unix-excl")==0 ){
28651    pNew->ctrlFlags = UNIXFILE_EXCL;
28652  }else{
28653    pNew->ctrlFlags = 0;
28654  }
28655  if( isReadOnly ){
28656    pNew->ctrlFlags |= UNIXFILE_RDONLY;
28657  }
28658  if( syncDir ){
28659    pNew->ctrlFlags |= UNIXFILE_DIRSYNC;
28660  }
28661
28662#if OS_VXWORKS
28663  pNew->pId = vxworksFindFileId(zFilename);
28664  if( pNew->pId==0 ){
28665    noLock = 1;
28666    rc = SQLITE_NOMEM;
28667  }
28668#endif
28669
28670  if( noLock ){
28671    pLockingStyle = &nolockIoMethods;
28672  }else{
28673    pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, pNew);
28674#if SQLITE_ENABLE_LOCKING_STYLE
28675    /* Cache zFilename in the locking context (AFP and dotlock override) for
28676    ** proxyLock activation is possible (remote proxy is based on db name)
28677    ** zFilename remains valid until file is closed, to support */
28678    pNew->lockingContext = (void*)zFilename;
28679#endif
28680  }
28681
28682  if( pLockingStyle == &posixIoMethods
28683#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
28684    || pLockingStyle == &nfsIoMethods
28685#endif
28686  ){
28687    unixEnterMutex();
28688    rc = findInodeInfo(pNew, &pNew->pInode);
28689    if( rc!=SQLITE_OK ){
28690      /* If an error occured in findInodeInfo(), close the file descriptor
28691      ** immediately, before releasing the mutex. findInodeInfo() may fail
28692      ** in two scenarios:
28693      **
28694      **   (a) A call to fstat() failed.
28695      **   (b) A malloc failed.
28696      **
28697      ** Scenario (b) may only occur if the process is holding no other
28698      ** file descriptors open on the same file. If there were other file
28699      ** descriptors on this file, then no malloc would be required by
28700      ** findInodeInfo(). If this is the case, it is quite safe to close
28701      ** handle h - as it is guaranteed that no posix locks will be released
28702      ** by doing so.
28703      **
28704      ** If scenario (a) caused the error then things are not so safe. The
28705      ** implicit assumption here is that if fstat() fails, things are in
28706      ** such bad shape that dropping a lock or two doesn't matter much.
28707      */
28708      robust_close(pNew, h, __LINE__);
28709      h = -1;
28710    }
28711    unixLeaveMutex();
28712  }
28713
28714#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
28715  else if( pLockingStyle == &afpIoMethods ){
28716    /* AFP locking uses the file path so it needs to be included in
28717    ** the afpLockingContext.
28718    */
28719    afpLockingContext *pCtx;
28720    pNew->lockingContext = pCtx = sqlite3_malloc( sizeof(*pCtx) );
28721    if( pCtx==0 ){
28722      rc = SQLITE_NOMEM;
28723    }else{
28724      /* NB: zFilename exists and remains valid until the file is closed
28725      ** according to requirement F11141.  So we do not need to make a
28726      ** copy of the filename. */
28727      pCtx->dbPath = zFilename;
28728      pCtx->reserved = 0;
28729      srandomdev();
28730      unixEnterMutex();
28731      rc = findInodeInfo(pNew, &pNew->pInode);
28732      if( rc!=SQLITE_OK ){
28733        sqlite3_free(pNew->lockingContext);
28734        robust_close(pNew, h, __LINE__);
28735        h = -1;
28736      }
28737      unixLeaveMutex();
28738    }
28739  }
28740#endif
28741
28742  else if( pLockingStyle == &dotlockIoMethods ){
28743    /* Dotfile locking uses the file path so it needs to be included in
28744    ** the dotlockLockingContext
28745    */
28746    char *zLockFile;
28747    int nFilename;
28748    nFilename = (int)strlen(zFilename) + 6;
28749    zLockFile = (char *)sqlite3_malloc(nFilename);
28750    if( zLockFile==0 ){
28751      rc = SQLITE_NOMEM;
28752    }else{
28753      sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename);
28754    }
28755    pNew->lockingContext = zLockFile;
28756  }
28757
28758#if OS_VXWORKS
28759  else if( pLockingStyle == &semIoMethods ){
28760    /* Named semaphore locking uses the file path so it needs to be
28761    ** included in the semLockingContext
28762    */
28763    unixEnterMutex();
28764    rc = findInodeInfo(pNew, &pNew->pInode);
28765    if( (rc==SQLITE_OK) && (pNew->pInode->pSem==NULL) ){
28766      char *zSemName = pNew->pInode->aSemName;
28767      int n;
28768      sqlite3_snprintf(MAX_PATHNAME, zSemName, "/%s.sem",
28769                       pNew->pId->zCanonicalName);
28770      for( n=1; zSemName[n]; n++ )
28771        if( zSemName[n]=='/' ) zSemName[n] = '_';
28772      pNew->pInode->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
28773      if( pNew->pInode->pSem == SEM_FAILED ){
28774        rc = SQLITE_NOMEM;
28775        pNew->pInode->aSemName[0] = '\0';
28776      }
28777    }
28778    unixLeaveMutex();
28779  }
28780#endif
28781
28782  pNew->lastErrno = 0;
28783#if OS_VXWORKS
28784  if( rc!=SQLITE_OK ){
28785    if( h>=0 ) robust_close(pNew, h, __LINE__);
28786    h = -1;
28787    osUnlink(zFilename);
28788    isDelete = 0;
28789  }
28790  pNew->isDelete = isDelete;
28791#endif
28792  if( rc!=SQLITE_OK ){
28793    if( h>=0 ) robust_close(pNew, h, __LINE__);
28794  }else{
28795    pNew->pMethod = pLockingStyle;
28796    OpenCounter(+1);
28797  }
28798  return rc;
28799}
28800
28801/*
28802** Return the name of a directory in which to put temporary files.
28803** If no suitable temporary file directory can be found, return NULL.
28804*/
28805static const char *unixTempFileDir(void){
28806  static const char *azDirs[] = {
28807     0,
28808     0,
28809     "/var/tmp",
28810     "/usr/tmp",
28811     "/tmp",
28812     0        /* List terminator */
28813  };
28814  unsigned int i;
28815  struct stat buf;
28816  const char *zDir = 0;
28817
28818  azDirs[0] = sqlite3_temp_directory;
28819  if( !azDirs[1] ) azDirs[1] = getenv("TMPDIR");
28820  for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); zDir=azDirs[i++]){
28821    if( zDir==0 ) continue;
28822    if( osStat(zDir, &buf) ) continue;
28823    if( !S_ISDIR(buf.st_mode) ) continue;
28824    if( osAccess(zDir, 07) ) continue;
28825    break;
28826  }
28827  return zDir;
28828}
28829
28830/*
28831** Create a temporary file name in zBuf.  zBuf must be allocated
28832** by the calling process and must be big enough to hold at least
28833** pVfs->mxPathname bytes.
28834*/
28835static int unixGetTempname(int nBuf, char *zBuf){
28836  static const unsigned char zChars[] =
28837    "abcdefghijklmnopqrstuvwxyz"
28838    "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
28839    "0123456789";
28840  unsigned int i, j;
28841  const char *zDir;
28842
28843  /* It's odd to simulate an io-error here, but really this is just
28844  ** using the io-error infrastructure to test that SQLite handles this
28845  ** function failing.
28846  */
28847  SimulateIOError( return SQLITE_IOERR );
28848
28849  zDir = unixTempFileDir();
28850  if( zDir==0 ) zDir = ".";
28851
28852  /* Check that the output buffer is large enough for the temporary file
28853  ** name. If it is not, return SQLITE_ERROR.
28854  */
28855  if( (strlen(zDir) + strlen(SQLITE_TEMP_FILE_PREFIX) + 17) >= (size_t)nBuf ){
28856    return SQLITE_ERROR;
28857  }
28858
28859  do{
28860    sqlite3_snprintf(nBuf-17, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX, zDir);
28861    j = (int)strlen(zBuf);
28862    sqlite3_randomness(15, &zBuf[j]);
28863    for(i=0; i<15; i++, j++){
28864      zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
28865    }
28866    zBuf[j] = 0;
28867  }while( osAccess(zBuf,0)==0 );
28868  return SQLITE_OK;
28869}
28870
28871#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
28872/*
28873** Routine to transform a unixFile into a proxy-locking unixFile.
28874** Implementation in the proxy-lock division, but used by unixOpen()
28875** if SQLITE_PREFER_PROXY_LOCKING is defined.
28876*/
28877static int proxyTransformUnixFile(unixFile*, const char*);
28878#endif
28879
28880/*
28881** Search for an unused file descriptor that was opened on the database
28882** file (not a journal or master-journal file) identified by pathname
28883** zPath with SQLITE_OPEN_XXX flags matching those passed as the second
28884** argument to this function.
28885**
28886** Such a file descriptor may exist if a database connection was closed
28887** but the associated file descriptor could not be closed because some
28888** other file descriptor open on the same file is holding a file-lock.
28889** Refer to comments in the unixClose() function and the lengthy comment
28890** describing "Posix Advisory Locking" at the start of this file for
28891** further details. Also, ticket #4018.
28892**
28893** If a suitable file descriptor is found, then it is returned. If no
28894** such file descriptor is located, -1 is returned.
28895*/
28896static UnixUnusedFd *findReusableFd(const char *zPath, int flags){
28897  UnixUnusedFd *pUnused = 0;
28898
28899  /* Do not search for an unused file descriptor on vxworks. Not because
28900  ** vxworks would not benefit from the change (it might, we're not sure),
28901  ** but because no way to test it is currently available. It is better
28902  ** not to risk breaking vxworks support for the sake of such an obscure
28903  ** feature.  */
28904#if !OS_VXWORKS
28905  struct stat sStat;                   /* Results of stat() call */
28906
28907  /* A stat() call may fail for various reasons. If this happens, it is
28908  ** almost certain that an open() call on the same path will also fail.
28909  ** For this reason, if an error occurs in the stat() call here, it is
28910  ** ignored and -1 is returned. The caller will try to open a new file
28911  ** descriptor on the same path, fail, and return an error to SQLite.
28912  **
28913  ** Even if a subsequent open() call does succeed, the consequences of
28914  ** not searching for a resusable file descriptor are not dire.  */
28915  if( 0==osStat(zPath, &sStat) ){
28916    unixInodeInfo *pInode;
28917
28918    unixEnterMutex();
28919    pInode = inodeList;
28920    while( pInode && (pInode->fileId.dev!=sStat.st_dev
28921                     || pInode->fileId.ino!=sStat.st_ino) ){
28922       pInode = pInode->pNext;
28923    }
28924    if( pInode ){
28925      UnixUnusedFd **pp;
28926      for(pp=&pInode->pUnused; *pp && (*pp)->flags!=flags; pp=&((*pp)->pNext));
28927      pUnused = *pp;
28928      if( pUnused ){
28929        *pp = pUnused->pNext;
28930      }
28931    }
28932    unixLeaveMutex();
28933  }
28934#endif    /* if !OS_VXWORKS */
28935  return pUnused;
28936}
28937
28938/*
28939** This function is called by unixOpen() to determine the unix permissions
28940** to create new files with. If no error occurs, then SQLITE_OK is returned
28941** and a value suitable for passing as the third argument to open(2) is
28942** written to *pMode. If an IO error occurs, an SQLite error code is
28943** returned and the value of *pMode is not modified.
28944**
28945** If the file being opened is a temporary file, it is always created with
28946** the octal permissions 0600 (read/writable by owner only). If the file
28947** is a database or master journal file, it is created with the permissions
28948** mask SQLITE_DEFAULT_FILE_PERMISSIONS.
28949**
28950** Finally, if the file being opened is a WAL or regular journal file, then
28951** this function queries the file-system for the permissions on the
28952** corresponding database file and sets *pMode to this value. Whenever
28953** possible, WAL and journal files are created using the same permissions
28954** as the associated database file.
28955*/
28956static int findCreateFileMode(
28957  const char *zPath,              /* Path of file (possibly) being created */
28958  int flags,                      /* Flags passed as 4th argument to xOpen() */
28959  mode_t *pMode                   /* OUT: Permissions to open file with */
28960){
28961  int rc = SQLITE_OK;             /* Return Code */
28962  if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
28963    char zDb[MAX_PATHNAME+1];     /* Database file path */
28964    int nDb;                      /* Number of valid bytes in zDb */
28965    struct stat sStat;            /* Output of stat() on database file */
28966
28967    /* zPath is a path to a WAL or journal file. The following block derives
28968    ** the path to the associated database file from zPath. This block handles
28969    ** the following naming conventions:
28970    **
28971    **   "<path to db>-journal"
28972    **   "<path to db>-wal"
28973    **   "<path to db>-journal-NNNN"
28974    **   "<path to db>-wal-NNNN"
28975    **
28976    ** where NNNN is a 4 digit decimal number. The NNNN naming schemes are
28977    ** used by the test_multiplex.c module.
28978    */
28979    nDb = sqlite3Strlen30(zPath) - 1;
28980    while( nDb>0 && zPath[nDb]!='l' ) nDb--;
28981    nDb -= ((flags & SQLITE_OPEN_WAL) ? 3 : 7);
28982    memcpy(zDb, zPath, nDb);
28983    zDb[nDb] = '\0';
28984
28985    if( 0==osStat(zDb, &sStat) ){
28986      *pMode = sStat.st_mode & 0777;
28987    }else{
28988      rc = SQLITE_IOERR_FSTAT;
28989    }
28990  }else if( flags & SQLITE_OPEN_DELETEONCLOSE ){
28991    *pMode = 0600;
28992  }else{
28993    *pMode = SQLITE_DEFAULT_FILE_PERMISSIONS;
28994  }
28995  return rc;
28996}
28997
28998/*
28999** Initializes a unixFile structure with zeros.
29000*/
29001void chromium_sqlite3_initialize_unix_sqlite3_file(sqlite3_file* file) {
29002  memset(file, 0, sizeof(unixFile));
29003}
29004
29005int chromium_sqlite3_fill_in_unix_sqlite3_file(sqlite3_vfs* vfs,
29006                                               int fd,
29007                                               int dirfd,
29008                                               sqlite3_file* file,
29009                                               const char* fileName,
29010                                               int noLock,
29011                                               int isDelete) {
29012  return fillInUnixFile(vfs, fd, dirfd, file, fileName, noLock, isDelete, 0);
29013}
29014
29015/*
29016** Search for an unused file descriptor that was opened on the database file.
29017** If a suitable file descriptor if found, then it is stored in *fd; otherwise,
29018** *fd is not modified.
29019**
29020** If a reusable file descriptor is not found, and a new UnixUnusedFd cannot
29021** be allocated, SQLITE_NOMEM is returned. Otherwise, SQLITE_OK is returned.
29022*/
29023int chromium_sqlite3_get_reusable_file_handle(sqlite3_file* file,
29024                                              const char* fileName,
29025                                              int flags,
29026                                              int* fd) {
29027  unixFile* unixSQLite3File = (unixFile*)file;
29028  int fileType = flags & 0xFFFFFF00;
29029  if (fileType == SQLITE_OPEN_MAIN_DB) {
29030    UnixUnusedFd *unusedFd = findReusableFd(fileName, flags);
29031    if (unusedFd) {
29032      *fd = unusedFd->fd;
29033    } else {
29034      unusedFd = sqlite3_malloc(sizeof(*unusedFd));
29035      if (!unusedFd) {
29036        return SQLITE_NOMEM;
29037      }
29038    }
29039    unixSQLite3File->pUnused = unusedFd;
29040  }
29041  return SQLITE_OK;
29042}
29043
29044/*
29045** Marks 'fd' as the unused file descriptor for 'pFile'.
29046*/
29047void chromium_sqlite3_update_reusable_file_handle(sqlite3_file* file,
29048                                                  int fd,
29049                                                  int flags) {
29050  unixFile* unixSQLite3File = (unixFile*)file;
29051  if (unixSQLite3File->pUnused) {
29052    unixSQLite3File->pUnused->fd = fd;
29053    unixSQLite3File->pUnused->flags = flags;
29054  }
29055}
29056
29057/*
29058** Destroys pFile's field that keeps track of the unused file descriptor.
29059*/
29060void chromium_sqlite3_destroy_reusable_file_handle(sqlite3_file* file) {
29061  unixFile* unixSQLite3File = (unixFile*)file;
29062  sqlite3_free(unixSQLite3File->pUnused);
29063}
29064
29065/*
29066** Open the file zPath.
29067**
29068** Previously, the SQLite OS layer used three functions in place of this
29069** one:
29070**
29071**     sqlite3OsOpenReadWrite();
29072**     sqlite3OsOpenReadOnly();
29073**     sqlite3OsOpenExclusive();
29074**
29075** These calls correspond to the following combinations of flags:
29076**
29077**     ReadWrite() ->     (READWRITE | CREATE)
29078**     ReadOnly()  ->     (READONLY)
29079**     OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
29080**
29081** The old OpenExclusive() accepted a boolean argument - "delFlag". If
29082** true, the file was configured to be automatically deleted when the
29083** file handle closed. To achieve the same effect using this new
29084** interface, add the DELETEONCLOSE flag to those specified above for
29085** OpenExclusive().
29086*/
29087static int unixOpen(
29088  sqlite3_vfs *pVfs,           /* The VFS for which this is the xOpen method */
29089  const char *zPath,           /* Pathname of file to be opened */
29090  sqlite3_file *pFile,         /* The file descriptor to be filled in */
29091  int flags,                   /* Input flags to control the opening */
29092  int *pOutFlags               /* Output flags returned to SQLite core */
29093){
29094  unixFile *p = (unixFile *)pFile;
29095  int fd = -1;                   /* File descriptor returned by open() */
29096  int openFlags = 0;             /* Flags to pass to open() */
29097  int eType = flags&0xFFFFFF00;  /* Type of file to open */
29098  int noLock;                    /* True to omit locking primitives */
29099  int rc = SQLITE_OK;            /* Function Return Code */
29100
29101  int isExclusive  = (flags & SQLITE_OPEN_EXCLUSIVE);
29102  int isDelete     = (flags & SQLITE_OPEN_DELETEONCLOSE);
29103  int isCreate     = (flags & SQLITE_OPEN_CREATE);
29104  int isReadonly   = (flags & SQLITE_OPEN_READONLY);
29105  int isReadWrite  = (flags & SQLITE_OPEN_READWRITE);
29106#if SQLITE_ENABLE_LOCKING_STYLE
29107  int isAutoProxy  = (flags & SQLITE_OPEN_AUTOPROXY);
29108#endif
29109
29110  /* If creating a master or main-file journal, this function will open
29111  ** a file-descriptor on the directory too. The first time unixSync()
29112  ** is called the directory file descriptor will be fsync()ed and close()d.
29113  */
29114  int syncDir = (isCreate && (
29115        eType==SQLITE_OPEN_MASTER_JOURNAL
29116     || eType==SQLITE_OPEN_MAIN_JOURNAL
29117     || eType==SQLITE_OPEN_WAL
29118  ));
29119
29120  /* If argument zPath is a NULL pointer, this function is required to open
29121  ** a temporary file. Use this buffer to store the file name in.
29122  */
29123  char zTmpname[MAX_PATHNAME+1];
29124  const char *zName = zPath;
29125
29126  /* Check the following statements are true:
29127  **
29128  **   (a) Exactly one of the READWRITE and READONLY flags must be set, and
29129  **   (b) if CREATE is set, then READWRITE must also be set, and
29130  **   (c) if EXCLUSIVE is set, then CREATE must also be set.
29131  **   (d) if DELETEONCLOSE is set, then CREATE must also be set.
29132  */
29133  assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
29134  assert(isCreate==0 || isReadWrite);
29135  assert(isExclusive==0 || isCreate);
29136  assert(isDelete==0 || isCreate);
29137
29138  /* The main DB, main journal, WAL file and master journal are never
29139  ** automatically deleted. Nor are they ever temporary files.  */
29140  assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
29141  assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
29142  assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
29143  assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
29144
29145  /* Assert that the upper layer has set one of the "file-type" flags. */
29146  assert( eType==SQLITE_OPEN_MAIN_DB      || eType==SQLITE_OPEN_TEMP_DB
29147       || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
29148       || eType==SQLITE_OPEN_SUBJOURNAL   || eType==SQLITE_OPEN_MASTER_JOURNAL
29149       || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
29150  );
29151
29152  chromium_sqlite3_initialize_unix_sqlite3_file(pFile);
29153
29154  if( eType==SQLITE_OPEN_MAIN_DB ){
29155    rc = chromium_sqlite3_get_reusable_file_handle(pFile, zName, flags, &fd);
29156    if( rc!=SQLITE_OK ){
29157      return rc;
29158    }
29159  }else if( !zName ){
29160    /* If zName is NULL, the upper layer is requesting a temp file. */
29161    assert(isDelete && !syncDir);
29162    rc = unixGetTempname(MAX_PATHNAME+1, zTmpname);
29163    if( rc!=SQLITE_OK ){
29164      return rc;
29165    }
29166    zName = zTmpname;
29167  }
29168
29169  /* Determine the value of the flags parameter passed to POSIX function
29170  ** open(). These must be calculated even if open() is not called, as
29171  ** they may be stored as part of the file handle and used by the
29172  ** 'conch file' locking functions later on.  */
29173  if( isReadonly )  openFlags |= O_RDONLY;
29174  if( isReadWrite ) openFlags |= O_RDWR;
29175  if( isCreate )    openFlags |= O_CREAT;
29176  if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW);
29177  openFlags |= (O_LARGEFILE|O_BINARY);
29178
29179  if( fd<0 ){
29180    mode_t openMode;              /* Permissions to create file with */
29181    rc = findCreateFileMode(zName, flags, &openMode);
29182    if( rc!=SQLITE_OK ){
29183      assert( !p->pUnused );
29184      assert( eType==SQLITE_OPEN_WAL || eType==SQLITE_OPEN_MAIN_JOURNAL );
29185      return rc;
29186    }
29187    fd = robust_open(zName, openFlags, openMode);
29188    OSTRACE(("OPENX   %-3d %s 0%o\n", fd, zName, openFlags));
29189    if( fd<0 && errno!=EISDIR && isReadWrite && !isExclusive ){
29190      /* Failed to open the file for read/write access. Try read-only. */
29191      flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
29192      openFlags &= ~(O_RDWR|O_CREAT);
29193      flags |= SQLITE_OPEN_READONLY;
29194      openFlags |= O_RDONLY;
29195      isReadonly = 1;
29196      fd = robust_open(zName, openFlags, openMode);
29197    }
29198    if( fd<0 ){
29199      rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zName);
29200      goto open_finished;
29201    }
29202  }
29203  assert( fd>=0 );
29204  if( pOutFlags ){
29205    *pOutFlags = flags;
29206  }
29207
29208  chromium_sqlite3_update_reusable_file_handle(pFile, fd, flags);
29209
29210  if( isDelete ){
29211#if OS_VXWORKS
29212    zPath = zName;
29213#else
29214    osUnlink(zName);
29215#endif
29216  }
29217#if SQLITE_ENABLE_LOCKING_STYLE
29218  else{
29219    p->openFlags = openFlags;
29220  }
29221#endif
29222
29223#ifdef FD_CLOEXEC
29224  osFcntl(fd, F_SETFD, osFcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
29225#endif
29226
29227  noLock = eType!=SQLITE_OPEN_MAIN_DB;
29228
29229
29230#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
29231  struct statfs fsInfo;
29232  if( fstatfs(fd, &fsInfo) == -1 ){
29233    ((unixFile*)pFile)->lastErrno = errno;
29234    robust_close(p, fd, __LINE__);
29235    return SQLITE_IOERR_ACCESS;
29236  }
29237  if (0 == strncmp("msdos", fsInfo.f_fstypename, 5)) {
29238    ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
29239  }
29240#endif
29241
29242#if SQLITE_ENABLE_LOCKING_STYLE
29243#if SQLITE_PREFER_PROXY_LOCKING
29244  isAutoProxy = 1;
29245#endif
29246  if( isAutoProxy && (zPath!=NULL) && (!noLock) && pVfs->xOpen ){
29247    char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING");
29248    int useProxy = 0;
29249
29250    /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy, 0 means
29251    ** never use proxy, NULL means use proxy for non-local files only.  */
29252    if( envforce!=NULL ){
29253      useProxy = atoi(envforce)>0;
29254    }else{
29255      struct statfs fsInfo;
29256      if( statfs(zPath, &fsInfo) == -1 ){
29257        /* In theory, the close(fd) call is sub-optimal. If the file opened
29258        ** with fd is a database file, and there are other connections open
29259        ** on that file that are currently holding advisory locks on it,
29260        ** then the call to close() will cancel those locks. In practice,
29261        ** we're assuming that statfs() doesn't fail very often. At least
29262        ** not while other file descriptors opened by the same process on
29263        ** the same file are working.  */
29264        p->lastErrno = errno;
29265        robust_close(p, fd, __LINE__);
29266        rc = SQLITE_IOERR_ACCESS;
29267        goto open_finished;
29268      }
29269      useProxy = !(fsInfo.f_flags&MNT_LOCAL);
29270    }
29271    if( useProxy ){
29272      rc = fillInUnixFile(pVfs, fd, syncDir, pFile, zPath, noLock,
29273                          isDelete, isReadonly);
29274      if( rc==SQLITE_OK ){
29275        rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:");
29276        if( rc!=SQLITE_OK ){
29277          /* Use unixClose to clean up the resources added in fillInUnixFile
29278          ** and clear all the structure's references.  Specifically,
29279          ** pFile->pMethods will be NULL so sqlite3OsClose will be a no-op
29280          */
29281          unixClose(pFile);
29282          return rc;
29283        }
29284      }
29285      goto open_finished;
29286    }
29287  }
29288#endif
29289
29290  rc = fillInUnixFile(pVfs, fd, syncDir, pFile, zPath, noLock,
29291                      isDelete, isReadonly);
29292open_finished:
29293  if( rc!=SQLITE_OK ){
29294    chromium_sqlite3_destroy_reusable_file_handle(pFile);
29295  }
29296  return rc;
29297}
29298
29299
29300/*
29301** Delete the file at zPath. If the dirSync argument is true, fsync()
29302** the directory after deleting the file.
29303*/
29304static int unixDelete(
29305  sqlite3_vfs *NotUsed,     /* VFS containing this as the xDelete method */
29306  const char *zPath,        /* Name of file to be deleted */
29307  int dirSync               /* If true, fsync() directory after deleting file */
29308){
29309  int rc = SQLITE_OK;
29310  UNUSED_PARAMETER(NotUsed);
29311  SimulateIOError(return SQLITE_IOERR_DELETE);
29312  if( osUnlink(zPath)==(-1) && errno!=ENOENT ){
29313    return unixLogError(SQLITE_IOERR_DELETE, "unlink", zPath);
29314  }
29315#ifndef SQLITE_DISABLE_DIRSYNC
29316  if( dirSync ){
29317    int fd;
29318    rc = osOpenDirectory(zPath, &fd);
29319    if( rc==SQLITE_OK ){
29320#if OS_VXWORKS
29321      if( fsync(fd)==-1 )
29322#else
29323      if( fsync(fd) )
29324#endif
29325      {
29326        rc = unixLogError(SQLITE_IOERR_DIR_FSYNC, "fsync", zPath);
29327      }
29328      robust_close(0, fd, __LINE__);
29329    }else if( rc==SQLITE_CANTOPEN ){
29330      rc = SQLITE_OK;
29331    }
29332  }
29333#endif
29334  return rc;
29335}
29336
29337/*
29338** Test the existance of or access permissions of file zPath. The
29339** test performed depends on the value of flags:
29340**
29341**     SQLITE_ACCESS_EXISTS: Return 1 if the file exists
29342**     SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
29343**     SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
29344**
29345** Otherwise return 0.
29346*/
29347static int unixAccess(
29348  sqlite3_vfs *NotUsed,   /* The VFS containing this xAccess method */
29349  const char *zPath,      /* Path of the file to examine */
29350  int flags,              /* What do we want to learn about the zPath file? */
29351  int *pResOut            /* Write result boolean here */
29352){
29353  int amode = 0;
29354  UNUSED_PARAMETER(NotUsed);
29355  SimulateIOError( return SQLITE_IOERR_ACCESS; );
29356  switch( flags ){
29357    case SQLITE_ACCESS_EXISTS:
29358      amode = F_OK;
29359      break;
29360    case SQLITE_ACCESS_READWRITE:
29361      amode = W_OK|R_OK;
29362      break;
29363    case SQLITE_ACCESS_READ:
29364      amode = R_OK;
29365      break;
29366
29367    default:
29368      assert(!"Invalid flags argument");
29369  }
29370  *pResOut = (osAccess(zPath, amode)==0);
29371  if( flags==SQLITE_ACCESS_EXISTS && *pResOut ){
29372    struct stat buf;
29373    if( 0==osStat(zPath, &buf) && buf.st_size==0 ){
29374      *pResOut = 0;
29375    }
29376  }
29377  return SQLITE_OK;
29378}
29379
29380
29381/*
29382** Turn a relative pathname into a full pathname. The relative path
29383** is stored as a nul-terminated string in the buffer pointed to by
29384** zPath.
29385**
29386** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes
29387** (in this case, MAX_PATHNAME bytes). The full-path is written to
29388** this buffer before returning.
29389*/
29390static int unixFullPathname(
29391  sqlite3_vfs *pVfs,            /* Pointer to vfs object */
29392  const char *zPath,            /* Possibly relative input path */
29393  int nOut,                     /* Size of output buffer in bytes */
29394  char *zOut                    /* Output buffer */
29395){
29396
29397  /* It's odd to simulate an io-error here, but really this is just
29398  ** using the io-error infrastructure to test that SQLite handles this
29399  ** function failing. This function could fail if, for example, the
29400  ** current working directory has been unlinked.
29401  */
29402  SimulateIOError( return SQLITE_ERROR );
29403
29404  assert( pVfs->mxPathname==MAX_PATHNAME );
29405  UNUSED_PARAMETER(pVfs);
29406
29407  zOut[nOut-1] = '\0';
29408  if( zPath[0]=='/' ){
29409    sqlite3_snprintf(nOut, zOut, "%s", zPath);
29410  }else{
29411    int nCwd;
29412    if( osGetcwd(zOut, nOut-1)==0 ){
29413      return unixLogError(SQLITE_CANTOPEN_BKPT, "getcwd", zPath);
29414    }
29415    nCwd = (int)strlen(zOut);
29416    sqlite3_snprintf(nOut-nCwd, &zOut[nCwd], "/%s", zPath);
29417  }
29418  return SQLITE_OK;
29419}
29420
29421
29422#ifndef SQLITE_OMIT_LOAD_EXTENSION
29423/*
29424** Interfaces for opening a shared library, finding entry points
29425** within the shared library, and closing the shared library.
29426*/
29427#include <dlfcn.h>
29428static void *unixDlOpen(sqlite3_vfs *NotUsed, const char *zFilename){
29429  UNUSED_PARAMETER(NotUsed);
29430  return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
29431}
29432
29433/*
29434** SQLite calls this function immediately after a call to unixDlSym() or
29435** unixDlOpen() fails (returns a null pointer). If a more detailed error
29436** message is available, it is written to zBufOut. If no error message
29437** is available, zBufOut is left unmodified and SQLite uses a default
29438** error message.
29439*/
29440static void unixDlError(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut){
29441  const char *zErr;
29442  UNUSED_PARAMETER(NotUsed);
29443  unixEnterMutex();
29444  zErr = dlerror();
29445  if( zErr ){
29446    sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
29447  }
29448  unixLeaveMutex();
29449}
29450static void (*unixDlSym(sqlite3_vfs *NotUsed, void *p, const char*zSym))(void){
29451  /*
29452  ** GCC with -pedantic-errors says that C90 does not allow a void* to be
29453  ** cast into a pointer to a function.  And yet the library dlsym() routine
29454  ** returns a void* which is really a pointer to a function.  So how do we
29455  ** use dlsym() with -pedantic-errors?
29456  **
29457  ** Variable x below is defined to be a pointer to a function taking
29458  ** parameters void* and const char* and returning a pointer to a function.
29459  ** We initialize x by assigning it a pointer to the dlsym() function.
29460  ** (That assignment requires a cast.)  Then we call the function that
29461  ** x points to.
29462  **
29463  ** This work-around is unlikely to work correctly on any system where
29464  ** you really cannot cast a function pointer into void*.  But then, on the
29465  ** other hand, dlsym() will not work on such a system either, so we have
29466  ** not really lost anything.
29467  */
29468  void (*(*x)(void*,const char*))(void);
29469  UNUSED_PARAMETER(NotUsed);
29470  x = (void(*(*)(void*,const char*))(void))dlsym;
29471  return (*x)(p, zSym);
29472}
29473static void unixDlClose(sqlite3_vfs *NotUsed, void *pHandle){
29474  UNUSED_PARAMETER(NotUsed);
29475  dlclose(pHandle);
29476}
29477#else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
29478  #define unixDlOpen  0
29479  #define unixDlError 0
29480  #define unixDlSym   0
29481  #define unixDlClose 0
29482#endif
29483
29484/*
29485** Write nBuf bytes of random data to the supplied buffer zBuf.
29486*/
29487static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
29488  UNUSED_PARAMETER(NotUsed);
29489  assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int)));
29490
29491  /* We have to initialize zBuf to prevent valgrind from reporting
29492  ** errors.  The reports issued by valgrind are incorrect - we would
29493  ** prefer that the randomness be increased by making use of the
29494  ** uninitialized space in zBuf - but valgrind errors tend to worry
29495  ** some users.  Rather than argue, it seems easier just to initialize
29496  ** the whole array and silence valgrind, even if that means less randomness
29497  ** in the random seed.
29498  **
29499  ** When testing, initializing zBuf[] to zero is all we do.  That means
29500  ** that we always use the same random number sequence.  This makes the
29501  ** tests repeatable.
29502  */
29503  memset(zBuf, 0, nBuf);
29504#if !defined(SQLITE_TEST)
29505  {
29506    int pid, fd;
29507    fd = robust_open("/dev/urandom", O_RDONLY, 0);
29508    if( fd<0 ){
29509      time_t t;
29510      time(&t);
29511      memcpy(zBuf, &t, sizeof(t));
29512      pid = getpid();
29513      memcpy(&zBuf[sizeof(t)], &pid, sizeof(pid));
29514      assert( sizeof(t)+sizeof(pid)<=(size_t)nBuf );
29515      nBuf = sizeof(t) + sizeof(pid);
29516    }else{
29517      do{ nBuf = osRead(fd, zBuf, nBuf); }while( nBuf<0 && errno==EINTR );
29518      robust_close(0, fd, __LINE__);
29519    }
29520  }
29521#endif
29522  return nBuf;
29523}
29524
29525
29526/*
29527** Sleep for a little while.  Return the amount of time slept.
29528** The argument is the number of microseconds we want to sleep.
29529** The return value is the number of microseconds of sleep actually
29530** requested from the underlying operating system, a number which
29531** might be greater than or equal to the argument, but not less
29532** than the argument.
29533*/
29534static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){
29535#if OS_VXWORKS
29536  struct timespec sp;
29537
29538  sp.tv_sec = microseconds / 1000000;
29539  sp.tv_nsec = (microseconds % 1000000) * 1000;
29540  nanosleep(&sp, NULL);
29541  UNUSED_PARAMETER(NotUsed);
29542  return microseconds;
29543#elif defined(HAVE_USLEEP) && HAVE_USLEEP
29544  usleep(microseconds);
29545  UNUSED_PARAMETER(NotUsed);
29546  return microseconds;
29547#else
29548  int seconds = (microseconds+999999)/1000000;
29549  sleep(seconds);
29550  UNUSED_PARAMETER(NotUsed);
29551  return seconds*1000000;
29552#endif
29553}
29554
29555/*
29556** The following variable, if set to a non-zero value, is interpreted as
29557** the number of seconds since 1970 and is used to set the result of
29558** sqlite3OsCurrentTime() during testing.
29559*/
29560#ifdef SQLITE_TEST
29561SQLITE_API int sqlite3_current_time = 0;  /* Fake system time in seconds since 1970. */
29562#endif
29563
29564/*
29565** Find the current time (in Universal Coordinated Time).  Write into *piNow
29566** the current time and date as a Julian Day number times 86_400_000.  In
29567** other words, write into *piNow the number of milliseconds since the Julian
29568** epoch of noon in Greenwich on November 24, 4714 B.C according to the
29569** proleptic Gregorian calendar.
29570**
29571** On success, return 0.  Return 1 if the time and date cannot be found.
29572*/
29573static int unixCurrentTimeInt64(sqlite3_vfs *NotUsed, sqlite3_int64 *piNow){
29574  static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
29575#if defined(NO_GETTOD)
29576  time_t t;
29577  time(&t);
29578  *piNow = ((sqlite3_int64)t)*1000 + unixEpoch;
29579#elif OS_VXWORKS
29580  struct timespec sNow;
29581  clock_gettime(CLOCK_REALTIME, &sNow);
29582  *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_nsec/1000000;
29583#else
29584  struct timeval sNow;
29585  gettimeofday(&sNow, 0);
29586  *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_usec/1000;
29587#endif
29588
29589#ifdef SQLITE_TEST
29590  if( sqlite3_current_time ){
29591    *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
29592  }
29593#endif
29594  UNUSED_PARAMETER(NotUsed);
29595  return 0;
29596}
29597
29598/*
29599** Find the current time (in Universal Coordinated Time).  Write the
29600** current time and date as a Julian Day number into *prNow and
29601** return 0.  Return 1 if the time and date cannot be found.
29602*/
29603static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){
29604  sqlite3_int64 i;
29605  UNUSED_PARAMETER(NotUsed);
29606  unixCurrentTimeInt64(0, &i);
29607  *prNow = i/86400000.0;
29608  return 0;
29609}
29610
29611/*
29612** We added the xGetLastError() method with the intention of providing
29613** better low-level error messages when operating-system problems come up
29614** during SQLite operation.  But so far, none of that has been implemented
29615** in the core.  So this routine is never called.  For now, it is merely
29616** a place-holder.
29617*/
29618static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
29619  UNUSED_PARAMETER(NotUsed);
29620  UNUSED_PARAMETER(NotUsed2);
29621  UNUSED_PARAMETER(NotUsed3);
29622  return 0;
29623}
29624
29625
29626/*
29627************************ End of sqlite3_vfs methods ***************************
29628******************************************************************************/
29629
29630/******************************************************************************
29631************************** Begin Proxy Locking ********************************
29632**
29633** Proxy locking is a "uber-locking-method" in this sense:  It uses the
29634** other locking methods on secondary lock files.  Proxy locking is a
29635** meta-layer over top of the primitive locking implemented above.  For
29636** this reason, the division that implements of proxy locking is deferred
29637** until late in the file (here) after all of the other I/O methods have
29638** been defined - so that the primitive locking methods are available
29639** as services to help with the implementation of proxy locking.
29640**
29641****
29642**
29643** The default locking schemes in SQLite use byte-range locks on the
29644** database file to coordinate safe, concurrent access by multiple readers
29645** and writers [http://sqlite.org/lockingv3.html].  The five file locking
29646** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented
29647** as POSIX read & write locks over fixed set of locations (via fsctl),
29648** on AFP and SMB only exclusive byte-range locks are available via fsctl
29649** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states.
29650** To simulate a F_RDLCK on the shared range, on AFP a randomly selected
29651** address in the shared range is taken for a SHARED lock, the entire
29652** shared range is taken for an EXCLUSIVE lock):
29653**
29654**      PENDING_BYTE        0x40000000
29655**      RESERVED_BYTE       0x40000001
29656**      SHARED_RANGE        0x40000002 -> 0x40000200
29657**
29658** This works well on the local file system, but shows a nearly 100x
29659** slowdown in read performance on AFP because the AFP client disables
29660** the read cache when byte-range locks are present.  Enabling the read
29661** cache exposes a cache coherency problem that is present on all OS X
29662** supported network file systems.  NFS and AFP both observe the
29663** close-to-open semantics for ensuring cache coherency
29664** [http://nfs.sourceforge.net/#faq_a8], which does not effectively
29665** address the requirements for concurrent database access by multiple
29666** readers and writers
29667** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html].
29668**
29669** To address the performance and cache coherency issues, proxy file locking
29670** changes the way database access is controlled by limiting access to a
29671** single host at a time and moving file locks off of the database file
29672** and onto a proxy file on the local file system.
29673**
29674**
29675** Using proxy locks
29676** -----------------
29677**
29678** C APIs
29679**
29680**  sqlite3_file_control(db, dbname, SQLITE_SET_LOCKPROXYFILE,
29681**                       <proxy_path> | ":auto:");
29682**  sqlite3_file_control(db, dbname, SQLITE_GET_LOCKPROXYFILE, &<proxy_path>);
29683**
29684**
29685** SQL pragmas
29686**
29687**  PRAGMA [database.]lock_proxy_file=<proxy_path> | :auto:
29688**  PRAGMA [database.]lock_proxy_file
29689**
29690** Specifying ":auto:" means that if there is a conch file with a matching
29691** host ID in it, the proxy path in the conch file will be used, otherwise
29692** a proxy path based on the user's temp dir
29693** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the
29694** actual proxy file name is generated from the name and path of the
29695** database file.  For example:
29696**
29697**       For database path "/Users/me/foo.db"
29698**       The lock path will be "<tmpdir>/sqliteplocks/_Users_me_foo.db:auto:")
29699**
29700** Once a lock proxy is configured for a database connection, it can not
29701** be removed, however it may be switched to a different proxy path via
29702** the above APIs (assuming the conch file is not being held by another
29703** connection or process).
29704**
29705**
29706** How proxy locking works
29707** -----------------------
29708**
29709** Proxy file locking relies primarily on two new supporting files:
29710**
29711**   *  conch file to limit access to the database file to a single host
29712**      at a time
29713**
29714**   *  proxy file to act as a proxy for the advisory locks normally
29715**      taken on the database
29716**
29717** The conch file - to use a proxy file, sqlite must first "hold the conch"
29718** by taking an sqlite-style shared lock on the conch file, reading the
29719** contents and comparing the host's unique host ID (see below) and lock
29720** proxy path against the values stored in the conch.  The conch file is
29721** stored in the same directory as the database file and the file name
29722** is patterned after the database file name as ".<databasename>-conch".
29723** If the conch file does not exist, or it's contents do not match the
29724** host ID and/or proxy path, then the lock is escalated to an exclusive
29725** lock and the conch file contents is updated with the host ID and proxy
29726** path and the lock is downgraded to a shared lock again.  If the conch
29727** is held by another process (with a shared lock), the exclusive lock
29728** will fail and SQLITE_BUSY is returned.
29729**
29730** The proxy file - a single-byte file used for all advisory file locks
29731** normally taken on the database file.   This allows for safe sharing
29732** of the database file for multiple readers and writers on the same
29733** host (the conch ensures that they all use the same local lock file).
29734**
29735** Requesting the lock proxy does not immediately take the conch, it is
29736** only taken when the first request to lock database file is made.
29737** This matches the semantics of the traditional locking behavior, where
29738** opening a connection to a database file does not take a lock on it.
29739** The shared lock and an open file descriptor are maintained until
29740** the connection to the database is closed.
29741**
29742** The proxy file and the lock file are never deleted so they only need
29743** to be created the first time they are used.
29744**
29745** Configuration options
29746** ---------------------
29747**
29748**  SQLITE_PREFER_PROXY_LOCKING
29749**
29750**       Database files accessed on non-local file systems are
29751**       automatically configured for proxy locking, lock files are
29752**       named automatically using the same logic as
29753**       PRAGMA lock_proxy_file=":auto:"
29754**
29755**  SQLITE_PROXY_DEBUG
29756**
29757**       Enables the logging of error messages during host id file
29758**       retrieval and creation
29759**
29760**  LOCKPROXYDIR
29761**
29762**       Overrides the default directory used for lock proxy files that
29763**       are named automatically via the ":auto:" setting
29764**
29765**  SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
29766**
29767**       Permissions to use when creating a directory for storing the
29768**       lock proxy files, only used when LOCKPROXYDIR is not set.
29769**
29770**
29771** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING,
29772** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will
29773** force proxy locking to be used for every database file opened, and 0
29774** will force automatic proxy locking to be disabled for all database
29775** files (explicity calling the SQLITE_SET_LOCKPROXYFILE pragma or
29776** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING).
29777*/
29778
29779/*
29780** Proxy locking is only available on MacOSX
29781*/
29782#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
29783
29784/*
29785** The proxyLockingContext has the path and file structures for the remote
29786** and local proxy files in it
29787*/
29788typedef struct proxyLockingContext proxyLockingContext;
29789struct proxyLockingContext {
29790  unixFile *conchFile;         /* Open conch file */
29791  char *conchFilePath;         /* Name of the conch file */
29792  unixFile *lockProxy;         /* Open proxy lock file */
29793  char *lockProxyPath;         /* Name of the proxy lock file */
29794  char *dbPath;                /* Name of the open file */
29795  int conchHeld;               /* 1 if the conch is held, -1 if lockless */
29796  void *oldLockingContext;     /* Original lockingcontext to restore on close */
29797  sqlite3_io_methods const *pOldMethod;     /* Original I/O methods for close */
29798};
29799
29800/*
29801** The proxy lock file path for the database at dbPath is written into lPath,
29802** which must point to valid, writable memory large enough for a maxLen length
29803** file path.
29804*/
29805static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){
29806  int len;
29807  int dbLen;
29808  int i;
29809
29810#ifdef LOCKPROXYDIR
29811  len = strlcpy(lPath, LOCKPROXYDIR, maxLen);
29812#else
29813# ifdef _CS_DARWIN_USER_TEMP_DIR
29814  {
29815    if( !confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen) ){
29816      OSTRACE(("GETLOCKPATH  failed %s errno=%d pid=%d\n",
29817               lPath, errno, getpid()));
29818      return SQLITE_IOERR_LOCK;
29819    }
29820    len = strlcat(lPath, "sqliteplocks", maxLen);
29821  }
29822# else
29823  len = strlcpy(lPath, "/tmp/", maxLen);
29824# endif
29825#endif
29826
29827  if( lPath[len-1]!='/' ){
29828    len = strlcat(lPath, "/", maxLen);
29829  }
29830
29831  /* transform the db path to a unique cache name */
29832  dbLen = (int)strlen(dbPath);
29833  for( i=0; i<dbLen && (i+len+7)<(int)maxLen; i++){
29834    char c = dbPath[i];
29835    lPath[i+len] = (c=='/')?'_':c;
29836  }
29837  lPath[i+len]='\0';
29838  strlcat(lPath, ":auto:", maxLen);
29839  OSTRACE(("GETLOCKPATH  proxy lock path=%s pid=%d\n", lPath, getpid()));
29840  return SQLITE_OK;
29841}
29842
29843/*
29844 ** Creates the lock file and any missing directories in lockPath
29845 */
29846static int proxyCreateLockPath(const char *lockPath){
29847  int i, len;
29848  char buf[MAXPATHLEN];
29849  int start = 0;
29850
29851  assert(lockPath!=NULL);
29852  /* try to create all the intermediate directories */
29853  len = (int)strlen(lockPath);
29854  buf[0] = lockPath[0];
29855  for( i=1; i<len; i++ ){
29856    if( lockPath[i] == '/' && (i - start > 0) ){
29857      /* only mkdir if leaf dir != "." or "/" or ".." */
29858      if( i-start>2 || (i-start==1 && buf[start] != '.' && buf[start] != '/')
29859         || (i-start==2 && buf[start] != '.' && buf[start+1] != '.') ){
29860        buf[i]='\0';
29861        if( mkdir(buf, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){
29862          int err=errno;
29863          if( err!=EEXIST ) {
29864            OSTRACE(("CREATELOCKPATH  FAILED creating %s, "
29865                     "'%s' proxy lock path=%s pid=%d\n",
29866                     buf, strerror(err), lockPath, getpid()));
29867            return err;
29868          }
29869        }
29870      }
29871      start=i+1;
29872    }
29873    buf[i] = lockPath[i];
29874  }
29875  OSTRACE(("CREATELOCKPATH  proxy lock path=%s pid=%d\n", lockPath, getpid()));
29876  return 0;
29877}
29878
29879/*
29880** Create a new VFS file descriptor (stored in memory obtained from
29881** sqlite3_malloc) and open the file named "path" in the file descriptor.
29882**
29883** The caller is responsible not only for closing the file descriptor
29884** but also for freeing the memory associated with the file descriptor.
29885*/
29886static int proxyCreateUnixFile(
29887    const char *path,        /* path for the new unixFile */
29888    unixFile **ppFile,       /* unixFile created and returned by ref */
29889    int islockfile           /* if non zero missing dirs will be created */
29890) {
29891  int fd = -1;
29892  unixFile *pNew;
29893  int rc = SQLITE_OK;
29894  int openFlags = O_RDWR | O_CREAT;
29895  sqlite3_vfs dummyVfs;
29896  int terrno = 0;
29897  UnixUnusedFd *pUnused = NULL;
29898
29899  /* 1. first try to open/create the file
29900  ** 2. if that fails, and this is a lock file (not-conch), try creating
29901  ** the parent directories and then try again.
29902  ** 3. if that fails, try to open the file read-only
29903  ** otherwise return BUSY (if lock file) or CANTOPEN for the conch file
29904  */
29905  pUnused = findReusableFd(path, openFlags);
29906  if( pUnused ){
29907    fd = pUnused->fd;
29908  }else{
29909    pUnused = sqlite3_malloc(sizeof(*pUnused));
29910    if( !pUnused ){
29911      return SQLITE_NOMEM;
29912    }
29913  }
29914  if( fd<0 ){
29915    fd = robust_open(path, openFlags, SQLITE_DEFAULT_FILE_PERMISSIONS);
29916    terrno = errno;
29917    if( fd<0 && errno==ENOENT && islockfile ){
29918      if( proxyCreateLockPath(path) == SQLITE_OK ){
29919        fd = robust_open(path, openFlags, SQLITE_DEFAULT_FILE_PERMISSIONS);
29920      }
29921    }
29922  }
29923  if( fd<0 ){
29924    openFlags = O_RDONLY;
29925    fd = robust_open(path, openFlags, SQLITE_DEFAULT_FILE_PERMISSIONS);
29926    terrno = errno;
29927  }
29928  if( fd<0 ){
29929    if( islockfile ){
29930      return SQLITE_BUSY;
29931    }
29932    switch (terrno) {
29933      case EACCES:
29934        return SQLITE_PERM;
29935      case EIO:
29936        return SQLITE_IOERR_LOCK; /* even though it is the conch */
29937      default:
29938        return SQLITE_CANTOPEN_BKPT;
29939    }
29940  }
29941
29942  pNew = (unixFile *)sqlite3_malloc(sizeof(*pNew));
29943  if( pNew==NULL ){
29944    rc = SQLITE_NOMEM;
29945    goto end_create_proxy;
29946  }
29947  memset(pNew, 0, sizeof(unixFile));
29948  pNew->openFlags = openFlags;
29949  memset(&dummyVfs, 0, sizeof(dummyVfs));
29950  dummyVfs.pAppData = (void*)&autolockIoFinder;
29951  dummyVfs.zName = "dummy";
29952  pUnused->fd = fd;
29953  pUnused->flags = openFlags;
29954  pNew->pUnused = pUnused;
29955
29956  rc = fillInUnixFile(&dummyVfs, fd, 0, (sqlite3_file*)pNew, path, 0, 0, 0);
29957  if( rc==SQLITE_OK ){
29958    *ppFile = pNew;
29959    return SQLITE_OK;
29960  }
29961end_create_proxy:
29962  robust_close(pNew, fd, __LINE__);
29963  sqlite3_free(pNew);
29964  sqlite3_free(pUnused);
29965  return rc;
29966}
29967
29968#ifdef SQLITE_TEST
29969/* simulate multiple hosts by creating unique hostid file paths */
29970SQLITE_API int sqlite3_hostid_num = 0;
29971#endif
29972
29973#define PROXY_HOSTIDLEN    16  /* conch file host id length */
29974
29975/* Not always defined in the headers as it ought to be */
29976extern int gethostuuid(uuid_t id, const struct timespec *wait);
29977
29978/* get the host ID via gethostuuid(), pHostID must point to PROXY_HOSTIDLEN
29979** bytes of writable memory.
29980*/
29981static int proxyGetHostID(unsigned char *pHostID, int *pError){
29982  assert(PROXY_HOSTIDLEN == sizeof(uuid_t));
29983  memset(pHostID, 0, PROXY_HOSTIDLEN);
29984#if defined(__MAX_OS_X_VERSION_MIN_REQUIRED)\
29985               && __MAC_OS_X_VERSION_MIN_REQUIRED<1050
29986  {
29987    static const struct timespec timeout = {1, 0}; /* 1 sec timeout */
29988    if( gethostuuid(pHostID, &timeout) ){
29989      int err = errno;
29990      if( pError ){
29991        *pError = err;
29992      }
29993      return SQLITE_IOERR;
29994    }
29995  }
29996#endif
29997#ifdef SQLITE_TEST
29998  /* simulate multiple hosts by creating unique hostid file paths */
29999  if( sqlite3_hostid_num != 0){
30000    pHostID[0] = (char)(pHostID[0] + (char)(sqlite3_hostid_num & 0xFF));
30001  }
30002#endif
30003
30004  return SQLITE_OK;
30005}
30006
30007/* The conch file contains the header, host id and lock file path
30008 */
30009#define PROXY_CONCHVERSION 2   /* 1-byte header, 16-byte host id, path */
30010#define PROXY_HEADERLEN    1   /* conch file header length */
30011#define PROXY_PATHINDEX    (PROXY_HEADERLEN+PROXY_HOSTIDLEN)
30012#define PROXY_MAXCONCHLEN  (PROXY_HEADERLEN+PROXY_HOSTIDLEN+MAXPATHLEN)
30013
30014/*
30015** Takes an open conch file, copies the contents to a new path and then moves
30016** it back.  The newly created file's file descriptor is assigned to the
30017** conch file structure and finally the original conch file descriptor is
30018** closed.  Returns zero if successful.
30019*/
30020static int proxyBreakConchLock(unixFile *pFile, uuid_t myHostID){
30021  proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
30022  unixFile *conchFile = pCtx->conchFile;
30023  char tPath[MAXPATHLEN];
30024  char buf[PROXY_MAXCONCHLEN];
30025  char *cPath = pCtx->conchFilePath;
30026  size_t readLen = 0;
30027  size_t pathLen = 0;
30028  char errmsg[64] = "";
30029  int fd = -1;
30030  int rc = -1;
30031  UNUSED_PARAMETER(myHostID);
30032
30033  /* create a new path by replace the trailing '-conch' with '-break' */
30034  pathLen = strlcpy(tPath, cPath, MAXPATHLEN);
30035  if( pathLen>MAXPATHLEN || pathLen<6 ||
30036     (strlcpy(&tPath[pathLen-5], "break", 6) != 5) ){
30037    sqlite3_snprintf(sizeof(errmsg),errmsg,"path error (len %d)",(int)pathLen);
30038    goto end_breaklock;
30039  }
30040  /* read the conch content */
30041  readLen = osPread(conchFile->h, buf, PROXY_MAXCONCHLEN, 0);
30042  if( readLen<PROXY_PATHINDEX ){
30043    sqlite3_snprintf(sizeof(errmsg),errmsg,"read error (len %d)",(int)readLen);
30044    goto end_breaklock;
30045  }
30046  /* write it out to the temporary break file */
30047  fd = robust_open(tPath, (O_RDWR|O_CREAT|O_EXCL),
30048                   SQLITE_DEFAULT_FILE_PERMISSIONS);
30049  if( fd<0 ){
30050    sqlite3_snprintf(sizeof(errmsg), errmsg, "create failed (%d)", errno);
30051    goto end_breaklock;
30052  }
30053  if( osPwrite(fd, buf, readLen, 0) != (ssize_t)readLen ){
30054    sqlite3_snprintf(sizeof(errmsg), errmsg, "write failed (%d)", errno);
30055    goto end_breaklock;
30056  }
30057  if( rename(tPath, cPath) ){
30058    sqlite3_snprintf(sizeof(errmsg), errmsg, "rename failed (%d)", errno);
30059    goto end_breaklock;
30060  }
30061  rc = 0;
30062  fprintf(stderr, "broke stale lock on %s\n", cPath);
30063  robust_close(pFile, conchFile->h, __LINE__);
30064  conchFile->h = fd;
30065  conchFile->openFlags = O_RDWR | O_CREAT;
30066
30067end_breaklock:
30068  if( rc ){
30069    if( fd>=0 ){
30070      osUnlink(tPath);
30071      robust_close(pFile, fd, __LINE__);
30072    }
30073    fprintf(stderr, "failed to break stale lock on %s, %s\n", cPath, errmsg);
30074  }
30075  return rc;
30076}
30077
30078/* Take the requested lock on the conch file and break a stale lock if the
30079** host id matches.
30080*/
30081static int proxyConchLock(unixFile *pFile, uuid_t myHostID, int lockType){
30082  proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
30083  unixFile *conchFile = pCtx->conchFile;
30084  int rc = SQLITE_OK;
30085  int nTries = 0;
30086  struct timespec conchModTime;
30087
30088  do {
30089    rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
30090    nTries ++;
30091    if( rc==SQLITE_BUSY ){
30092      /* If the lock failed (busy):
30093       * 1st try: get the mod time of the conch, wait 0.5s and try again.
30094       * 2nd try: fail if the mod time changed or host id is different, wait
30095       *           10 sec and try again
30096       * 3rd try: break the lock unless the mod time has changed.
30097       */
30098      struct stat buf;
30099      if( osFstat(conchFile->h, &buf) ){
30100        pFile->lastErrno = errno;
30101        return SQLITE_IOERR_LOCK;
30102      }
30103
30104      if( nTries==1 ){
30105        conchModTime = buf.st_mtimespec;
30106        usleep(500000); /* wait 0.5 sec and try the lock again*/
30107        continue;
30108      }
30109
30110      assert( nTries>1 );
30111      if( conchModTime.tv_sec != buf.st_mtimespec.tv_sec ||
30112         conchModTime.tv_nsec != buf.st_mtimespec.tv_nsec ){
30113        return SQLITE_BUSY;
30114      }
30115
30116      if( nTries==2 ){
30117        char tBuf[PROXY_MAXCONCHLEN];
30118        int len = osPread(conchFile->h, tBuf, PROXY_MAXCONCHLEN, 0);
30119        if( len<0 ){
30120          pFile->lastErrno = errno;
30121          return SQLITE_IOERR_LOCK;
30122        }
30123        if( len>PROXY_PATHINDEX && tBuf[0]==(char)PROXY_CONCHVERSION){
30124          /* don't break the lock if the host id doesn't match */
30125          if( 0!=memcmp(&tBuf[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN) ){
30126            return SQLITE_BUSY;
30127          }
30128        }else{
30129          /* don't break the lock on short read or a version mismatch */
30130          return SQLITE_BUSY;
30131        }
30132        usleep(10000000); /* wait 10 sec and try the lock again */
30133        continue;
30134      }
30135
30136      assert( nTries==3 );
30137      if( 0==proxyBreakConchLock(pFile, myHostID) ){
30138        rc = SQLITE_OK;
30139        if( lockType==EXCLUSIVE_LOCK ){
30140          rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK);
30141        }
30142        if( !rc ){
30143          rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
30144        }
30145      }
30146    }
30147  } while( rc==SQLITE_BUSY && nTries<3 );
30148
30149  return rc;
30150}
30151
30152/* Takes the conch by taking a shared lock and read the contents conch, if
30153** lockPath is non-NULL, the host ID and lock file path must match.  A NULL
30154** lockPath means that the lockPath in the conch file will be used if the
30155** host IDs match, or a new lock path will be generated automatically
30156** and written to the conch file.
30157*/
30158static int proxyTakeConch(unixFile *pFile){
30159  proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
30160
30161  if( pCtx->conchHeld!=0 ){
30162    return SQLITE_OK;
30163  }else{
30164    unixFile *conchFile = pCtx->conchFile;
30165    uuid_t myHostID;
30166    int pError = 0;
30167    char readBuf[PROXY_MAXCONCHLEN];
30168    char lockPath[MAXPATHLEN];
30169    char *tempLockPath = NULL;
30170    int rc = SQLITE_OK;
30171    int createConch = 0;
30172    int hostIdMatch = 0;
30173    int readLen = 0;
30174    int tryOldLockPath = 0;
30175    int forceNewLockPath = 0;
30176
30177    OSTRACE(("TAKECONCH  %d for %s pid=%d\n", conchFile->h,
30178             (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"), getpid()));
30179
30180    rc = proxyGetHostID(myHostID, &pError);
30181    if( (rc&0xff)==SQLITE_IOERR ){
30182      pFile->lastErrno = pError;
30183      goto end_takeconch;
30184    }
30185    rc = proxyConchLock(pFile, myHostID, SHARED_LOCK);
30186    if( rc!=SQLITE_OK ){
30187      goto end_takeconch;
30188    }
30189    /* read the existing conch file */
30190    readLen = seekAndRead((unixFile*)conchFile, 0, readBuf, PROXY_MAXCONCHLEN);
30191    if( readLen<0 ){
30192      /* I/O error: lastErrno set by seekAndRead */
30193      pFile->lastErrno = conchFile->lastErrno;
30194      rc = SQLITE_IOERR_READ;
30195      goto end_takeconch;
30196    }else if( readLen<=(PROXY_HEADERLEN+PROXY_HOSTIDLEN) ||
30197             readBuf[0]!=(char)PROXY_CONCHVERSION ){
30198      /* a short read or version format mismatch means we need to create a new
30199      ** conch file.
30200      */
30201      createConch = 1;
30202    }
30203    /* if the host id matches and the lock path already exists in the conch
30204    ** we'll try to use the path there, if we can't open that path, we'll
30205    ** retry with a new auto-generated path
30206    */
30207    do { /* in case we need to try again for an :auto: named lock file */
30208
30209      if( !createConch && !forceNewLockPath ){
30210        hostIdMatch = !memcmp(&readBuf[PROXY_HEADERLEN], myHostID,
30211                                  PROXY_HOSTIDLEN);
30212        /* if the conch has data compare the contents */
30213        if( !pCtx->lockProxyPath ){
30214          /* for auto-named local lock file, just check the host ID and we'll
30215           ** use the local lock file path that's already in there
30216           */
30217          if( hostIdMatch ){
30218            size_t pathLen = (readLen - PROXY_PATHINDEX);
30219
30220            if( pathLen>=MAXPATHLEN ){
30221              pathLen=MAXPATHLEN-1;
30222            }
30223            memcpy(lockPath, &readBuf[PROXY_PATHINDEX], pathLen);
30224            lockPath[pathLen] = 0;
30225            tempLockPath = lockPath;
30226            tryOldLockPath = 1;
30227            /* create a copy of the lock path if the conch is taken */
30228            goto end_takeconch;
30229          }
30230        }else if( hostIdMatch
30231               && !strncmp(pCtx->lockProxyPath, &readBuf[PROXY_PATHINDEX],
30232                           readLen-PROXY_PATHINDEX)
30233        ){
30234          /* conch host and lock path match */
30235          goto end_takeconch;
30236        }
30237      }
30238
30239      /* if the conch isn't writable and doesn't match, we can't take it */
30240      if( (conchFile->openFlags&O_RDWR) == 0 ){
30241        rc = SQLITE_BUSY;
30242        goto end_takeconch;
30243      }
30244
30245      /* either the conch didn't match or we need to create a new one */
30246      if( !pCtx->lockProxyPath ){
30247        proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN);
30248        tempLockPath = lockPath;
30249        /* create a copy of the lock path _only_ if the conch is taken */
30250      }
30251
30252      /* update conch with host and path (this will fail if other process
30253      ** has a shared lock already), if the host id matches, use the big
30254      ** stick.
30255      */
30256      futimes(conchFile->h, NULL);
30257      if( hostIdMatch && !createConch ){
30258        if( conchFile->pInode && conchFile->pInode->nShared>1 ){
30259          /* We are trying for an exclusive lock but another thread in this
30260           ** same process is still holding a shared lock. */
30261          rc = SQLITE_BUSY;
30262        } else {
30263          rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
30264        }
30265      }else{
30266        rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, EXCLUSIVE_LOCK);
30267      }
30268      if( rc==SQLITE_OK ){
30269        char writeBuffer[PROXY_MAXCONCHLEN];
30270        int writeSize = 0;
30271
30272        writeBuffer[0] = (char)PROXY_CONCHVERSION;
30273        memcpy(&writeBuffer[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN);
30274        if( pCtx->lockProxyPath!=NULL ){
30275          strlcpy(&writeBuffer[PROXY_PATHINDEX], pCtx->lockProxyPath, MAXPATHLEN);
30276        }else{
30277          strlcpy(&writeBuffer[PROXY_PATHINDEX], tempLockPath, MAXPATHLEN);
30278        }
30279        writeSize = PROXY_PATHINDEX + strlen(&writeBuffer[PROXY_PATHINDEX]);
30280        robust_ftruncate(conchFile->h, writeSize);
30281        rc = unixWrite((sqlite3_file *)conchFile, writeBuffer, writeSize, 0);
30282        fsync(conchFile->h);
30283        /* If we created a new conch file (not just updated the contents of a
30284         ** valid conch file), try to match the permissions of the database
30285         */
30286        if( rc==SQLITE_OK && createConch ){
30287          struct stat buf;
30288          int err = osFstat(pFile->h, &buf);
30289          if( err==0 ){
30290            mode_t cmode = buf.st_mode&(S_IRUSR|S_IWUSR | S_IRGRP|S_IWGRP |
30291                                        S_IROTH|S_IWOTH);
30292            /* try to match the database file R/W permissions, ignore failure */
30293#ifndef SQLITE_PROXY_DEBUG
30294            osFchmod(conchFile->h, cmode);
30295#else
30296            do{
30297              rc = osFchmod(conchFile->h, cmode);
30298            }while( rc==(-1) && errno==EINTR );
30299            if( rc!=0 ){
30300              int code = errno;
30301              fprintf(stderr, "fchmod %o FAILED with %d %s\n",
30302                      cmode, code, strerror(code));
30303            } else {
30304              fprintf(stderr, "fchmod %o SUCCEDED\n",cmode);
30305            }
30306          }else{
30307            int code = errno;
30308            fprintf(stderr, "STAT FAILED[%d] with %d %s\n",
30309                    err, code, strerror(code));
30310#endif
30311          }
30312        }
30313      }
30314      conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK);
30315
30316    end_takeconch:
30317      OSTRACE(("TRANSPROXY: CLOSE  %d\n", pFile->h));
30318      if( rc==SQLITE_OK && pFile->openFlags ){
30319        if( pFile->h>=0 ){
30320          robust_close(pFile, pFile->h, __LINE__);
30321        }
30322        pFile->h = -1;
30323        int fd = robust_open(pCtx->dbPath, pFile->openFlags,
30324                      SQLITE_DEFAULT_FILE_PERMISSIONS);
30325        OSTRACE(("TRANSPROXY: OPEN  %d\n", fd));
30326        if( fd>=0 ){
30327          pFile->h = fd;
30328        }else{
30329          rc=SQLITE_CANTOPEN_BKPT; /* SQLITE_BUSY? proxyTakeConch called
30330           during locking */
30331        }
30332      }
30333      if( rc==SQLITE_OK && !pCtx->lockProxy ){
30334        char *path = tempLockPath ? tempLockPath : pCtx->lockProxyPath;
30335        rc = proxyCreateUnixFile(path, &pCtx->lockProxy, 1);
30336        if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM && tryOldLockPath ){
30337          /* we couldn't create the proxy lock file with the old lock file path
30338           ** so try again via auto-naming
30339           */
30340          forceNewLockPath = 1;
30341          tryOldLockPath = 0;
30342          continue; /* go back to the do {} while start point, try again */
30343        }
30344      }
30345      if( rc==SQLITE_OK ){
30346        /* Need to make a copy of path if we extracted the value
30347         ** from the conch file or the path was allocated on the stack
30348         */
30349        if( tempLockPath ){
30350          pCtx->lockProxyPath = sqlite3DbStrDup(0, tempLockPath);
30351          if( !pCtx->lockProxyPath ){
30352            rc = SQLITE_NOMEM;
30353          }
30354        }
30355      }
30356      if( rc==SQLITE_OK ){
30357        pCtx->conchHeld = 1;
30358
30359        if( pCtx->lockProxy->pMethod == &afpIoMethods ){
30360          afpLockingContext *afpCtx;
30361          afpCtx = (afpLockingContext *)pCtx->lockProxy->lockingContext;
30362          afpCtx->dbPath = pCtx->lockProxyPath;
30363        }
30364      } else {
30365        conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
30366      }
30367      OSTRACE(("TAKECONCH  %d %s\n", conchFile->h,
30368               rc==SQLITE_OK?"ok":"failed"));
30369      return rc;
30370    } while (1); /* in case we need to retry the :auto: lock file -
30371                 ** we should never get here except via the 'continue' call. */
30372  }
30373}
30374
30375/*
30376** If pFile holds a lock on a conch file, then release that lock.
30377*/
30378static int proxyReleaseConch(unixFile *pFile){
30379  int rc = SQLITE_OK;         /* Subroutine return code */
30380  proxyLockingContext *pCtx;  /* The locking context for the proxy lock */
30381  unixFile *conchFile;        /* Name of the conch file */
30382
30383  pCtx = (proxyLockingContext *)pFile->lockingContext;
30384  conchFile = pCtx->conchFile;
30385  OSTRACE(("RELEASECONCH  %d for %s pid=%d\n", conchFile->h,
30386           (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
30387           getpid()));
30388  if( pCtx->conchHeld>0 ){
30389    rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
30390  }
30391  pCtx->conchHeld = 0;
30392  OSTRACE(("RELEASECONCH  %d %s\n", conchFile->h,
30393           (rc==SQLITE_OK ? "ok" : "failed")));
30394  return rc;
30395}
30396
30397/*
30398** Given the name of a database file, compute the name of its conch file.
30399** Store the conch filename in memory obtained from sqlite3_malloc().
30400** Make *pConchPath point to the new name.  Return SQLITE_OK on success
30401** or SQLITE_NOMEM if unable to obtain memory.
30402**
30403** The caller is responsible for ensuring that the allocated memory
30404** space is eventually freed.
30405**
30406** *pConchPath is set to NULL if a memory allocation error occurs.
30407*/
30408static int proxyCreateConchPathname(char *dbPath, char **pConchPath){
30409  int i;                        /* Loop counter */
30410  int len = (int)strlen(dbPath); /* Length of database filename - dbPath */
30411  char *conchPath;              /* buffer in which to construct conch name */
30412
30413  /* Allocate space for the conch filename and initialize the name to
30414  ** the name of the original database file. */
30415  *pConchPath = conchPath = (char *)sqlite3_malloc(len + 8);
30416  if( conchPath==0 ){
30417    return SQLITE_NOMEM;
30418  }
30419  memcpy(conchPath, dbPath, len+1);
30420
30421  /* now insert a "." before the last / character */
30422  for( i=(len-1); i>=0; i-- ){
30423    if( conchPath[i]=='/' ){
30424      i++;
30425      break;
30426    }
30427  }
30428  conchPath[i]='.';
30429  while ( i<len ){
30430    conchPath[i+1]=dbPath[i];
30431    i++;
30432  }
30433
30434  /* append the "-conch" suffix to the file */
30435  memcpy(&conchPath[i+1], "-conch", 7);
30436  assert( (int)strlen(conchPath) == len+7 );
30437
30438  return SQLITE_OK;
30439}
30440
30441
30442/* Takes a fully configured proxy locking-style unix file and switches
30443** the local lock file path
30444*/
30445static int switchLockProxyPath(unixFile *pFile, const char *path) {
30446  proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
30447  char *oldPath = pCtx->lockProxyPath;
30448  int rc = SQLITE_OK;
30449
30450  if( pFile->eFileLock!=NO_LOCK ){
30451    return SQLITE_BUSY;
30452  }
30453
30454  /* nothing to do if the path is NULL, :auto: or matches the existing path */
30455  if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ||
30456    (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){
30457    return SQLITE_OK;
30458  }else{
30459    unixFile *lockProxy = pCtx->lockProxy;
30460    pCtx->lockProxy=NULL;
30461    pCtx->conchHeld = 0;
30462    if( lockProxy!=NULL ){
30463      rc=lockProxy->pMethod->xClose((sqlite3_file *)lockProxy);
30464      if( rc ) return rc;
30465      sqlite3_free(lockProxy);
30466    }
30467    sqlite3_free(oldPath);
30468    pCtx->lockProxyPath = sqlite3DbStrDup(0, path);
30469  }
30470
30471  return rc;
30472}
30473
30474/*
30475** pFile is a file that has been opened by a prior xOpen call.  dbPath
30476** is a string buffer at least MAXPATHLEN+1 characters in size.
30477**
30478** This routine find the filename associated with pFile and writes it
30479** int dbPath.
30480*/
30481static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){
30482#if defined(__APPLE__)
30483  if( pFile->pMethod == &afpIoMethods ){
30484    /* afp style keeps a reference to the db path in the filePath field
30485    ** of the struct */
30486    assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
30487    strlcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath, MAXPATHLEN);
30488  } else
30489#endif
30490  if( pFile->pMethod == &dotlockIoMethods ){
30491    /* dot lock style uses the locking context to store the dot lock
30492    ** file path */
30493    int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX);
30494    memcpy(dbPath, (char *)pFile->lockingContext, len + 1);
30495  }else{
30496    /* all other styles use the locking context to store the db file path */
30497    assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
30498    strlcpy(dbPath, (char *)pFile->lockingContext, MAXPATHLEN);
30499  }
30500  return SQLITE_OK;
30501}
30502
30503/*
30504** Takes an already filled in unix file and alters it so all file locking
30505** will be performed on the local proxy lock file.  The following fields
30506** are preserved in the locking context so that they can be restored and
30507** the unix structure properly cleaned up at close time:
30508**  ->lockingContext
30509**  ->pMethod
30510*/
30511static int proxyTransformUnixFile(unixFile *pFile, const char *path) {
30512  proxyLockingContext *pCtx;
30513  char dbPath[MAXPATHLEN+1];       /* Name of the database file */
30514  char *lockPath=NULL;
30515  int rc = SQLITE_OK;
30516
30517  if( pFile->eFileLock!=NO_LOCK ){
30518    return SQLITE_BUSY;
30519  }
30520  proxyGetDbPathForUnixFile(pFile, dbPath);
30521  if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ){
30522    lockPath=NULL;
30523  }else{
30524    lockPath=(char *)path;
30525  }
30526
30527  OSTRACE(("TRANSPROXY  %d for %s pid=%d\n", pFile->h,
30528           (lockPath ? lockPath : ":auto:"), getpid()));
30529
30530  pCtx = sqlite3_malloc( sizeof(*pCtx) );
30531  if( pCtx==0 ){
30532    return SQLITE_NOMEM;
30533  }
30534  memset(pCtx, 0, sizeof(*pCtx));
30535
30536  rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath);
30537  if( rc==SQLITE_OK ){
30538    rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile, 0);
30539    if( rc==SQLITE_CANTOPEN && ((pFile->openFlags&O_RDWR) == 0) ){
30540      /* if (a) the open flags are not O_RDWR, (b) the conch isn't there, and
30541      ** (c) the file system is read-only, then enable no-locking access.
30542      ** Ugh, since O_RDONLY==0x0000 we test for !O_RDWR since unixOpen asserts
30543      ** that openFlags will have only one of O_RDONLY or O_RDWR.
30544      */
30545      struct statfs fsInfo;
30546      struct stat conchInfo;
30547      int goLockless = 0;
30548
30549      if( osStat(pCtx->conchFilePath, &conchInfo) == -1 ) {
30550        int err = errno;
30551        if( (err==ENOENT) && (statfs(dbPath, &fsInfo) != -1) ){
30552          goLockless = (fsInfo.f_flags&MNT_RDONLY) == MNT_RDONLY;
30553        }
30554      }
30555      if( goLockless ){
30556        pCtx->conchHeld = -1; /* read only FS/ lockless */
30557        rc = SQLITE_OK;
30558      }
30559    }
30560  }
30561  if( rc==SQLITE_OK && lockPath ){
30562    pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath);
30563  }
30564
30565  if( rc==SQLITE_OK ){
30566    pCtx->dbPath = sqlite3DbStrDup(0, dbPath);
30567    if( pCtx->dbPath==NULL ){
30568      rc = SQLITE_NOMEM;
30569    }
30570  }
30571  if( rc==SQLITE_OK ){
30572    /* all memory is allocated, proxys are created and assigned,
30573    ** switch the locking context and pMethod then return.
30574    */
30575    pCtx->oldLockingContext = pFile->lockingContext;
30576    pFile->lockingContext = pCtx;
30577    pCtx->pOldMethod = pFile->pMethod;
30578    pFile->pMethod = &proxyIoMethods;
30579  }else{
30580    if( pCtx->conchFile ){
30581      pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile);
30582      sqlite3_free(pCtx->conchFile);
30583    }
30584    sqlite3DbFree(0, pCtx->lockProxyPath);
30585    sqlite3_free(pCtx->conchFilePath);
30586    sqlite3_free(pCtx);
30587  }
30588  OSTRACE(("TRANSPROXY  %d %s\n", pFile->h,
30589           (rc==SQLITE_OK ? "ok" : "failed")));
30590  return rc;
30591}
30592
30593
30594/*
30595** This routine handles sqlite3_file_control() calls that are specific
30596** to proxy locking.
30597*/
30598static int proxyFileControl(sqlite3_file *id, int op, void *pArg){
30599  switch( op ){
30600    case SQLITE_GET_LOCKPROXYFILE: {
30601      unixFile *pFile = (unixFile*)id;
30602      if( pFile->pMethod == &proxyIoMethods ){
30603        proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
30604        proxyTakeConch(pFile);
30605        if( pCtx->lockProxyPath ){
30606          *(const char **)pArg = pCtx->lockProxyPath;
30607        }else{
30608          *(const char **)pArg = ":auto: (not held)";
30609        }
30610      } else {
30611        *(const char **)pArg = NULL;
30612      }
30613      return SQLITE_OK;
30614    }
30615    case SQLITE_SET_LOCKPROXYFILE: {
30616      unixFile *pFile = (unixFile*)id;
30617      int rc = SQLITE_OK;
30618      int isProxyStyle = (pFile->pMethod == &proxyIoMethods);
30619      if( pArg==NULL || (const char *)pArg==0 ){
30620        if( isProxyStyle ){
30621          /* turn off proxy locking - not supported */
30622          rc = SQLITE_ERROR /*SQLITE_PROTOCOL? SQLITE_MISUSE?*/;
30623        }else{
30624          /* turn off proxy locking - already off - NOOP */
30625          rc = SQLITE_OK;
30626        }
30627      }else{
30628        const char *proxyPath = (const char *)pArg;
30629        if( isProxyStyle ){
30630          proxyLockingContext *pCtx =
30631            (proxyLockingContext*)pFile->lockingContext;
30632          if( !strcmp(pArg, ":auto:")
30633           || (pCtx->lockProxyPath &&
30634               !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN))
30635          ){
30636            rc = SQLITE_OK;
30637          }else{
30638            rc = switchLockProxyPath(pFile, proxyPath);
30639          }
30640        }else{
30641          /* turn on proxy file locking */
30642          rc = proxyTransformUnixFile(pFile, proxyPath);
30643        }
30644      }
30645      return rc;
30646    }
30647    default: {
30648      assert( 0 );  /* The call assures that only valid opcodes are sent */
30649    }
30650  }
30651  /*NOTREACHED*/
30652  return SQLITE_ERROR;
30653}
30654
30655/*
30656** Within this division (the proxying locking implementation) the procedures
30657** above this point are all utilities.  The lock-related methods of the
30658** proxy-locking sqlite3_io_method object follow.
30659*/
30660
30661
30662/*
30663** This routine checks if there is a RESERVED lock held on the specified
30664** file by this or any other process. If such a lock is held, set *pResOut
30665** to a non-zero value otherwise *pResOut is set to zero.  The return value
30666** is set to SQLITE_OK unless an I/O error occurs during lock checking.
30667*/
30668static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) {
30669  unixFile *pFile = (unixFile*)id;
30670  int rc = proxyTakeConch(pFile);
30671  if( rc==SQLITE_OK ){
30672    proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
30673    if( pCtx->conchHeld>0 ){
30674      unixFile *proxy = pCtx->lockProxy;
30675      return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut);
30676    }else{ /* conchHeld < 0 is lockless */
30677      pResOut=0;
30678    }
30679  }
30680  return rc;
30681}
30682
30683/*
30684** Lock the file with the lock specified by parameter eFileLock - one
30685** of the following:
30686**
30687**     (1) SHARED_LOCK
30688**     (2) RESERVED_LOCK
30689**     (3) PENDING_LOCK
30690**     (4) EXCLUSIVE_LOCK
30691**
30692** Sometimes when requesting one lock state, additional lock states
30693** are inserted in between.  The locking might fail on one of the later
30694** transitions leaving the lock state different from what it started but
30695** still short of its goal.  The following chart shows the allowed
30696** transitions and the inserted intermediate states:
30697**
30698**    UNLOCKED -> SHARED
30699**    SHARED -> RESERVED
30700**    SHARED -> (PENDING) -> EXCLUSIVE
30701**    RESERVED -> (PENDING) -> EXCLUSIVE
30702**    PENDING -> EXCLUSIVE
30703**
30704** This routine will only increase a lock.  Use the sqlite3OsUnlock()
30705** routine to lower a locking level.
30706*/
30707static int proxyLock(sqlite3_file *id, int eFileLock) {
30708  unixFile *pFile = (unixFile*)id;
30709  int rc = proxyTakeConch(pFile);
30710  if( rc==SQLITE_OK ){
30711    proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
30712    if( pCtx->conchHeld>0 ){
30713      unixFile *proxy = pCtx->lockProxy;
30714      rc = proxy->pMethod->xLock((sqlite3_file*)proxy, eFileLock);
30715      pFile->eFileLock = proxy->eFileLock;
30716    }else{
30717      /* conchHeld < 0 is lockless */
30718    }
30719  }
30720  return rc;
30721}
30722
30723
30724/*
30725** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
30726** must be either NO_LOCK or SHARED_LOCK.
30727**
30728** If the locking level of the file descriptor is already at or below
30729** the requested locking level, this routine is a no-op.
30730*/
30731static int proxyUnlock(sqlite3_file *id, int eFileLock) {
30732  unixFile *pFile = (unixFile*)id;
30733  int rc = proxyTakeConch(pFile);
30734  if( rc==SQLITE_OK ){
30735    proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
30736    if( pCtx->conchHeld>0 ){
30737      unixFile *proxy = pCtx->lockProxy;
30738      rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, eFileLock);
30739      pFile->eFileLock = proxy->eFileLock;
30740    }else{
30741      /* conchHeld < 0 is lockless */
30742    }
30743  }
30744  return rc;
30745}
30746
30747/*
30748** Close a file that uses proxy locks.
30749*/
30750static int proxyClose(sqlite3_file *id) {
30751  if( id ){
30752    unixFile *pFile = (unixFile*)id;
30753    proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
30754    unixFile *lockProxy = pCtx->lockProxy;
30755    unixFile *conchFile = pCtx->conchFile;
30756    int rc = SQLITE_OK;
30757
30758    if( lockProxy ){
30759      rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK);
30760      if( rc ) return rc;
30761      rc = lockProxy->pMethod->xClose((sqlite3_file*)lockProxy);
30762      if( rc ) return rc;
30763      sqlite3_free(lockProxy);
30764      pCtx->lockProxy = 0;
30765    }
30766    if( conchFile ){
30767      if( pCtx->conchHeld ){
30768        rc = proxyReleaseConch(pFile);
30769        if( rc ) return rc;
30770      }
30771      rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile);
30772      if( rc ) return rc;
30773      sqlite3_free(conchFile);
30774    }
30775    sqlite3DbFree(0, pCtx->lockProxyPath);
30776    sqlite3_free(pCtx->conchFilePath);
30777    sqlite3DbFree(0, pCtx->dbPath);
30778    /* restore the original locking context and pMethod then close it */
30779    pFile->lockingContext = pCtx->oldLockingContext;
30780    pFile->pMethod = pCtx->pOldMethod;
30781    sqlite3_free(pCtx);
30782    return pFile->pMethod->xClose(id);
30783  }
30784  return SQLITE_OK;
30785}
30786
30787
30788
30789#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
30790/*
30791** The proxy locking style is intended for use with AFP filesystems.
30792** And since AFP is only supported on MacOSX, the proxy locking is also
30793** restricted to MacOSX.
30794**
30795**
30796******************* End of the proxy lock implementation **********************
30797******************************************************************************/
30798
30799/*
30800** Initialize the operating system interface.
30801**
30802** This routine registers all VFS implementations for unix-like operating
30803** systems.  This routine, and the sqlite3_os_end() routine that follows,
30804** should be the only routines in this file that are visible from other
30805** files.
30806**
30807** This routine is called once during SQLite initialization and by a
30808** single thread.  The memory allocation and mutex subsystems have not
30809** necessarily been initialized when this routine is called, and so they
30810** should not be used.
30811*/
30812SQLITE_API int sqlite3_os_init(void){
30813  /*
30814  ** The following macro defines an initializer for an sqlite3_vfs object.
30815  ** The name of the VFS is NAME.  The pAppData is a pointer to a pointer
30816  ** to the "finder" function.  (pAppData is a pointer to a pointer because
30817  ** silly C90 rules prohibit a void* from being cast to a function pointer
30818  ** and so we have to go through the intermediate pointer to avoid problems
30819  ** when compiling with -pedantic-errors on GCC.)
30820  **
30821  ** The FINDER parameter to this macro is the name of the pointer to the
30822  ** finder-function.  The finder-function returns a pointer to the
30823  ** sqlite_io_methods object that implements the desired locking
30824  ** behaviors.  See the division above that contains the IOMETHODS
30825  ** macro for addition information on finder-functions.
30826  **
30827  ** Most finders simply return a pointer to a fixed sqlite3_io_methods
30828  ** object.  But the "autolockIoFinder" available on MacOSX does a little
30829  ** more than that; it looks at the filesystem type that hosts the
30830  ** database file and tries to choose an locking method appropriate for
30831  ** that filesystem time.
30832  */
30833  #define UNIXVFS(VFSNAME, FINDER) {                        \
30834    3,                    /* iVersion */                    \
30835    sizeof(unixFile),     /* szOsFile */                    \
30836    MAX_PATHNAME,         /* mxPathname */                  \
30837    0,                    /* pNext */                       \
30838    VFSNAME,              /* zName */                       \
30839    (void*)&FINDER,       /* pAppData */                    \
30840    unixOpen,             /* xOpen */                       \
30841    unixDelete,           /* xDelete */                     \
30842    unixAccess,           /* xAccess */                     \
30843    unixFullPathname,     /* xFullPathname */               \
30844    unixDlOpen,           /* xDlOpen */                     \
30845    unixDlError,          /* xDlError */                    \
30846    unixDlSym,            /* xDlSym */                      \
30847    unixDlClose,          /* xDlClose */                    \
30848    unixRandomness,       /* xRandomness */                 \
30849    unixSleep,            /* xSleep */                      \
30850    unixCurrentTime,      /* xCurrentTime */                \
30851    unixGetLastError,     /* xGetLastError */               \
30852    unixCurrentTimeInt64, /* xCurrentTimeInt64 */           \
30853    unixSetSystemCall,    /* xSetSystemCall */              \
30854    unixGetSystemCall,    /* xGetSystemCall */              \
30855    unixNextSystemCall,   /* xNextSystemCall */             \
30856  }
30857
30858  /*
30859  ** All default VFSes for unix are contained in the following array.
30860  **
30861  ** Note that the sqlite3_vfs.pNext field of the VFS object is modified
30862  ** by the SQLite core when the VFS is registered.  So the following
30863  ** array cannot be const.
30864  */
30865  static sqlite3_vfs aVfs[] = {
30866#if SQLITE_ENABLE_LOCKING_STYLE && (OS_VXWORKS || defined(__APPLE__))
30867    UNIXVFS("unix",          autolockIoFinder ),
30868#else
30869    UNIXVFS("unix",          posixIoFinder ),
30870#endif
30871    UNIXVFS("unix-none",     nolockIoFinder ),
30872    UNIXVFS("unix-dotfile",  dotlockIoFinder ),
30873    UNIXVFS("unix-excl",     posixIoFinder ),
30874#if OS_VXWORKS
30875    UNIXVFS("unix-namedsem", semIoFinder ),
30876#endif
30877#if SQLITE_ENABLE_LOCKING_STYLE
30878    UNIXVFS("unix-posix",    posixIoFinder ),
30879#if !OS_VXWORKS
30880    UNIXVFS("unix-flock",    flockIoFinder ),
30881#endif
30882#endif
30883#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
30884    UNIXVFS("unix-afp",      afpIoFinder ),
30885    UNIXVFS("unix-nfs",      nfsIoFinder ),
30886    UNIXVFS("unix-proxy",    proxyIoFinder ),
30887#endif
30888  };
30889  unsigned int i;          /* Loop counter */
30890
30891  /* Double-check that the aSyscall[] array has been constructed
30892  ** correctly.  See ticket [bb3a86e890c8e96ab] */
30893  assert( ArraySize(aSyscall)==18 );
30894
30895  /* Register all VFSes defined in the aVfs[] array */
30896  for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
30897    sqlite3_vfs_register(&aVfs[i], i==0);
30898  }
30899  return SQLITE_OK;
30900}
30901
30902/*
30903** Shutdown the operating system interface.
30904**
30905** Some operating systems might need to do some cleanup in this routine,
30906** to release dynamically allocated objects.  But not on unix.
30907** This routine is a no-op for unix.
30908*/
30909SQLITE_API int sqlite3_os_end(void){
30910  return SQLITE_OK;
30911}
30912
30913#endif /* SQLITE_OS_UNIX */
30914
30915/************** End of os_unix.c *********************************************/
30916/************** Begin file os_win.c ******************************************/
30917/*
30918** 2004 May 22
30919**
30920** The author disclaims copyright to this source code.  In place of
30921** a legal notice, here is a blessing:
30922**
30923**    May you do good and not evil.
30924**    May you find forgiveness for yourself and forgive others.
30925**    May you share freely, never taking more than you give.
30926**
30927******************************************************************************
30928**
30929** This file contains code that is specific to windows.
30930*/
30931#if SQLITE_OS_WIN               /* This file is used for windows only */
30932
30933
30934/*
30935** A Note About Memory Allocation:
30936**
30937** This driver uses malloc()/free() directly rather than going through
30938** the SQLite-wrappers sqlite3_malloc()/sqlite3_free().  Those wrappers
30939** are designed for use on embedded systems where memory is scarce and
30940** malloc failures happen frequently.  Win32 does not typically run on
30941** embedded systems, and when it does the developers normally have bigger
30942** problems to worry about than running out of memory.  So there is not
30943** a compelling need to use the wrappers.
30944**
30945** But there is a good reason to not use the wrappers.  If we use the
30946** wrappers then we will get simulated malloc() failures within this
30947** driver.  And that causes all kinds of problems for our tests.  We
30948** could enhance SQLite to deal with simulated malloc failures within
30949** the OS driver, but the code to deal with those failure would not
30950** be exercised on Linux (which does not need to malloc() in the driver)
30951** and so we would have difficulty writing coverage tests for that
30952** code.  Better to leave the code out, we think.
30953**
30954** The point of this discussion is as follows:  When creating a new
30955** OS layer for an embedded system, if you use this file as an example,
30956** avoid the use of malloc()/free().  Those routines work ok on windows
30957** desktops but not so well in embedded systems.
30958*/
30959
30960#include <winbase.h>
30961
30962#ifdef __CYGWIN__
30963# include <sys/cygwin.h>
30964#endif
30965
30966/*
30967** Macros used to determine whether or not to use threads.
30968*/
30969#if defined(THREADSAFE) && THREADSAFE
30970# define SQLITE_W32_THREADS 1
30971#endif
30972
30973/*
30974** Include code that is common to all os_*.c files
30975*/
30976/************** Include os_common.h in the middle of os_win.c ****************/
30977/************** Begin file os_common.h ***************************************/
30978/*
30979** 2004 May 22
30980**
30981** The author disclaims copyright to this source code.  In place of
30982** a legal notice, here is a blessing:
30983**
30984**    May you do good and not evil.
30985**    May you find forgiveness for yourself and forgive others.
30986**    May you share freely, never taking more than you give.
30987**
30988******************************************************************************
30989**
30990** This file contains macros and a little bit of code that is common to
30991** all of the platform-specific files (os_*.c) and is #included into those
30992** files.
30993**
30994** This file should be #included by the os_*.c files only.  It is not a
30995** general purpose header file.
30996*/
30997#ifndef _OS_COMMON_H_
30998#define _OS_COMMON_H_
30999
31000/*
31001** At least two bugs have slipped in because we changed the MEMORY_DEBUG
31002** macro to SQLITE_DEBUG and some older makefiles have not yet made the
31003** switch.  The following code should catch this problem at compile-time.
31004*/
31005#ifdef MEMORY_DEBUG
31006# error "The MEMORY_DEBUG macro is obsolete.  Use SQLITE_DEBUG instead."
31007#endif
31008
31009#ifdef SQLITE_DEBUG
31010SQLITE_PRIVATE int sqlite3OSTrace = 0;
31011#define OSTRACE(X)          if( sqlite3OSTrace ) sqlite3DebugPrintf X
31012#else
31013#define OSTRACE(X)
31014#endif
31015
31016/*
31017** Macros for performance tracing.  Normally turned off.  Only works
31018** on i486 hardware.
31019*/
31020#ifdef SQLITE_PERFORMANCE_TRACE
31021
31022/*
31023** hwtime.h contains inline assembler code for implementing
31024** high-performance timing routines.
31025*/
31026/************** Include hwtime.h in the middle of os_common.h ****************/
31027/************** Begin file hwtime.h ******************************************/
31028/*
31029** 2008 May 27
31030**
31031** The author disclaims copyright to this source code.  In place of
31032** a legal notice, here is a blessing:
31033**
31034**    May you do good and not evil.
31035**    May you find forgiveness for yourself and forgive others.
31036**    May you share freely, never taking more than you give.
31037**
31038******************************************************************************
31039**
31040** This file contains inline asm code for retrieving "high-performance"
31041** counters for x86 class CPUs.
31042*/
31043#ifndef _HWTIME_H_
31044#define _HWTIME_H_
31045
31046/*
31047** The following routine only works on pentium-class (or newer) processors.
31048** It uses the RDTSC opcode to read the cycle count value out of the
31049** processor and returns that value.  This can be used for high-res
31050** profiling.
31051*/
31052#if (defined(__GNUC__) || defined(_MSC_VER)) && \
31053      (defined(i386) || defined(__i386__) || defined(_M_IX86))
31054
31055  #if defined(__GNUC__)
31056
31057  __inline__ sqlite_uint64 sqlite3Hwtime(void){
31058     unsigned int lo, hi;
31059     __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
31060     return (sqlite_uint64)hi << 32 | lo;
31061  }
31062
31063  #elif defined(_MSC_VER)
31064
31065  __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
31066     __asm {
31067        rdtsc
31068        ret       ; return value at EDX:EAX
31069     }
31070  }
31071
31072  #endif
31073
31074#elif (defined(__GNUC__) && defined(__x86_64__))
31075
31076  __inline__ sqlite_uint64 sqlite3Hwtime(void){
31077      unsigned long val;
31078      __asm__ __volatile__ ("rdtsc" : "=A" (val));
31079      return val;
31080  }
31081
31082#elif (defined(__GNUC__) && defined(__ppc__))
31083
31084  __inline__ sqlite_uint64 sqlite3Hwtime(void){
31085      unsigned long long retval;
31086      unsigned long junk;
31087      __asm__ __volatile__ ("\n\
31088          1:      mftbu   %1\n\
31089                  mftb    %L0\n\
31090                  mftbu   %0\n\
31091                  cmpw    %0,%1\n\
31092                  bne     1b"
31093                  : "=r" (retval), "=r" (junk));
31094      return retval;
31095  }
31096
31097#else
31098
31099  #error Need implementation of sqlite3Hwtime() for your platform.
31100
31101  /*
31102  ** To compile without implementing sqlite3Hwtime() for your platform,
31103  ** you can remove the above #error and use the following
31104  ** stub function.  You will lose timing support for many
31105  ** of the debugging and testing utilities, but it should at
31106  ** least compile and run.
31107  */
31108SQLITE_PRIVATE   sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
31109
31110#endif
31111
31112#endif /* !defined(_HWTIME_H_) */
31113
31114/************** End of hwtime.h **********************************************/
31115/************** Continuing where we left off in os_common.h ******************/
31116
31117static sqlite_uint64 g_start;
31118static sqlite_uint64 g_elapsed;
31119#define TIMER_START       g_start=sqlite3Hwtime()
31120#define TIMER_END         g_elapsed=sqlite3Hwtime()-g_start
31121#define TIMER_ELAPSED     g_elapsed
31122#else
31123#define TIMER_START
31124#define TIMER_END
31125#define TIMER_ELAPSED     ((sqlite_uint64)0)
31126#endif
31127
31128/*
31129** If we compile with the SQLITE_TEST macro set, then the following block
31130** of code will give us the ability to simulate a disk I/O error.  This
31131** is used for testing the I/O recovery logic.
31132*/
31133#ifdef SQLITE_TEST
31134SQLITE_API int sqlite3_io_error_hit = 0;            /* Total number of I/O Errors */
31135SQLITE_API int sqlite3_io_error_hardhit = 0;        /* Number of non-benign errors */
31136SQLITE_API int sqlite3_io_error_pending = 0;        /* Count down to first I/O error */
31137SQLITE_API int sqlite3_io_error_persist = 0;        /* True if I/O errors persist */
31138SQLITE_API int sqlite3_io_error_benign = 0;         /* True if errors are benign */
31139SQLITE_API int sqlite3_diskfull_pending = 0;
31140SQLITE_API int sqlite3_diskfull = 0;
31141#define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
31142#define SimulateIOError(CODE)  \
31143  if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
31144       || sqlite3_io_error_pending-- == 1 )  \
31145              { local_ioerr(); CODE; }
31146static void local_ioerr(){
31147  IOTRACE(("IOERR\n"));
31148  sqlite3_io_error_hit++;
31149  if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
31150}
31151#define SimulateDiskfullError(CODE) \
31152   if( sqlite3_diskfull_pending ){ \
31153     if( sqlite3_diskfull_pending == 1 ){ \
31154       local_ioerr(); \
31155       sqlite3_diskfull = 1; \
31156       sqlite3_io_error_hit = 1; \
31157       CODE; \
31158     }else{ \
31159       sqlite3_diskfull_pending--; \
31160     } \
31161   }
31162#else
31163#define SimulateIOErrorBenign(X)
31164#define SimulateIOError(A)
31165#define SimulateDiskfullError(A)
31166#endif
31167
31168/*
31169** When testing, keep a count of the number of open files.
31170*/
31171#ifdef SQLITE_TEST
31172SQLITE_API int sqlite3_open_file_count = 0;
31173#define OpenCounter(X)  sqlite3_open_file_count+=(X)
31174#else
31175#define OpenCounter(X)
31176#endif
31177
31178#endif /* !defined(_OS_COMMON_H_) */
31179
31180/************** End of os_common.h *******************************************/
31181/************** Continuing where we left off in os_win.c *********************/
31182
31183/*
31184** Some microsoft compilers lack this definition.
31185*/
31186#ifndef INVALID_FILE_ATTRIBUTES
31187# define INVALID_FILE_ATTRIBUTES ((DWORD)-1)
31188#endif
31189
31190/*
31191** Determine if we are dealing with WindowsCE - which has a much
31192** reduced API.
31193*/
31194#if SQLITE_OS_WINCE
31195# define AreFileApisANSI() 1
31196# define FormatMessageW(a,b,c,d,e,f,g) 0
31197#endif
31198
31199/* Forward references */
31200typedef struct winShm winShm;           /* A connection to shared-memory */
31201typedef struct winShmNode winShmNode;   /* A region of shared-memory */
31202
31203/*
31204** WinCE lacks native support for file locking so we have to fake it
31205** with some code of our own.
31206*/
31207#if SQLITE_OS_WINCE
31208typedef struct winceLock {
31209  int nReaders;       /* Number of reader locks obtained */
31210  BOOL bPending;      /* Indicates a pending lock has been obtained */
31211  BOOL bReserved;     /* Indicates a reserved lock has been obtained */
31212  BOOL bExclusive;    /* Indicates an exclusive lock has been obtained */
31213} winceLock;
31214#endif
31215
31216/*
31217** The winFile structure is a subclass of sqlite3_file* specific to the win32
31218** portability layer.
31219*/
31220typedef struct winFile winFile;
31221struct winFile {
31222  const sqlite3_io_methods *pMethod; /*** Must be first ***/
31223  sqlite3_vfs *pVfs;      /* The VFS used to open this file */
31224  HANDLE h;               /* Handle for accessing the file */
31225  unsigned char locktype; /* Type of lock currently held on this file */
31226  short sharedLockByte;   /* Randomly chosen byte used as a shared lock */
31227  DWORD lastErrno;        /* The Windows errno from the last I/O error */
31228  DWORD sectorSize;       /* Sector size of the device file is on */
31229  winShm *pShm;           /* Instance of shared memory on this file */
31230  const char *zPath;      /* Full pathname of this file */
31231  int szChunk;            /* Chunk size configured by FCNTL_CHUNK_SIZE */
31232#if SQLITE_OS_WINCE
31233  WCHAR *zDeleteOnClose;  /* Name of file to delete when closing */
31234  HANDLE hMutex;          /* Mutex used to control access to shared lock */
31235  HANDLE hShared;         /* Shared memory segment used for locking */
31236  winceLock local;        /* Locks obtained by this instance of winFile */
31237  winceLock *shared;      /* Global shared lock memory for the file  */
31238#endif
31239};
31240
31241/*
31242** Forward prototypes.
31243*/
31244static int getSectorSize(
31245    sqlite3_vfs *pVfs,
31246    const char *zRelative     /* UTF-8 file name */
31247);
31248
31249/*
31250** The following variable is (normally) set once and never changes
31251** thereafter.  It records whether the operating system is Win95
31252** or WinNT.
31253**
31254** 0:   Operating system unknown.
31255** 1:   Operating system is Win95.
31256** 2:   Operating system is WinNT.
31257**
31258** In order to facilitate testing on a WinNT system, the test fixture
31259** can manually set this value to 1 to emulate Win98 behavior.
31260*/
31261#ifdef SQLITE_TEST
31262SQLITE_API int sqlite3_os_type = 0;
31263#else
31264static int sqlite3_os_type = 0;
31265#endif
31266
31267/*
31268** Return true (non-zero) if we are running under WinNT, Win2K, WinXP,
31269** or WinCE.  Return false (zero) for Win95, Win98, or WinME.
31270**
31271** Here is an interesting observation:  Win95, Win98, and WinME lack
31272** the LockFileEx() API.  But we can still statically link against that
31273** API as long as we don't call it when running Win95/98/ME.  A call to
31274** this routine is used to determine if the host is Win95/98/ME or
31275** WinNT/2K/XP so that we will know whether or not we can safely call
31276** the LockFileEx() API.
31277*/
31278#if SQLITE_OS_WINCE
31279# define isNT()  (1)
31280#else
31281  static int isNT(void){
31282    if( sqlite3_os_type==0 ){
31283      OSVERSIONINFO sInfo;
31284      sInfo.dwOSVersionInfoSize = sizeof(sInfo);
31285      GetVersionEx(&sInfo);
31286      sqlite3_os_type = sInfo.dwPlatformId==VER_PLATFORM_WIN32_NT ? 2 : 1;
31287    }
31288    return sqlite3_os_type==2;
31289  }
31290#endif /* SQLITE_OS_WINCE */
31291
31292/*
31293** Convert a UTF-8 string to microsoft unicode (UTF-16?).
31294**
31295** Space to hold the returned string is obtained from malloc.
31296*/
31297static WCHAR *utf8ToUnicode(const char *zFilename){
31298  int nChar;
31299  WCHAR *zWideFilename;
31300
31301  nChar = MultiByteToWideChar(CP_UTF8, 0, zFilename, -1, NULL, 0);
31302  zWideFilename = malloc( nChar*sizeof(zWideFilename[0]) );
31303  if( zWideFilename==0 ){
31304    return 0;
31305  }
31306  nChar = MultiByteToWideChar(CP_UTF8, 0, zFilename, -1, zWideFilename, nChar);
31307  if( nChar==0 ){
31308    free(zWideFilename);
31309    zWideFilename = 0;
31310  }
31311  return zWideFilename;
31312}
31313
31314/*
31315** Convert microsoft unicode to UTF-8.  Space to hold the returned string is
31316** obtained from malloc().
31317*/
31318static char *unicodeToUtf8(const WCHAR *zWideFilename){
31319  int nByte;
31320  char *zFilename;
31321
31322  nByte = WideCharToMultiByte(CP_UTF8, 0, zWideFilename, -1, 0, 0, 0, 0);
31323  zFilename = malloc( nByte );
31324  if( zFilename==0 ){
31325    return 0;
31326  }
31327  nByte = WideCharToMultiByte(CP_UTF8, 0, zWideFilename, -1, zFilename, nByte,
31328                              0, 0);
31329  if( nByte == 0 ){
31330    free(zFilename);
31331    zFilename = 0;
31332  }
31333  return zFilename;
31334}
31335
31336/*
31337** Convert an ansi string to microsoft unicode, based on the
31338** current codepage settings for file apis.
31339**
31340** Space to hold the returned string is obtained
31341** from malloc.
31342*/
31343static WCHAR *mbcsToUnicode(const char *zFilename){
31344  int nByte;
31345  WCHAR *zMbcsFilename;
31346  int codepage = AreFileApisANSI() ? CP_ACP : CP_OEMCP;
31347
31348  nByte = MultiByteToWideChar(codepage, 0, zFilename, -1, NULL,0)*sizeof(WCHAR);
31349  zMbcsFilename = malloc( nByte*sizeof(zMbcsFilename[0]) );
31350  if( zMbcsFilename==0 ){
31351    return 0;
31352  }
31353  nByte = MultiByteToWideChar(codepage, 0, zFilename, -1, zMbcsFilename, nByte);
31354  if( nByte==0 ){
31355    free(zMbcsFilename);
31356    zMbcsFilename = 0;
31357  }
31358  return zMbcsFilename;
31359}
31360
31361/*
31362** Convert microsoft unicode to multibyte character string, based on the
31363** user's Ansi codepage.
31364**
31365** Space to hold the returned string is obtained from
31366** malloc().
31367*/
31368static char *unicodeToMbcs(const WCHAR *zWideFilename){
31369  int nByte;
31370  char *zFilename;
31371  int codepage = AreFileApisANSI() ? CP_ACP : CP_OEMCP;
31372
31373  nByte = WideCharToMultiByte(codepage, 0, zWideFilename, -1, 0, 0, 0, 0);
31374  zFilename = malloc( nByte );
31375  if( zFilename==0 ){
31376    return 0;
31377  }
31378  nByte = WideCharToMultiByte(codepage, 0, zWideFilename, -1, zFilename, nByte,
31379                              0, 0);
31380  if( nByte == 0 ){
31381    free(zFilename);
31382    zFilename = 0;
31383  }
31384  return zFilename;
31385}
31386
31387/*
31388** Convert multibyte character string to UTF-8.  Space to hold the
31389** returned string is obtained from malloc().
31390*/
31391SQLITE_API char *sqlite3_win32_mbcs_to_utf8(const char *zFilename){
31392  char *zFilenameUtf8;
31393  WCHAR *zTmpWide;
31394
31395  zTmpWide = mbcsToUnicode(zFilename);
31396  if( zTmpWide==0 ){
31397    return 0;
31398  }
31399  zFilenameUtf8 = unicodeToUtf8(zTmpWide);
31400  free(zTmpWide);
31401  return zFilenameUtf8;
31402}
31403
31404/*
31405** Convert UTF-8 to multibyte character string.  Space to hold the
31406** returned string is obtained from malloc().
31407*/
31408static char *utf8ToMbcs(const char *zFilename){
31409  char *zFilenameMbcs;
31410  WCHAR *zTmpWide;
31411
31412  zTmpWide = utf8ToUnicode(zFilename);
31413  if( zTmpWide==0 ){
31414    return 0;
31415  }
31416  zFilenameMbcs = unicodeToMbcs(zTmpWide);
31417  free(zTmpWide);
31418  return zFilenameMbcs;
31419}
31420
31421#if SQLITE_OS_WINCE
31422/*************************************************************************
31423** This section contains code for WinCE only.
31424*/
31425/*
31426** WindowsCE does not have a localtime() function.  So create a
31427** substitute.
31428*/
31429struct tm *__cdecl localtime(const time_t *t)
31430{
31431  static struct tm y;
31432  FILETIME uTm, lTm;
31433  SYSTEMTIME pTm;
31434  sqlite3_int64 t64;
31435  t64 = *t;
31436  t64 = (t64 + 11644473600)*10000000;
31437  uTm.dwLowDateTime = (DWORD)(t64 & 0xFFFFFFFF);
31438  uTm.dwHighDateTime= (DWORD)(t64 >> 32);
31439  FileTimeToLocalFileTime(&uTm,&lTm);
31440  FileTimeToSystemTime(&lTm,&pTm);
31441  y.tm_year = pTm.wYear - 1900;
31442  y.tm_mon = pTm.wMonth - 1;
31443  y.tm_wday = pTm.wDayOfWeek;
31444  y.tm_mday = pTm.wDay;
31445  y.tm_hour = pTm.wHour;
31446  y.tm_min = pTm.wMinute;
31447  y.tm_sec = pTm.wSecond;
31448  return &y;
31449}
31450
31451/* This will never be called, but defined to make the code compile */
31452#define GetTempPathA(a,b)
31453
31454#define LockFile(a,b,c,d,e)       winceLockFile(&a, b, c, d, e)
31455#define UnlockFile(a,b,c,d,e)     winceUnlockFile(&a, b, c, d, e)
31456#define LockFileEx(a,b,c,d,e,f)   winceLockFileEx(&a, b, c, d, e, f)
31457
31458#define HANDLE_TO_WINFILE(a) (winFile*)&((char*)a)[-(int)offsetof(winFile,h)]
31459
31460/*
31461** Acquire a lock on the handle h
31462*/
31463static void winceMutexAcquire(HANDLE h){
31464   DWORD dwErr;
31465   do {
31466     dwErr = WaitForSingleObject(h, INFINITE);
31467   } while (dwErr != WAIT_OBJECT_0 && dwErr != WAIT_ABANDONED);
31468}
31469/*
31470** Release a lock acquired by winceMutexAcquire()
31471*/
31472#define winceMutexRelease(h) ReleaseMutex(h)
31473
31474/*
31475** Create the mutex and shared memory used for locking in the file
31476** descriptor pFile
31477*/
31478static BOOL winceCreateLock(const char *zFilename, winFile *pFile){
31479  WCHAR *zTok;
31480  WCHAR *zName = utf8ToUnicode(zFilename);
31481  BOOL bInit = TRUE;
31482
31483  /* Initialize the local lockdata */
31484  ZeroMemory(&pFile->local, sizeof(pFile->local));
31485
31486  /* Replace the backslashes from the filename and lowercase it
31487  ** to derive a mutex name. */
31488  zTok = CharLowerW(zName);
31489  for (;*zTok;zTok++){
31490    if (*zTok == '\\') *zTok = '_';
31491  }
31492
31493  /* Create/open the named mutex */
31494  pFile->hMutex = CreateMutexW(NULL, FALSE, zName);
31495  if (!pFile->hMutex){
31496    pFile->lastErrno = GetLastError();
31497    free(zName);
31498    return FALSE;
31499  }
31500
31501  /* Acquire the mutex before continuing */
31502  winceMutexAcquire(pFile->hMutex);
31503
31504  /* Since the names of named mutexes, semaphores, file mappings etc are
31505  ** case-sensitive, take advantage of that by uppercasing the mutex name
31506  ** and using that as the shared filemapping name.
31507  */
31508  CharUpperW(zName);
31509  pFile->hShared = CreateFileMappingW(INVALID_HANDLE_VALUE, NULL,
31510                                       PAGE_READWRITE, 0, sizeof(winceLock),
31511                                       zName);
31512
31513  /* Set a flag that indicates we're the first to create the memory so it
31514  ** must be zero-initialized */
31515  if (GetLastError() == ERROR_ALREADY_EXISTS){
31516    bInit = FALSE;
31517  }
31518
31519  free(zName);
31520
31521  /* If we succeeded in making the shared memory handle, map it. */
31522  if (pFile->hShared){
31523    pFile->shared = (winceLock*)MapViewOfFile(pFile->hShared,
31524             FILE_MAP_READ|FILE_MAP_WRITE, 0, 0, sizeof(winceLock));
31525    /* If mapping failed, close the shared memory handle and erase it */
31526    if (!pFile->shared){
31527      pFile->lastErrno = GetLastError();
31528      CloseHandle(pFile->hShared);
31529      pFile->hShared = NULL;
31530    }
31531  }
31532
31533  /* If shared memory could not be created, then close the mutex and fail */
31534  if (pFile->hShared == NULL){
31535    winceMutexRelease(pFile->hMutex);
31536    CloseHandle(pFile->hMutex);
31537    pFile->hMutex = NULL;
31538    return FALSE;
31539  }
31540
31541  /* Initialize the shared memory if we're supposed to */
31542  if (bInit) {
31543    ZeroMemory(pFile->shared, sizeof(winceLock));
31544  }
31545
31546  winceMutexRelease(pFile->hMutex);
31547  return TRUE;
31548}
31549
31550/*
31551** Destroy the part of winFile that deals with wince locks
31552*/
31553static void winceDestroyLock(winFile *pFile){
31554  if (pFile->hMutex){
31555    /* Acquire the mutex */
31556    winceMutexAcquire(pFile->hMutex);
31557
31558    /* The following blocks should probably assert in debug mode, but they
31559       are to cleanup in case any locks remained open */
31560    if (pFile->local.nReaders){
31561      pFile->shared->nReaders --;
31562    }
31563    if (pFile->local.bReserved){
31564      pFile->shared->bReserved = FALSE;
31565    }
31566    if (pFile->local.bPending){
31567      pFile->shared->bPending = FALSE;
31568    }
31569    if (pFile->local.bExclusive){
31570      pFile->shared->bExclusive = FALSE;
31571    }
31572
31573    /* De-reference and close our copy of the shared memory handle */
31574    UnmapViewOfFile(pFile->shared);
31575    CloseHandle(pFile->hShared);
31576
31577    /* Done with the mutex */
31578    winceMutexRelease(pFile->hMutex);
31579    CloseHandle(pFile->hMutex);
31580    pFile->hMutex = NULL;
31581  }
31582}
31583
31584/*
31585** An implementation of the LockFile() API of windows for wince
31586*/
31587static BOOL winceLockFile(
31588  HANDLE *phFile,
31589  DWORD dwFileOffsetLow,
31590  DWORD dwFileOffsetHigh,
31591  DWORD nNumberOfBytesToLockLow,
31592  DWORD nNumberOfBytesToLockHigh
31593){
31594  winFile *pFile = HANDLE_TO_WINFILE(phFile);
31595  BOOL bReturn = FALSE;
31596
31597  UNUSED_PARAMETER(dwFileOffsetHigh);
31598  UNUSED_PARAMETER(nNumberOfBytesToLockHigh);
31599
31600  if (!pFile->hMutex) return TRUE;
31601  winceMutexAcquire(pFile->hMutex);
31602
31603  /* Wanting an exclusive lock? */
31604  if (dwFileOffsetLow == (DWORD)SHARED_FIRST
31605       && nNumberOfBytesToLockLow == (DWORD)SHARED_SIZE){
31606    if (pFile->shared->nReaders == 0 && pFile->shared->bExclusive == 0){
31607       pFile->shared->bExclusive = TRUE;
31608       pFile->local.bExclusive = TRUE;
31609       bReturn = TRUE;
31610    }
31611  }
31612
31613  /* Want a read-only lock? */
31614  else if (dwFileOffsetLow == (DWORD)SHARED_FIRST &&
31615           nNumberOfBytesToLockLow == 1){
31616    if (pFile->shared->bExclusive == 0){
31617      pFile->local.nReaders ++;
31618      if (pFile->local.nReaders == 1){
31619        pFile->shared->nReaders ++;
31620      }
31621      bReturn = TRUE;
31622    }
31623  }
31624
31625  /* Want a pending lock? */
31626  else if (dwFileOffsetLow == (DWORD)PENDING_BYTE && nNumberOfBytesToLockLow == 1){
31627    /* If no pending lock has been acquired, then acquire it */
31628    if (pFile->shared->bPending == 0) {
31629      pFile->shared->bPending = TRUE;
31630      pFile->local.bPending = TRUE;
31631      bReturn = TRUE;
31632    }
31633  }
31634
31635  /* Want a reserved lock? */
31636  else if (dwFileOffsetLow == (DWORD)RESERVED_BYTE && nNumberOfBytesToLockLow == 1){
31637    if (pFile->shared->bReserved == 0) {
31638      pFile->shared->bReserved = TRUE;
31639      pFile->local.bReserved = TRUE;
31640      bReturn = TRUE;
31641    }
31642  }
31643
31644  winceMutexRelease(pFile->hMutex);
31645  return bReturn;
31646}
31647
31648/*
31649** An implementation of the UnlockFile API of windows for wince
31650*/
31651static BOOL winceUnlockFile(
31652  HANDLE *phFile,
31653  DWORD dwFileOffsetLow,
31654  DWORD dwFileOffsetHigh,
31655  DWORD nNumberOfBytesToUnlockLow,
31656  DWORD nNumberOfBytesToUnlockHigh
31657){
31658  winFile *pFile = HANDLE_TO_WINFILE(phFile);
31659  BOOL bReturn = FALSE;
31660
31661  UNUSED_PARAMETER(dwFileOffsetHigh);
31662  UNUSED_PARAMETER(nNumberOfBytesToUnlockHigh);
31663
31664  if (!pFile->hMutex) return TRUE;
31665  winceMutexAcquire(pFile->hMutex);
31666
31667  /* Releasing a reader lock or an exclusive lock */
31668  if (dwFileOffsetLow == (DWORD)SHARED_FIRST){
31669    /* Did we have an exclusive lock? */
31670    if (pFile->local.bExclusive){
31671      assert(nNumberOfBytesToUnlockLow == (DWORD)SHARED_SIZE);
31672      pFile->local.bExclusive = FALSE;
31673      pFile->shared->bExclusive = FALSE;
31674      bReturn = TRUE;
31675    }
31676
31677    /* Did we just have a reader lock? */
31678    else if (pFile->local.nReaders){
31679      assert(nNumberOfBytesToUnlockLow == (DWORD)SHARED_SIZE || nNumberOfBytesToUnlockLow == 1);
31680      pFile->local.nReaders --;
31681      if (pFile->local.nReaders == 0)
31682      {
31683        pFile->shared->nReaders --;
31684      }
31685      bReturn = TRUE;
31686    }
31687  }
31688
31689  /* Releasing a pending lock */
31690  else if (dwFileOffsetLow == (DWORD)PENDING_BYTE && nNumberOfBytesToUnlockLow == 1){
31691    if (pFile->local.bPending){
31692      pFile->local.bPending = FALSE;
31693      pFile->shared->bPending = FALSE;
31694      bReturn = TRUE;
31695    }
31696  }
31697  /* Releasing a reserved lock */
31698  else if (dwFileOffsetLow == (DWORD)RESERVED_BYTE && nNumberOfBytesToUnlockLow == 1){
31699    if (pFile->local.bReserved) {
31700      pFile->local.bReserved = FALSE;
31701      pFile->shared->bReserved = FALSE;
31702      bReturn = TRUE;
31703    }
31704  }
31705
31706  winceMutexRelease(pFile->hMutex);
31707  return bReturn;
31708}
31709
31710/*
31711** An implementation of the LockFileEx() API of windows for wince
31712*/
31713static BOOL winceLockFileEx(
31714  HANDLE *phFile,
31715  DWORD dwFlags,
31716  DWORD dwReserved,
31717  DWORD nNumberOfBytesToLockLow,
31718  DWORD nNumberOfBytesToLockHigh,
31719  LPOVERLAPPED lpOverlapped
31720){
31721  UNUSED_PARAMETER(dwReserved);
31722  UNUSED_PARAMETER(nNumberOfBytesToLockHigh);
31723
31724  /* If the caller wants a shared read lock, forward this call
31725  ** to winceLockFile */
31726  if (lpOverlapped->Offset == (DWORD)SHARED_FIRST &&
31727      dwFlags == 1 &&
31728      nNumberOfBytesToLockLow == (DWORD)SHARED_SIZE){
31729    return winceLockFile(phFile, SHARED_FIRST, 0, 1, 0);
31730  }
31731  return FALSE;
31732}
31733/*
31734** End of the special code for wince
31735*****************************************************************************/
31736#endif /* SQLITE_OS_WINCE */
31737
31738/*****************************************************************************
31739** The next group of routines implement the I/O methods specified
31740** by the sqlite3_io_methods object.
31741******************************************************************************/
31742
31743/*
31744** Some microsoft compilers lack this definition.
31745*/
31746#ifndef INVALID_SET_FILE_POINTER
31747# define INVALID_SET_FILE_POINTER ((DWORD)-1)
31748#endif
31749
31750/*
31751** Move the current position of the file handle passed as the first
31752** argument to offset iOffset within the file. If successful, return 0.
31753** Otherwise, set pFile->lastErrno and return non-zero.
31754*/
31755static int seekWinFile(winFile *pFile, sqlite3_int64 iOffset){
31756  LONG upperBits;                 /* Most sig. 32 bits of new offset */
31757  LONG lowerBits;                 /* Least sig. 32 bits of new offset */
31758  DWORD dwRet;                    /* Value returned by SetFilePointer() */
31759
31760  upperBits = (LONG)((iOffset>>32) & 0x7fffffff);
31761  lowerBits = (LONG)(iOffset & 0xffffffff);
31762
31763  /* API oddity: If successful, SetFilePointer() returns a dword
31764  ** containing the lower 32-bits of the new file-offset. Or, if it fails,
31765  ** it returns INVALID_SET_FILE_POINTER. However according to MSDN,
31766  ** INVALID_SET_FILE_POINTER may also be a valid new offset. So to determine
31767  ** whether an error has actually occured, it is also necessary to call
31768  ** GetLastError().
31769  */
31770  dwRet = SetFilePointer(pFile->h, lowerBits, &upperBits, FILE_BEGIN);
31771  if( (dwRet==INVALID_SET_FILE_POINTER && GetLastError()!=NO_ERROR) ){
31772    pFile->lastErrno = GetLastError();
31773    return 1;
31774  }
31775
31776  return 0;
31777}
31778
31779/*
31780** Close a file.
31781**
31782** It is reported that an attempt to close a handle might sometimes
31783** fail.  This is a very unreasonable result, but windows is notorious
31784** for being unreasonable so I do not doubt that it might happen.  If
31785** the close fails, we pause for 100 milliseconds and try again.  As
31786** many as MX_CLOSE_ATTEMPT attempts to close the handle are made before
31787** giving up and returning an error.
31788*/
31789#define MX_CLOSE_ATTEMPT 3
31790static int winClose(sqlite3_file *id){
31791  int rc, cnt = 0;
31792  winFile *pFile = (winFile*)id;
31793
31794  assert( id!=0 );
31795  assert( pFile->pShm==0 );
31796  OSTRACE(("CLOSE %d\n", pFile->h));
31797  do{
31798    rc = CloseHandle(pFile->h);
31799    /* SimulateIOError( rc=0; cnt=MX_CLOSE_ATTEMPT; ); */
31800  }while( rc==0 && ++cnt < MX_CLOSE_ATTEMPT && (Sleep(100), 1) );
31801#if SQLITE_OS_WINCE
31802#define WINCE_DELETION_ATTEMPTS 3
31803  winceDestroyLock(pFile);
31804  if( pFile->zDeleteOnClose ){
31805    int cnt = 0;
31806    while(
31807           DeleteFileW(pFile->zDeleteOnClose)==0
31808        && GetFileAttributesW(pFile->zDeleteOnClose)!=0xffffffff
31809        && cnt++ < WINCE_DELETION_ATTEMPTS
31810    ){
31811       Sleep(100);  /* Wait a little before trying again */
31812    }
31813    free(pFile->zDeleteOnClose);
31814  }
31815#endif
31816  OSTRACE(("CLOSE %d %s\n", pFile->h, rc ? "ok" : "failed"));
31817  OpenCounter(-1);
31818  return rc ? SQLITE_OK : SQLITE_IOERR;
31819}
31820
31821/*
31822** Read data from a file into a buffer.  Return SQLITE_OK if all
31823** bytes were read successfully and SQLITE_IOERR if anything goes
31824** wrong.
31825*/
31826static int winRead(
31827  sqlite3_file *id,          /* File to read from */
31828  void *pBuf,                /* Write content into this buffer */
31829  int amt,                   /* Number of bytes to read */
31830  sqlite3_int64 offset       /* Begin reading at this offset */
31831){
31832  winFile *pFile = (winFile*)id;  /* file handle */
31833  DWORD nRead;                    /* Number of bytes actually read from file */
31834
31835  assert( id!=0 );
31836  SimulateIOError(return SQLITE_IOERR_READ);
31837  OSTRACE(("READ %d lock=%d\n", pFile->h, pFile->locktype));
31838
31839  if( seekWinFile(pFile, offset) ){
31840    return SQLITE_FULL;
31841  }
31842  if( !ReadFile(pFile->h, pBuf, amt, &nRead, 0) ){
31843    pFile->lastErrno = GetLastError();
31844    return SQLITE_IOERR_READ;
31845  }
31846  if( nRead<(DWORD)amt ){
31847    /* Unread parts of the buffer must be zero-filled */
31848    memset(&((char*)pBuf)[nRead], 0, amt-nRead);
31849    return SQLITE_IOERR_SHORT_READ;
31850  }
31851
31852  return SQLITE_OK;
31853}
31854
31855/*
31856** Write data from a buffer into a file.  Return SQLITE_OK on success
31857** or some other error code on failure.
31858*/
31859static int winWrite(
31860  sqlite3_file *id,               /* File to write into */
31861  const void *pBuf,               /* The bytes to be written */
31862  int amt,                        /* Number of bytes to write */
31863  sqlite3_int64 offset            /* Offset into the file to begin writing at */
31864){
31865  int rc;                         /* True if error has occured, else false */
31866  winFile *pFile = (winFile*)id;  /* File handle */
31867
31868  assert( amt>0 );
31869  assert( pFile );
31870  SimulateIOError(return SQLITE_IOERR_WRITE);
31871  SimulateDiskfullError(return SQLITE_FULL);
31872
31873  OSTRACE(("WRITE %d lock=%d\n", pFile->h, pFile->locktype));
31874
31875  rc = seekWinFile(pFile, offset);
31876  if( rc==0 ){
31877    u8 *aRem = (u8 *)pBuf;        /* Data yet to be written */
31878    int nRem = amt;               /* Number of bytes yet to be written */
31879    DWORD nWrite;                 /* Bytes written by each WriteFile() call */
31880
31881    while( nRem>0 && WriteFile(pFile->h, aRem, nRem, &nWrite, 0) && nWrite>0 ){
31882      aRem += nWrite;
31883      nRem -= nWrite;
31884    }
31885    if( nRem>0 ){
31886      pFile->lastErrno = GetLastError();
31887      rc = 1;
31888    }
31889  }
31890
31891  if( rc ){
31892    if( pFile->lastErrno==ERROR_HANDLE_DISK_FULL ){
31893      return SQLITE_FULL;
31894    }
31895    return SQLITE_IOERR_WRITE;
31896  }
31897  return SQLITE_OK;
31898}
31899
31900/*
31901** Truncate an open file to a specified size
31902*/
31903static int winTruncate(sqlite3_file *id, sqlite3_int64 nByte){
31904  winFile *pFile = (winFile*)id;  /* File handle object */
31905  int rc = SQLITE_OK;             /* Return code for this function */
31906
31907  assert( pFile );
31908
31909  OSTRACE(("TRUNCATE %d %lld\n", pFile->h, nByte));
31910  SimulateIOError(return SQLITE_IOERR_TRUNCATE);
31911
31912  /* If the user has configured a chunk-size for this file, truncate the
31913  ** file so that it consists of an integer number of chunks (i.e. the
31914  ** actual file size after the operation may be larger than the requested
31915  ** size).
31916  */
31917  if( pFile->szChunk ){
31918    nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
31919  }
31920
31921  /* SetEndOfFile() returns non-zero when successful, or zero when it fails. */
31922  if( seekWinFile(pFile, nByte) ){
31923    rc = SQLITE_IOERR_TRUNCATE;
31924  }else if( 0==SetEndOfFile(pFile->h) ){
31925    pFile->lastErrno = GetLastError();
31926    rc = SQLITE_IOERR_TRUNCATE;
31927  }
31928
31929  OSTRACE(("TRUNCATE %d %lld %s\n", pFile->h, nByte, rc ? "failed" : "ok"));
31930  return rc;
31931}
31932
31933#ifdef SQLITE_TEST
31934/*
31935** Count the number of fullsyncs and normal syncs.  This is used to test
31936** that syncs and fullsyncs are occuring at the right times.
31937*/
31938SQLITE_API int sqlite3_sync_count = 0;
31939SQLITE_API int sqlite3_fullsync_count = 0;
31940#endif
31941
31942/*
31943** Make sure all writes to a particular file are committed to disk.
31944*/
31945static int winSync(sqlite3_file *id, int flags){
31946#if !defined(NDEBUG) || !defined(SQLITE_NO_SYNC) || defined(SQLITE_DEBUG)
31947  winFile *pFile = (winFile*)id;
31948#else
31949  UNUSED_PARAMETER(id);
31950#endif
31951
31952  assert( pFile );
31953  /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
31954  assert((flags&0x0F)==SQLITE_SYNC_NORMAL
31955      || (flags&0x0F)==SQLITE_SYNC_FULL
31956  );
31957
31958  OSTRACE(("SYNC %d lock=%d\n", pFile->h, pFile->locktype));
31959
31960#ifndef SQLITE_TEST
31961  UNUSED_PARAMETER(flags);
31962#else
31963  if( flags & SQLITE_SYNC_FULL ){
31964    sqlite3_fullsync_count++;
31965  }
31966  sqlite3_sync_count++;
31967#endif
31968
31969  /* Unix cannot, but some systems may return SQLITE_FULL from here. This
31970  ** line is to test that doing so does not cause any problems.
31971  */
31972  SimulateDiskfullError( return SQLITE_FULL );
31973  SimulateIOError( return SQLITE_IOERR; );
31974
31975  /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
31976  ** no-op
31977  */
31978#ifdef SQLITE_NO_SYNC
31979  return SQLITE_OK;
31980#else
31981  if( FlushFileBuffers(pFile->h) ){
31982    return SQLITE_OK;
31983  }else{
31984    pFile->lastErrno = GetLastError();
31985    return SQLITE_IOERR;
31986  }
31987#endif
31988}
31989
31990/*
31991** Determine the current size of a file in bytes
31992*/
31993static int winFileSize(sqlite3_file *id, sqlite3_int64 *pSize){
31994  DWORD upperBits;
31995  DWORD lowerBits;
31996  winFile *pFile = (winFile*)id;
31997  DWORD error;
31998
31999  assert( id!=0 );
32000  SimulateIOError(return SQLITE_IOERR_FSTAT);
32001  lowerBits = GetFileSize(pFile->h, &upperBits);
32002  if(   (lowerBits == INVALID_FILE_SIZE)
32003     && ((error = GetLastError()) != NO_ERROR) )
32004  {
32005    pFile->lastErrno = error;
32006    return SQLITE_IOERR_FSTAT;
32007  }
32008  *pSize = (((sqlite3_int64)upperBits)<<32) + lowerBits;
32009  return SQLITE_OK;
32010}
32011
32012/*
32013** LOCKFILE_FAIL_IMMEDIATELY is undefined on some Windows systems.
32014*/
32015#ifndef LOCKFILE_FAIL_IMMEDIATELY
32016# define LOCKFILE_FAIL_IMMEDIATELY 1
32017#endif
32018
32019/*
32020** Acquire a reader lock.
32021** Different API routines are called depending on whether or not this
32022** is Win95 or WinNT.
32023*/
32024static int getReadLock(winFile *pFile){
32025  int res;
32026  if( isNT() ){
32027    OVERLAPPED ovlp;
32028    ovlp.Offset = SHARED_FIRST;
32029    ovlp.OffsetHigh = 0;
32030    ovlp.hEvent = 0;
32031    res = LockFileEx(pFile->h, LOCKFILE_FAIL_IMMEDIATELY,
32032                     0, SHARED_SIZE, 0, &ovlp);
32033/* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
32034*/
32035#if SQLITE_OS_WINCE==0
32036  }else{
32037    int lk;
32038    sqlite3_randomness(sizeof(lk), &lk);
32039    pFile->sharedLockByte = (short)((lk & 0x7fffffff)%(SHARED_SIZE - 1));
32040    res = LockFile(pFile->h, SHARED_FIRST+pFile->sharedLockByte, 0, 1, 0);
32041#endif
32042  }
32043  if( res == 0 ){
32044    pFile->lastErrno = GetLastError();
32045  }
32046  return res;
32047}
32048
32049/*
32050** Undo a readlock
32051*/
32052static int unlockReadLock(winFile *pFile){
32053  int res;
32054  if( isNT() ){
32055    res = UnlockFile(pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
32056/* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
32057*/
32058#if SQLITE_OS_WINCE==0
32059  }else{
32060    res = UnlockFile(pFile->h, SHARED_FIRST + pFile->sharedLockByte, 0, 1, 0);
32061#endif
32062  }
32063  if( res == 0 ){
32064    pFile->lastErrno = GetLastError();
32065  }
32066  return res;
32067}
32068
32069/*
32070** Lock the file with the lock specified by parameter locktype - one
32071** of the following:
32072**
32073**     (1) SHARED_LOCK
32074**     (2) RESERVED_LOCK
32075**     (3) PENDING_LOCK
32076**     (4) EXCLUSIVE_LOCK
32077**
32078** Sometimes when requesting one lock state, additional lock states
32079** are inserted in between.  The locking might fail on one of the later
32080** transitions leaving the lock state different from what it started but
32081** still short of its goal.  The following chart shows the allowed
32082** transitions and the inserted intermediate states:
32083**
32084**    UNLOCKED -> SHARED
32085**    SHARED -> RESERVED
32086**    SHARED -> (PENDING) -> EXCLUSIVE
32087**    RESERVED -> (PENDING) -> EXCLUSIVE
32088**    PENDING -> EXCLUSIVE
32089**
32090** This routine will only increase a lock.  The winUnlock() routine
32091** erases all locks at once and returns us immediately to locking level 0.
32092** It is not possible to lower the locking level one step at a time.  You
32093** must go straight to locking level 0.
32094*/
32095static int winLock(sqlite3_file *id, int locktype){
32096  int rc = SQLITE_OK;    /* Return code from subroutines */
32097  int res = 1;           /* Result of a windows lock call */
32098  int newLocktype;       /* Set pFile->locktype to this value before exiting */
32099  int gotPendingLock = 0;/* True if we acquired a PENDING lock this time */
32100  winFile *pFile = (winFile*)id;
32101  DWORD error = NO_ERROR;
32102
32103  assert( id!=0 );
32104  OSTRACE(("LOCK %d %d was %d(%d)\n",
32105           pFile->h, locktype, pFile->locktype, pFile->sharedLockByte));
32106
32107  /* If there is already a lock of this type or more restrictive on the
32108  ** OsFile, do nothing. Don't use the end_lock: exit path, as
32109  ** sqlite3OsEnterMutex() hasn't been called yet.
32110  */
32111  if( pFile->locktype>=locktype ){
32112    return SQLITE_OK;
32113  }
32114
32115  /* Make sure the locking sequence is correct
32116  */
32117  assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
32118  assert( locktype!=PENDING_LOCK );
32119  assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
32120
32121  /* Lock the PENDING_LOCK byte if we need to acquire a PENDING lock or
32122  ** a SHARED lock.  If we are acquiring a SHARED lock, the acquisition of
32123  ** the PENDING_LOCK byte is temporary.
32124  */
32125  newLocktype = pFile->locktype;
32126  if(   (pFile->locktype==NO_LOCK)
32127     || (   (locktype==EXCLUSIVE_LOCK)
32128         && (pFile->locktype==RESERVED_LOCK))
32129  ){
32130    int cnt = 3;
32131    while( cnt-->0 && (res = LockFile(pFile->h, PENDING_BYTE, 0, 1, 0))==0 ){
32132      /* Try 3 times to get the pending lock.  The pending lock might be
32133      ** held by another reader process who will release it momentarily.
32134      */
32135      OSTRACE(("could not get a PENDING lock. cnt=%d\n", cnt));
32136      Sleep(1);
32137    }
32138    gotPendingLock = res;
32139    if( !res ){
32140      error = GetLastError();
32141    }
32142  }
32143
32144  /* Acquire a shared lock
32145  */
32146  if( locktype==SHARED_LOCK && res ){
32147    assert( pFile->locktype==NO_LOCK );
32148    res = getReadLock(pFile);
32149    if( res ){
32150      newLocktype = SHARED_LOCK;
32151    }else{
32152      error = GetLastError();
32153    }
32154  }
32155
32156  /* Acquire a RESERVED lock
32157  */
32158  if( locktype==RESERVED_LOCK && res ){
32159    assert( pFile->locktype==SHARED_LOCK );
32160    res = LockFile(pFile->h, RESERVED_BYTE, 0, 1, 0);
32161    if( res ){
32162      newLocktype = RESERVED_LOCK;
32163    }else{
32164      error = GetLastError();
32165    }
32166  }
32167
32168  /* Acquire a PENDING lock
32169  */
32170  if( locktype==EXCLUSIVE_LOCK && res ){
32171    newLocktype = PENDING_LOCK;
32172    gotPendingLock = 0;
32173  }
32174
32175  /* Acquire an EXCLUSIVE lock
32176  */
32177  if( locktype==EXCLUSIVE_LOCK && res ){
32178    assert( pFile->locktype>=SHARED_LOCK );
32179    res = unlockReadLock(pFile);
32180    OSTRACE(("unreadlock = %d\n", res));
32181    res = LockFile(pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
32182    if( res ){
32183      newLocktype = EXCLUSIVE_LOCK;
32184    }else{
32185      error = GetLastError();
32186      OSTRACE(("error-code = %d\n", error));
32187      getReadLock(pFile);
32188    }
32189  }
32190
32191  /* If we are holding a PENDING lock that ought to be released, then
32192  ** release it now.
32193  */
32194  if( gotPendingLock && locktype==SHARED_LOCK ){
32195    UnlockFile(pFile->h, PENDING_BYTE, 0, 1, 0);
32196  }
32197
32198  /* Update the state of the lock has held in the file descriptor then
32199  ** return the appropriate result code.
32200  */
32201  if( res ){
32202    rc = SQLITE_OK;
32203  }else{
32204    OSTRACE(("LOCK FAILED %d trying for %d but got %d\n", pFile->h,
32205           locktype, newLocktype));
32206    pFile->lastErrno = error;
32207    rc = SQLITE_BUSY;
32208  }
32209  pFile->locktype = (u8)newLocktype;
32210  return rc;
32211}
32212
32213/*
32214** This routine checks if there is a RESERVED lock held on the specified
32215** file by this or any other process. If such a lock is held, return
32216** non-zero, otherwise zero.
32217*/
32218static int winCheckReservedLock(sqlite3_file *id, int *pResOut){
32219  int rc;
32220  winFile *pFile = (winFile*)id;
32221
32222  SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
32223
32224  assert( id!=0 );
32225  if( pFile->locktype>=RESERVED_LOCK ){
32226    rc = 1;
32227    OSTRACE(("TEST WR-LOCK %d %d (local)\n", pFile->h, rc));
32228  }else{
32229    rc = LockFile(pFile->h, RESERVED_BYTE, 0, 1, 0);
32230    if( rc ){
32231      UnlockFile(pFile->h, RESERVED_BYTE, 0, 1, 0);
32232    }
32233    rc = !rc;
32234    OSTRACE(("TEST WR-LOCK %d %d (remote)\n", pFile->h, rc));
32235  }
32236  *pResOut = rc;
32237  return SQLITE_OK;
32238}
32239
32240/*
32241** Lower the locking level on file descriptor id to locktype.  locktype
32242** must be either NO_LOCK or SHARED_LOCK.
32243**
32244** If the locking level of the file descriptor is already at or below
32245** the requested locking level, this routine is a no-op.
32246**
32247** It is not possible for this routine to fail if the second argument
32248** is NO_LOCK.  If the second argument is SHARED_LOCK then this routine
32249** might return SQLITE_IOERR;
32250*/
32251static int winUnlock(sqlite3_file *id, int locktype){
32252  int type;
32253  winFile *pFile = (winFile*)id;
32254  int rc = SQLITE_OK;
32255  assert( pFile!=0 );
32256  assert( locktype<=SHARED_LOCK );
32257  OSTRACE(("UNLOCK %d to %d was %d(%d)\n", pFile->h, locktype,
32258          pFile->locktype, pFile->sharedLockByte));
32259  type = pFile->locktype;
32260  if( type>=EXCLUSIVE_LOCK ){
32261    UnlockFile(pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
32262    if( locktype==SHARED_LOCK && !getReadLock(pFile) ){
32263      /* This should never happen.  We should always be able to
32264      ** reacquire the read lock */
32265      rc = SQLITE_IOERR_UNLOCK;
32266    }
32267  }
32268  if( type>=RESERVED_LOCK ){
32269    UnlockFile(pFile->h, RESERVED_BYTE, 0, 1, 0);
32270  }
32271  if( locktype==NO_LOCK && type>=SHARED_LOCK ){
32272    unlockReadLock(pFile);
32273  }
32274  if( type>=PENDING_LOCK ){
32275    UnlockFile(pFile->h, PENDING_BYTE, 0, 1, 0);
32276  }
32277  pFile->locktype = (u8)locktype;
32278  return rc;
32279}
32280
32281/*
32282** Control and query of the open file handle.
32283*/
32284static int winFileControl(sqlite3_file *id, int op, void *pArg){
32285  switch( op ){
32286    case SQLITE_FCNTL_LOCKSTATE: {
32287      *(int*)pArg = ((winFile*)id)->locktype;
32288      return SQLITE_OK;
32289    }
32290    case SQLITE_LAST_ERRNO: {
32291      *(int*)pArg = (int)((winFile*)id)->lastErrno;
32292      return SQLITE_OK;
32293    }
32294    case SQLITE_FCNTL_CHUNK_SIZE: {
32295      ((winFile*)id)->szChunk = *(int *)pArg;
32296      return SQLITE_OK;
32297    }
32298    case SQLITE_FCNTL_SIZE_HINT: {
32299      sqlite3_int64 sz = *(sqlite3_int64*)pArg;
32300      SimulateIOErrorBenign(1);
32301      winTruncate(id, sz);
32302      SimulateIOErrorBenign(0);
32303      return SQLITE_OK;
32304    }
32305    case SQLITE_FCNTL_SYNC_OMITTED: {
32306      return SQLITE_OK;
32307    }
32308  }
32309  return SQLITE_NOTFOUND;
32310}
32311
32312/*
32313** Return the sector size in bytes of the underlying block device for
32314** the specified file. This is almost always 512 bytes, but may be
32315** larger for some devices.
32316**
32317** SQLite code assumes this function cannot fail. It also assumes that
32318** if two files are created in the same file-system directory (i.e.
32319** a database and its journal file) that the sector size will be the
32320** same for both.
32321*/
32322static int winSectorSize(sqlite3_file *id){
32323  assert( id!=0 );
32324  return (int)(((winFile*)id)->sectorSize);
32325}
32326
32327/*
32328** Return a vector of device characteristics.
32329*/
32330static int winDeviceCharacteristics(sqlite3_file *id){
32331  UNUSED_PARAMETER(id);
32332  return SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN;
32333}
32334
32335#ifndef SQLITE_OMIT_WAL
32336
32337/*
32338** Windows will only let you create file view mappings
32339** on allocation size granularity boundaries.
32340** During sqlite3_os_init() we do a GetSystemInfo()
32341** to get the granularity size.
32342*/
32343SYSTEM_INFO winSysInfo;
32344
32345/*
32346** Helper functions to obtain and relinquish the global mutex. The
32347** global mutex is used to protect the winLockInfo objects used by
32348** this file, all of which may be shared by multiple threads.
32349**
32350** Function winShmMutexHeld() is used to assert() that the global mutex
32351** is held when required. This function is only used as part of assert()
32352** statements. e.g.
32353**
32354**   winShmEnterMutex()
32355**     assert( winShmMutexHeld() );
32356**   winShmLeaveMutex()
32357*/
32358static void winShmEnterMutex(void){
32359  sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
32360}
32361static void winShmLeaveMutex(void){
32362  sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
32363}
32364#ifdef SQLITE_DEBUG
32365static int winShmMutexHeld(void) {
32366  return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
32367}
32368#endif
32369
32370/*
32371** Object used to represent a single file opened and mmapped to provide
32372** shared memory.  When multiple threads all reference the same
32373** log-summary, each thread has its own winFile object, but they all
32374** point to a single instance of this object.  In other words, each
32375** log-summary is opened only once per process.
32376**
32377** winShmMutexHeld() must be true when creating or destroying
32378** this object or while reading or writing the following fields:
32379**
32380**      nRef
32381**      pNext
32382**
32383** The following fields are read-only after the object is created:
32384**
32385**      fid
32386**      zFilename
32387**
32388** Either winShmNode.mutex must be held or winShmNode.nRef==0 and
32389** winShmMutexHeld() is true when reading or writing any other field
32390** in this structure.
32391**
32392*/
32393struct winShmNode {
32394  sqlite3_mutex *mutex;      /* Mutex to access this object */
32395  char *zFilename;           /* Name of the file */
32396  winFile hFile;             /* File handle from winOpen */
32397
32398  int szRegion;              /* Size of shared-memory regions */
32399  int nRegion;               /* Size of array apRegion */
32400  struct ShmRegion {
32401    HANDLE hMap;             /* File handle from CreateFileMapping */
32402    void *pMap;
32403  } *aRegion;
32404  DWORD lastErrno;           /* The Windows errno from the last I/O error */
32405
32406  int nRef;                  /* Number of winShm objects pointing to this */
32407  winShm *pFirst;            /* All winShm objects pointing to this */
32408  winShmNode *pNext;         /* Next in list of all winShmNode objects */
32409#ifdef SQLITE_DEBUG
32410  u8 nextShmId;              /* Next available winShm.id value */
32411#endif
32412};
32413
32414/*
32415** A global array of all winShmNode objects.
32416**
32417** The winShmMutexHeld() must be true while reading or writing this list.
32418*/
32419static winShmNode *winShmNodeList = 0;
32420
32421/*
32422** Structure used internally by this VFS to record the state of an
32423** open shared memory connection.
32424**
32425** The following fields are initialized when this object is created and
32426** are read-only thereafter:
32427**
32428**    winShm.pShmNode
32429**    winShm.id
32430**
32431** All other fields are read/write.  The winShm.pShmNode->mutex must be held
32432** while accessing any read/write fields.
32433*/
32434struct winShm {
32435  winShmNode *pShmNode;      /* The underlying winShmNode object */
32436  winShm *pNext;             /* Next winShm with the same winShmNode */
32437  u8 hasMutex;               /* True if holding the winShmNode mutex */
32438  u16 sharedMask;            /* Mask of shared locks held */
32439  u16 exclMask;              /* Mask of exclusive locks held */
32440#ifdef SQLITE_DEBUG
32441  u8 id;                     /* Id of this connection with its winShmNode */
32442#endif
32443};
32444
32445/*
32446** Constants used for locking
32447*/
32448#define WIN_SHM_BASE   ((22+SQLITE_SHM_NLOCK)*4)        /* first lock byte */
32449#define WIN_SHM_DMS    (WIN_SHM_BASE+SQLITE_SHM_NLOCK)  /* deadman switch */
32450
32451/*
32452** Apply advisory locks for all n bytes beginning at ofst.
32453*/
32454#define _SHM_UNLCK  1
32455#define _SHM_RDLCK  2
32456#define _SHM_WRLCK  3
32457static int winShmSystemLock(
32458  winShmNode *pFile,    /* Apply locks to this open shared-memory segment */
32459  int lockType,         /* _SHM_UNLCK, _SHM_RDLCK, or _SHM_WRLCK */
32460  int ofst,             /* Offset to first byte to be locked/unlocked */
32461  int nByte             /* Number of bytes to lock or unlock */
32462){
32463  OVERLAPPED ovlp;
32464  DWORD dwFlags;
32465  int rc = 0;           /* Result code form Lock/UnlockFileEx() */
32466
32467  /* Access to the winShmNode object is serialized by the caller */
32468  assert( sqlite3_mutex_held(pFile->mutex) || pFile->nRef==0 );
32469
32470  /* Initialize the locking parameters */
32471  dwFlags = LOCKFILE_FAIL_IMMEDIATELY;
32472  if( lockType == _SHM_WRLCK ) dwFlags |= LOCKFILE_EXCLUSIVE_LOCK;
32473
32474  memset(&ovlp, 0, sizeof(OVERLAPPED));
32475  ovlp.Offset = ofst;
32476
32477  /* Release/Acquire the system-level lock */
32478  if( lockType==_SHM_UNLCK ){
32479    rc = UnlockFileEx(pFile->hFile.h, 0, nByte, 0, &ovlp);
32480  }else{
32481    rc = LockFileEx(pFile->hFile.h, dwFlags, 0, nByte, 0, &ovlp);
32482  }
32483
32484  if( rc!= 0 ){
32485    rc = SQLITE_OK;
32486  }else{
32487    pFile->lastErrno =  GetLastError();
32488    rc = SQLITE_BUSY;
32489  }
32490
32491  OSTRACE(("SHM-LOCK %d %s %s 0x%08lx\n",
32492           pFile->hFile.h,
32493           rc==SQLITE_OK ? "ok" : "failed",
32494           lockType==_SHM_UNLCK ? "UnlockFileEx" : "LockFileEx",
32495           pFile->lastErrno));
32496
32497  return rc;
32498}
32499
32500/* Forward references to VFS methods */
32501static int winOpen(sqlite3_vfs*,const char*,sqlite3_file*,int,int*);
32502static int winDelete(sqlite3_vfs *,const char*,int);
32503
32504/*
32505** Purge the winShmNodeList list of all entries with winShmNode.nRef==0.
32506**
32507** This is not a VFS shared-memory method; it is a utility function called
32508** by VFS shared-memory methods.
32509*/
32510static void winShmPurge(sqlite3_vfs *pVfs, int deleteFlag){
32511  winShmNode **pp;
32512  winShmNode *p;
32513  BOOL bRc;
32514  assert( winShmMutexHeld() );
32515  pp = &winShmNodeList;
32516  while( (p = *pp)!=0 ){
32517    if( p->nRef==0 ){
32518      int i;
32519      if( p->mutex ) sqlite3_mutex_free(p->mutex);
32520      for(i=0; i<p->nRegion; i++){
32521        bRc = UnmapViewOfFile(p->aRegion[i].pMap);
32522        OSTRACE(("SHM-PURGE pid-%d unmap region=%d %s\n",
32523                 (int)GetCurrentProcessId(), i,
32524                 bRc ? "ok" : "failed"));
32525        bRc = CloseHandle(p->aRegion[i].hMap);
32526        OSTRACE(("SHM-PURGE pid-%d close region=%d %s\n",
32527                 (int)GetCurrentProcessId(), i,
32528                 bRc ? "ok" : "failed"));
32529      }
32530      if( p->hFile.h != INVALID_HANDLE_VALUE ){
32531        SimulateIOErrorBenign(1);
32532        winClose((sqlite3_file *)&p->hFile);
32533        SimulateIOErrorBenign(0);
32534      }
32535      if( deleteFlag ){
32536        SimulateIOErrorBenign(1);
32537        winDelete(pVfs, p->zFilename, 0);
32538        SimulateIOErrorBenign(0);
32539      }
32540      *pp = p->pNext;
32541      sqlite3_free(p->aRegion);
32542      sqlite3_free(p);
32543    }else{
32544      pp = &p->pNext;
32545    }
32546  }
32547}
32548
32549/*
32550** Open the shared-memory area associated with database file pDbFd.
32551**
32552** When opening a new shared-memory file, if no other instances of that
32553** file are currently open, in this process or in other processes, then
32554** the file must be truncated to zero length or have its header cleared.
32555*/
32556static int winOpenSharedMemory(winFile *pDbFd){
32557  struct winShm *p;                  /* The connection to be opened */
32558  struct winShmNode *pShmNode = 0;   /* The underlying mmapped file */
32559  int rc;                            /* Result code */
32560  struct winShmNode *pNew;           /* Newly allocated winShmNode */
32561  int nName;                         /* Size of zName in bytes */
32562
32563  assert( pDbFd->pShm==0 );    /* Not previously opened */
32564
32565  /* Allocate space for the new sqlite3_shm object.  Also speculatively
32566  ** allocate space for a new winShmNode and filename.
32567  */
32568  p = sqlite3_malloc( sizeof(*p) );
32569  if( p==0 ) return SQLITE_NOMEM;
32570  memset(p, 0, sizeof(*p));
32571  nName = sqlite3Strlen30(pDbFd->zPath);
32572  pNew = sqlite3_malloc( sizeof(*pShmNode) + nName + 15 );
32573  if( pNew==0 ){
32574    sqlite3_free(p);
32575    return SQLITE_NOMEM;
32576  }
32577  memset(pNew, 0, sizeof(*pNew));
32578  pNew->zFilename = (char*)&pNew[1];
32579  sqlite3_snprintf(nName+15, pNew->zFilename, "%s-shm", pDbFd->zPath);
32580
32581  /* Look to see if there is an existing winShmNode that can be used.
32582  ** If no matching winShmNode currently exists, create a new one.
32583  */
32584  winShmEnterMutex();
32585  for(pShmNode = winShmNodeList; pShmNode; pShmNode=pShmNode->pNext){
32586    /* TBD need to come up with better match here.  Perhaps
32587    ** use FILE_ID_BOTH_DIR_INFO Structure.
32588    */
32589    if( sqlite3StrICmp(pShmNode->zFilename, pNew->zFilename)==0 ) break;
32590  }
32591  if( pShmNode ){
32592    sqlite3_free(pNew);
32593  }else{
32594    pShmNode = pNew;
32595    pNew = 0;
32596    ((winFile*)(&pShmNode->hFile))->h = INVALID_HANDLE_VALUE;
32597    pShmNode->pNext = winShmNodeList;
32598    winShmNodeList = pShmNode;
32599
32600    pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
32601    if( pShmNode->mutex==0 ){
32602      rc = SQLITE_NOMEM;
32603      goto shm_open_err;
32604    }
32605
32606    rc = winOpen(pDbFd->pVfs,
32607                 pShmNode->zFilename,             /* Name of the file (UTF-8) */
32608                 (sqlite3_file*)&pShmNode->hFile,  /* File handle here */
32609                 SQLITE_OPEN_WAL | SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, /* Mode flags */
32610                 0);
32611    if( SQLITE_OK!=rc ){
32612      rc = SQLITE_CANTOPEN_BKPT;
32613      goto shm_open_err;
32614    }
32615
32616    /* Check to see if another process is holding the dead-man switch.
32617    ** If not, truncate the file to zero length.
32618    */
32619    if( winShmSystemLock(pShmNode, _SHM_WRLCK, WIN_SHM_DMS, 1)==SQLITE_OK ){
32620      rc = winTruncate((sqlite3_file *)&pShmNode->hFile, 0);
32621      if( rc!=SQLITE_OK ){
32622        rc = SQLITE_IOERR_SHMOPEN;
32623      }
32624    }
32625    if( rc==SQLITE_OK ){
32626      winShmSystemLock(pShmNode, _SHM_UNLCK, WIN_SHM_DMS, 1);
32627      rc = winShmSystemLock(pShmNode, _SHM_RDLCK, WIN_SHM_DMS, 1);
32628    }
32629    if( rc ) goto shm_open_err;
32630  }
32631
32632  /* Make the new connection a child of the winShmNode */
32633  p->pShmNode = pShmNode;
32634#ifdef SQLITE_DEBUG
32635  p->id = pShmNode->nextShmId++;
32636#endif
32637  pShmNode->nRef++;
32638  pDbFd->pShm = p;
32639  winShmLeaveMutex();
32640
32641  /* The reference count on pShmNode has already been incremented under
32642  ** the cover of the winShmEnterMutex() mutex and the pointer from the
32643  ** new (struct winShm) object to the pShmNode has been set. All that is
32644  ** left to do is to link the new object into the linked list starting
32645  ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex
32646  ** mutex.
32647  */
32648  sqlite3_mutex_enter(pShmNode->mutex);
32649  p->pNext = pShmNode->pFirst;
32650  pShmNode->pFirst = p;
32651  sqlite3_mutex_leave(pShmNode->mutex);
32652  return SQLITE_OK;
32653
32654  /* Jump here on any error */
32655shm_open_err:
32656  winShmSystemLock(pShmNode, _SHM_UNLCK, WIN_SHM_DMS, 1);
32657  winShmPurge(pDbFd->pVfs, 0);      /* This call frees pShmNode if required */
32658  sqlite3_free(p);
32659  sqlite3_free(pNew);
32660  winShmLeaveMutex();
32661  return rc;
32662}
32663
32664/*
32665** Close a connection to shared-memory.  Delete the underlying
32666** storage if deleteFlag is true.
32667*/
32668static int winShmUnmap(
32669  sqlite3_file *fd,          /* Database holding shared memory */
32670  int deleteFlag             /* Delete after closing if true */
32671){
32672  winFile *pDbFd;       /* Database holding shared-memory */
32673  winShm *p;            /* The connection to be closed */
32674  winShmNode *pShmNode; /* The underlying shared-memory file */
32675  winShm **pp;          /* For looping over sibling connections */
32676
32677  pDbFd = (winFile*)fd;
32678  p = pDbFd->pShm;
32679  if( p==0 ) return SQLITE_OK;
32680  pShmNode = p->pShmNode;
32681
32682  /* Remove connection p from the set of connections associated
32683  ** with pShmNode */
32684  sqlite3_mutex_enter(pShmNode->mutex);
32685  for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
32686  *pp = p->pNext;
32687
32688  /* Free the connection p */
32689  sqlite3_free(p);
32690  pDbFd->pShm = 0;
32691  sqlite3_mutex_leave(pShmNode->mutex);
32692
32693  /* If pShmNode->nRef has reached 0, then close the underlying
32694  ** shared-memory file, too */
32695  winShmEnterMutex();
32696  assert( pShmNode->nRef>0 );
32697  pShmNode->nRef--;
32698  if( pShmNode->nRef==0 ){
32699    winShmPurge(pDbFd->pVfs, deleteFlag);
32700  }
32701  winShmLeaveMutex();
32702
32703  return SQLITE_OK;
32704}
32705
32706/*
32707** Change the lock state for a shared-memory segment.
32708*/
32709static int winShmLock(
32710  sqlite3_file *fd,          /* Database file holding the shared memory */
32711  int ofst,                  /* First lock to acquire or release */
32712  int n,                     /* Number of locks to acquire or release */
32713  int flags                  /* What to do with the lock */
32714){
32715  winFile *pDbFd = (winFile*)fd;        /* Connection holding shared memory */
32716  winShm *p = pDbFd->pShm;              /* The shared memory being locked */
32717  winShm *pX;                           /* For looping over all siblings */
32718  winShmNode *pShmNode = p->pShmNode;
32719  int rc = SQLITE_OK;                   /* Result code */
32720  u16 mask;                             /* Mask of locks to take or release */
32721
32722  assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
32723  assert( n>=1 );
32724  assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
32725       || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
32726       || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
32727       || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
32728  assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
32729
32730  mask = (u16)((1U<<(ofst+n)) - (1U<<ofst));
32731  assert( n>1 || mask==(1<<ofst) );
32732  sqlite3_mutex_enter(pShmNode->mutex);
32733  if( flags & SQLITE_SHM_UNLOCK ){
32734    u16 allMask = 0; /* Mask of locks held by siblings */
32735
32736    /* See if any siblings hold this same lock */
32737    for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
32738      if( pX==p ) continue;
32739      assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
32740      allMask |= pX->sharedMask;
32741    }
32742
32743    /* Unlock the system-level locks */
32744    if( (mask & allMask)==0 ){
32745      rc = winShmSystemLock(pShmNode, _SHM_UNLCK, ofst+WIN_SHM_BASE, n);
32746    }else{
32747      rc = SQLITE_OK;
32748    }
32749
32750    /* Undo the local locks */
32751    if( rc==SQLITE_OK ){
32752      p->exclMask &= ~mask;
32753      p->sharedMask &= ~mask;
32754    }
32755  }else if( flags & SQLITE_SHM_SHARED ){
32756    u16 allShared = 0;  /* Union of locks held by connections other than "p" */
32757
32758    /* Find out which shared locks are already held by sibling connections.
32759    ** If any sibling already holds an exclusive lock, go ahead and return
32760    ** SQLITE_BUSY.
32761    */
32762    for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
32763      if( (pX->exclMask & mask)!=0 ){
32764        rc = SQLITE_BUSY;
32765        break;
32766      }
32767      allShared |= pX->sharedMask;
32768    }
32769
32770    /* Get shared locks at the system level, if necessary */
32771    if( rc==SQLITE_OK ){
32772      if( (allShared & mask)==0 ){
32773        rc = winShmSystemLock(pShmNode, _SHM_RDLCK, ofst+WIN_SHM_BASE, n);
32774      }else{
32775        rc = SQLITE_OK;
32776      }
32777    }
32778
32779    /* Get the local shared locks */
32780    if( rc==SQLITE_OK ){
32781      p->sharedMask |= mask;
32782    }
32783  }else{
32784    /* Make sure no sibling connections hold locks that will block this
32785    ** lock.  If any do, return SQLITE_BUSY right away.
32786    */
32787    for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
32788      if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
32789        rc = SQLITE_BUSY;
32790        break;
32791      }
32792    }
32793
32794    /* Get the exclusive locks at the system level.  Then if successful
32795    ** also mark the local connection as being locked.
32796    */
32797    if( rc==SQLITE_OK ){
32798      rc = winShmSystemLock(pShmNode, _SHM_WRLCK, ofst+WIN_SHM_BASE, n);
32799      if( rc==SQLITE_OK ){
32800        assert( (p->sharedMask & mask)==0 );
32801        p->exclMask |= mask;
32802      }
32803    }
32804  }
32805  sqlite3_mutex_leave(pShmNode->mutex);
32806  OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x %s\n",
32807           p->id, (int)GetCurrentProcessId(), p->sharedMask, p->exclMask,
32808           rc ? "failed" : "ok"));
32809  return rc;
32810}
32811
32812/*
32813** Implement a memory barrier or memory fence on shared memory.
32814**
32815** All loads and stores begun before the barrier must complete before
32816** any load or store begun after the barrier.
32817*/
32818static void winShmBarrier(
32819  sqlite3_file *fd          /* Database holding the shared memory */
32820){
32821  UNUSED_PARAMETER(fd);
32822  /* MemoryBarrier(); // does not work -- do not know why not */
32823  winShmEnterMutex();
32824  winShmLeaveMutex();
32825}
32826
32827/*
32828** This function is called to obtain a pointer to region iRegion of the
32829** shared-memory associated with the database file fd. Shared-memory regions
32830** are numbered starting from zero. Each shared-memory region is szRegion
32831** bytes in size.
32832**
32833** If an error occurs, an error code is returned and *pp is set to NULL.
32834**
32835** Otherwise, if the isWrite parameter is 0 and the requested shared-memory
32836** region has not been allocated (by any client, including one running in a
32837** separate process), then *pp is set to NULL and SQLITE_OK returned. If
32838** isWrite is non-zero and the requested shared-memory region has not yet
32839** been allocated, it is allocated by this function.
32840**
32841** If the shared-memory region has already been allocated or is allocated by
32842** this call as described above, then it is mapped into this processes
32843** address space (if it is not already), *pp is set to point to the mapped
32844** memory and SQLITE_OK returned.
32845*/
32846static int winShmMap(
32847  sqlite3_file *fd,               /* Handle open on database file */
32848  int iRegion,                    /* Region to retrieve */
32849  int szRegion,                   /* Size of regions */
32850  int isWrite,                    /* True to extend file if necessary */
32851  void volatile **pp              /* OUT: Mapped memory */
32852){
32853  winFile *pDbFd = (winFile*)fd;
32854  winShm *p = pDbFd->pShm;
32855  winShmNode *pShmNode;
32856  int rc = SQLITE_OK;
32857
32858  if( !p ){
32859    rc = winOpenSharedMemory(pDbFd);
32860    if( rc!=SQLITE_OK ) return rc;
32861    p = pDbFd->pShm;
32862  }
32863  pShmNode = p->pShmNode;
32864
32865  sqlite3_mutex_enter(pShmNode->mutex);
32866  assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
32867
32868  if( pShmNode->nRegion<=iRegion ){
32869    struct ShmRegion *apNew;           /* New aRegion[] array */
32870    int nByte = (iRegion+1)*szRegion;  /* Minimum required file size */
32871    sqlite3_int64 sz;                  /* Current size of wal-index file */
32872
32873    pShmNode->szRegion = szRegion;
32874
32875    /* The requested region is not mapped into this processes address space.
32876    ** Check to see if it has been allocated (i.e. if the wal-index file is
32877    ** large enough to contain the requested region).
32878    */
32879    rc = winFileSize((sqlite3_file *)&pShmNode->hFile, &sz);
32880    if( rc!=SQLITE_OK ){
32881      rc = SQLITE_IOERR_SHMSIZE;
32882      goto shmpage_out;
32883    }
32884
32885    if( sz<nByte ){
32886      /* The requested memory region does not exist. If isWrite is set to
32887      ** zero, exit early. *pp will be set to NULL and SQLITE_OK returned.
32888      **
32889      ** Alternatively, if isWrite is non-zero, use ftruncate() to allocate
32890      ** the requested memory region.
32891      */
32892      if( !isWrite ) goto shmpage_out;
32893      rc = winTruncate((sqlite3_file *)&pShmNode->hFile, nByte);
32894      if( rc!=SQLITE_OK ){
32895        rc = SQLITE_IOERR_SHMSIZE;
32896        goto shmpage_out;
32897      }
32898    }
32899
32900    /* Map the requested memory region into this processes address space. */
32901    apNew = (struct ShmRegion *)sqlite3_realloc(
32902        pShmNode->aRegion, (iRegion+1)*sizeof(apNew[0])
32903    );
32904    if( !apNew ){
32905      rc = SQLITE_IOERR_NOMEM;
32906      goto shmpage_out;
32907    }
32908    pShmNode->aRegion = apNew;
32909
32910    while( pShmNode->nRegion<=iRegion ){
32911      HANDLE hMap;                /* file-mapping handle */
32912      void *pMap = 0;             /* Mapped memory region */
32913
32914      hMap = CreateFileMapping(pShmNode->hFile.h,
32915          NULL, PAGE_READWRITE, 0, nByte, NULL
32916      );
32917      OSTRACE(("SHM-MAP pid-%d create region=%d nbyte=%d %s\n",
32918               (int)GetCurrentProcessId(), pShmNode->nRegion, nByte,
32919               hMap ? "ok" : "failed"));
32920      if( hMap ){
32921        int iOffset = pShmNode->nRegion*szRegion;
32922        int iOffsetShift = iOffset % winSysInfo.dwAllocationGranularity;
32923        pMap = MapViewOfFile(hMap, FILE_MAP_WRITE | FILE_MAP_READ,
32924            0, iOffset - iOffsetShift, szRegion + iOffsetShift
32925        );
32926        OSTRACE(("SHM-MAP pid-%d map region=%d offset=%d size=%d %s\n",
32927                 (int)GetCurrentProcessId(), pShmNode->nRegion, iOffset, szRegion,
32928                 pMap ? "ok" : "failed"));
32929      }
32930      if( !pMap ){
32931        pShmNode->lastErrno = GetLastError();
32932        rc = SQLITE_IOERR;
32933        if( hMap ) CloseHandle(hMap);
32934        goto shmpage_out;
32935      }
32936
32937      pShmNode->aRegion[pShmNode->nRegion].pMap = pMap;
32938      pShmNode->aRegion[pShmNode->nRegion].hMap = hMap;
32939      pShmNode->nRegion++;
32940    }
32941  }
32942
32943shmpage_out:
32944  if( pShmNode->nRegion>iRegion ){
32945    int iOffset = iRegion*szRegion;
32946    int iOffsetShift = iOffset % winSysInfo.dwAllocationGranularity;
32947    char *p = (char *)pShmNode->aRegion[iRegion].pMap;
32948    *pp = (void *)&p[iOffsetShift];
32949  }else{
32950    *pp = 0;
32951  }
32952  sqlite3_mutex_leave(pShmNode->mutex);
32953  return rc;
32954}
32955
32956#else
32957# define winShmMap     0
32958# define winShmLock    0
32959# define winShmBarrier 0
32960# define winShmUnmap   0
32961#endif /* #ifndef SQLITE_OMIT_WAL */
32962
32963/*
32964** Here ends the implementation of all sqlite3_file methods.
32965**
32966********************** End sqlite3_file Methods *******************************
32967******************************************************************************/
32968
32969/*
32970** This vector defines all the methods that can operate on an
32971** sqlite3_file for win32.
32972*/
32973static const sqlite3_io_methods winIoMethod = {
32974  2,                              /* iVersion */
32975  winClose,                       /* xClose */
32976  winRead,                        /* xRead */
32977  winWrite,                       /* xWrite */
32978  winTruncate,                    /* xTruncate */
32979  winSync,                        /* xSync */
32980  winFileSize,                    /* xFileSize */
32981  winLock,                        /* xLock */
32982  winUnlock,                      /* xUnlock */
32983  winCheckReservedLock,           /* xCheckReservedLock */
32984  winFileControl,                 /* xFileControl */
32985  winSectorSize,                  /* xSectorSize */
32986  winDeviceCharacteristics,       /* xDeviceCharacteristics */
32987  winShmMap,                      /* xShmMap */
32988  winShmLock,                     /* xShmLock */
32989  winShmBarrier,                  /* xShmBarrier */
32990  winShmUnmap                     /* xShmUnmap */
32991};
32992
32993/****************************************************************************
32994**************************** sqlite3_vfs methods ****************************
32995**
32996** This division contains the implementation of methods on the
32997** sqlite3_vfs object.
32998*/
32999
33000/*
33001** Convert a UTF-8 filename into whatever form the underlying
33002** operating system wants filenames in.  Space to hold the result
33003** is obtained from malloc and must be freed by the calling
33004** function.
33005*/
33006static void *convertUtf8Filename(const char *zFilename){
33007  void *zConverted = 0;
33008  if( isNT() ){
33009    zConverted = utf8ToUnicode(zFilename);
33010/* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
33011*/
33012#if SQLITE_OS_WINCE==0
33013  }else{
33014    zConverted = utf8ToMbcs(zFilename);
33015#endif
33016  }
33017  /* caller will handle out of memory */
33018  return zConverted;
33019}
33020
33021/*
33022** Create a temporary file name in zBuf.  zBuf must be big enough to
33023** hold at pVfs->mxPathname characters.
33024*/
33025static int getTempname(int nBuf, char *zBuf){
33026  static char zChars[] =
33027    "abcdefghijklmnopqrstuvwxyz"
33028    "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
33029    "0123456789";
33030  size_t i, j;
33031  char zTempPath[MAX_PATH+1];
33032
33033  /* It's odd to simulate an io-error here, but really this is just
33034  ** using the io-error infrastructure to test that SQLite handles this
33035  ** function failing.
33036  */
33037  SimulateIOError( return SQLITE_IOERR );
33038
33039  if( sqlite3_temp_directory ){
33040    sqlite3_snprintf(MAX_PATH-30, zTempPath, "%s", sqlite3_temp_directory);
33041  }else if( isNT() ){
33042    char *zMulti;
33043    WCHAR zWidePath[MAX_PATH];
33044    GetTempPathW(MAX_PATH-30, zWidePath);
33045    zMulti = unicodeToUtf8(zWidePath);
33046    if( zMulti ){
33047      sqlite3_snprintf(MAX_PATH-30, zTempPath, "%s", zMulti);
33048      free(zMulti);
33049    }else{
33050      return SQLITE_NOMEM;
33051    }
33052/* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
33053** Since the ASCII version of these Windows API do not exist for WINCE,
33054** it's important to not reference them for WINCE builds.
33055*/
33056#if SQLITE_OS_WINCE==0
33057  }else{
33058    char *zUtf8;
33059    char zMbcsPath[MAX_PATH];
33060    GetTempPathA(MAX_PATH-30, zMbcsPath);
33061    zUtf8 = sqlite3_win32_mbcs_to_utf8(zMbcsPath);
33062    if( zUtf8 ){
33063      sqlite3_snprintf(MAX_PATH-30, zTempPath, "%s", zUtf8);
33064      free(zUtf8);
33065    }else{
33066      return SQLITE_NOMEM;
33067    }
33068#endif
33069  }
33070
33071  /* Check that the output buffer is large enough for the temporary file
33072  ** name. If it is not, return SQLITE_ERROR.
33073  */
33074  if( (sqlite3Strlen30(zTempPath) + sqlite3Strlen30(SQLITE_TEMP_FILE_PREFIX) + 17) >= nBuf ){
33075    return SQLITE_ERROR;
33076  }
33077
33078  for(i=sqlite3Strlen30(zTempPath); i>0 && zTempPath[i-1]=='\\'; i--){}
33079  zTempPath[i] = 0;
33080
33081  sqlite3_snprintf(nBuf-17, zBuf,
33082                   "%s\\"SQLITE_TEMP_FILE_PREFIX, zTempPath);
33083  j = sqlite3Strlen30(zBuf);
33084  sqlite3_randomness(15, &zBuf[j]);
33085  for(i=0; i<15; i++, j++){
33086    zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
33087  }
33088  zBuf[j] = 0;
33089
33090  OSTRACE(("TEMP FILENAME: %s\n", zBuf));
33091  return SQLITE_OK;
33092}
33093
33094/*
33095** The return value of getLastErrorMsg
33096** is zero if the error message fits in the buffer, or non-zero
33097** otherwise (if the message was truncated).
33098*/
33099static int getLastErrorMsg(int nBuf, char *zBuf){
33100  /* FormatMessage returns 0 on failure.  Otherwise it
33101  ** returns the number of TCHARs written to the output
33102  ** buffer, excluding the terminating null char.
33103  */
33104  DWORD error = GetLastError();
33105  DWORD dwLen = 0;
33106  char *zOut = 0;
33107
33108  if( isNT() ){
33109    WCHAR *zTempWide = NULL;
33110    dwLen = FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
33111                           NULL,
33112                           error,
33113                           0,
33114                           (LPWSTR) &zTempWide,
33115                           0,
33116                           0);
33117    if( dwLen > 0 ){
33118      /* allocate a buffer and convert to UTF8 */
33119      zOut = unicodeToUtf8(zTempWide);
33120      /* free the system buffer allocated by FormatMessage */
33121      LocalFree(zTempWide);
33122    }
33123/* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
33124** Since the ASCII version of these Windows API do not exist for WINCE,
33125** it's important to not reference them for WINCE builds.
33126*/
33127#if SQLITE_OS_WINCE==0
33128  }else{
33129    char *zTemp = NULL;
33130    dwLen = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
33131                           NULL,
33132                           error,
33133                           0,
33134                           (LPSTR) &zTemp,
33135                           0,
33136                           0);
33137    if( dwLen > 0 ){
33138      /* allocate a buffer and convert to UTF8 */
33139      zOut = sqlite3_win32_mbcs_to_utf8(zTemp);
33140      /* free the system buffer allocated by FormatMessage */
33141      LocalFree(zTemp);
33142    }
33143#endif
33144  }
33145  if( 0 == dwLen ){
33146    sqlite3_snprintf(nBuf, zBuf, "OsError 0x%x (%u)", error, error);
33147  }else{
33148    /* copy a maximum of nBuf chars to output buffer */
33149    sqlite3_snprintf(nBuf, zBuf, "%s", zOut);
33150    /* free the UTF8 buffer */
33151    free(zOut);
33152  }
33153  return 0;
33154}
33155
33156/*
33157** Open a file.
33158*/
33159static int winOpen(
33160  sqlite3_vfs *pVfs,        /* Not used */
33161  const char *zName,        /* Name of the file (UTF-8) */
33162  sqlite3_file *id,         /* Write the SQLite file handle here */
33163  int flags,                /* Open mode flags */
33164  int *pOutFlags            /* Status return flags */
33165){
33166  HANDLE h;
33167  DWORD dwDesiredAccess;
33168  DWORD dwShareMode;
33169  DWORD dwCreationDisposition;
33170  DWORD dwFlagsAndAttributes = 0;
33171#if SQLITE_OS_WINCE
33172  int isTemp = 0;
33173#endif
33174  winFile *pFile = (winFile*)id;
33175  void *zConverted;              /* Filename in OS encoding */
33176  const char *zUtf8Name = zName; /* Filename in UTF-8 encoding */
33177
33178  /* If argument zPath is a NULL pointer, this function is required to open
33179  ** a temporary file. Use this buffer to store the file name in.
33180  */
33181  char zTmpname[MAX_PATH+1];     /* Buffer used to create temp filename */
33182
33183  int rc = SQLITE_OK;            /* Function Return Code */
33184#if !defined(NDEBUG) || SQLITE_OS_WINCE
33185  int eType = flags&0xFFFFFF00;  /* Type of file to open */
33186#endif
33187
33188  int isExclusive  = (flags & SQLITE_OPEN_EXCLUSIVE);
33189  int isDelete     = (flags & SQLITE_OPEN_DELETEONCLOSE);
33190  int isCreate     = (flags & SQLITE_OPEN_CREATE);
33191#ifndef NDEBUG
33192  int isReadonly   = (flags & SQLITE_OPEN_READONLY);
33193#endif
33194  int isReadWrite  = (flags & SQLITE_OPEN_READWRITE);
33195
33196#ifndef NDEBUG
33197  int isOpenJournal = (isCreate && (
33198        eType==SQLITE_OPEN_MASTER_JOURNAL
33199     || eType==SQLITE_OPEN_MAIN_JOURNAL
33200     || eType==SQLITE_OPEN_WAL
33201  ));
33202#endif
33203
33204  /* Check the following statements are true:
33205  **
33206  **   (a) Exactly one of the READWRITE and READONLY flags must be set, and
33207  **   (b) if CREATE is set, then READWRITE must also be set, and
33208  **   (c) if EXCLUSIVE is set, then CREATE must also be set.
33209  **   (d) if DELETEONCLOSE is set, then CREATE must also be set.
33210  */
33211  assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
33212  assert(isCreate==0 || isReadWrite);
33213  assert(isExclusive==0 || isCreate);
33214  assert(isDelete==0 || isCreate);
33215
33216  /* The main DB, main journal, WAL file and master journal are never
33217  ** automatically deleted. Nor are they ever temporary files.  */
33218  assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
33219  assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
33220  assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
33221  assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
33222
33223  /* Assert that the upper layer has set one of the "file-type" flags. */
33224  assert( eType==SQLITE_OPEN_MAIN_DB      || eType==SQLITE_OPEN_TEMP_DB
33225       || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
33226       || eType==SQLITE_OPEN_SUBJOURNAL   || eType==SQLITE_OPEN_MASTER_JOURNAL
33227       || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
33228  );
33229
33230  assert( id!=0 );
33231  UNUSED_PARAMETER(pVfs);
33232
33233  pFile->h = INVALID_HANDLE_VALUE;
33234
33235  /* If the second argument to this function is NULL, generate a
33236  ** temporary file name to use
33237  */
33238  if( !zUtf8Name ){
33239    assert(isDelete && !isOpenJournal);
33240    rc = getTempname(MAX_PATH+1, zTmpname);
33241    if( rc!=SQLITE_OK ){
33242      return rc;
33243    }
33244    zUtf8Name = zTmpname;
33245  }
33246
33247  /* Convert the filename to the system encoding. */
33248  zConverted = convertUtf8Filename(zUtf8Name);
33249  if( zConverted==0 ){
33250    return SQLITE_NOMEM;
33251  }
33252
33253  if( isReadWrite ){
33254    dwDesiredAccess = GENERIC_READ | GENERIC_WRITE;
33255  }else{
33256    dwDesiredAccess = GENERIC_READ;
33257  }
33258
33259  /* SQLITE_OPEN_EXCLUSIVE is used to make sure that a new file is
33260  ** created. SQLite doesn't use it to indicate "exclusive access"
33261  ** as it is usually understood.
33262  */
33263  if( isExclusive ){
33264    /* Creates a new file, only if it does not already exist. */
33265    /* If the file exists, it fails. */
33266    dwCreationDisposition = CREATE_NEW;
33267  }else if( isCreate ){
33268    /* Open existing file, or create if it doesn't exist */
33269    dwCreationDisposition = OPEN_ALWAYS;
33270  }else{
33271    /* Opens a file, only if it exists. */
33272    dwCreationDisposition = OPEN_EXISTING;
33273  }
33274
33275  dwShareMode = FILE_SHARE_READ | FILE_SHARE_WRITE;
33276
33277  if( isDelete ){
33278#if SQLITE_OS_WINCE
33279    dwFlagsAndAttributes = FILE_ATTRIBUTE_HIDDEN;
33280    isTemp = 1;
33281#else
33282    dwFlagsAndAttributes = FILE_ATTRIBUTE_TEMPORARY
33283                               | FILE_ATTRIBUTE_HIDDEN
33284                               | FILE_FLAG_DELETE_ON_CLOSE;
33285#endif
33286  }else{
33287    dwFlagsAndAttributes = FILE_ATTRIBUTE_NORMAL;
33288  }
33289  /* Reports from the internet are that performance is always
33290  ** better if FILE_FLAG_RANDOM_ACCESS is used.  Ticket #2699. */
33291#if SQLITE_OS_WINCE
33292  dwFlagsAndAttributes |= FILE_FLAG_RANDOM_ACCESS;
33293#endif
33294
33295  if( isNT() ){
33296    h = CreateFileW((WCHAR*)zConverted,
33297       dwDesiredAccess,
33298       dwShareMode,
33299       NULL,
33300       dwCreationDisposition,
33301       dwFlagsAndAttributes,
33302       NULL
33303    );
33304/* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
33305** Since the ASCII version of these Windows API do not exist for WINCE,
33306** it's important to not reference them for WINCE builds.
33307*/
33308#if SQLITE_OS_WINCE==0
33309  }else{
33310    h = CreateFileA((char*)zConverted,
33311       dwDesiredAccess,
33312       dwShareMode,
33313       NULL,
33314       dwCreationDisposition,
33315       dwFlagsAndAttributes,
33316       NULL
33317    );
33318#endif
33319  }
33320
33321  OSTRACE(("OPEN %d %s 0x%lx %s\n",
33322           h, zName, dwDesiredAccess,
33323           h==INVALID_HANDLE_VALUE ? "failed" : "ok"));
33324
33325  if( h==INVALID_HANDLE_VALUE ){
33326    pFile->lastErrno = GetLastError();
33327    free(zConverted);
33328    if( isReadWrite ){
33329      return winOpen(pVfs, zName, id,
33330             ((flags|SQLITE_OPEN_READONLY)&~(SQLITE_OPEN_CREATE|SQLITE_OPEN_READWRITE)), pOutFlags);
33331    }else{
33332      return SQLITE_CANTOPEN_BKPT;
33333    }
33334  }
33335
33336  if( pOutFlags ){
33337    if( isReadWrite ){
33338      *pOutFlags = SQLITE_OPEN_READWRITE;
33339    }else{
33340      *pOutFlags = SQLITE_OPEN_READONLY;
33341    }
33342  }
33343
33344  memset(pFile, 0, sizeof(*pFile));
33345  pFile->pMethod = &winIoMethod;
33346  pFile->h = h;
33347  pFile->lastErrno = NO_ERROR;
33348  pFile->pVfs = pVfs;
33349  pFile->pShm = 0;
33350  pFile->zPath = zName;
33351  pFile->sectorSize = getSectorSize(pVfs, zUtf8Name);
33352
33353#if SQLITE_OS_WINCE
33354  if( isReadWrite && eType==SQLITE_OPEN_MAIN_DB
33355       && !winceCreateLock(zName, pFile)
33356  ){
33357    CloseHandle(h);
33358    free(zConverted);
33359    return SQLITE_CANTOPEN_BKPT;
33360  }
33361  if( isTemp ){
33362    pFile->zDeleteOnClose = zConverted;
33363  }else
33364#endif
33365  {
33366    free(zConverted);
33367  }
33368
33369  OpenCounter(+1);
33370  return rc;
33371}
33372
33373/*
33374** Delete the named file.
33375**
33376** Note that windows does not allow a file to be deleted if some other
33377** process has it open.  Sometimes a virus scanner or indexing program
33378** will open a journal file shortly after it is created in order to do
33379** whatever it does.  While this other process is holding the
33380** file open, we will be unable to delete it.  To work around this
33381** problem, we delay 100 milliseconds and try to delete again.  Up
33382** to MX_DELETION_ATTEMPTs deletion attempts are run before giving
33383** up and returning an error.
33384*/
33385#define MX_DELETION_ATTEMPTS 5
33386static int winDelete(
33387  sqlite3_vfs *pVfs,          /* Not used on win32 */
33388  const char *zFilename,      /* Name of file to delete */
33389  int syncDir                 /* Not used on win32 */
33390){
33391  int cnt = 0;
33392  DWORD rc;
33393  DWORD error = 0;
33394  void *zConverted;
33395  UNUSED_PARAMETER(pVfs);
33396  UNUSED_PARAMETER(syncDir);
33397
33398  SimulateIOError(return SQLITE_IOERR_DELETE);
33399  zConverted = convertUtf8Filename(zFilename);
33400  if( zConverted==0 ){
33401    return SQLITE_NOMEM;
33402  }
33403  if( isNT() ){
33404    do{
33405      DeleteFileW(zConverted);
33406    }while(   (   ((rc = GetFileAttributesW(zConverted)) != INVALID_FILE_ATTRIBUTES)
33407               || ((error = GetLastError()) == ERROR_ACCESS_DENIED))
33408           && (++cnt < MX_DELETION_ATTEMPTS)
33409           && (Sleep(100), 1) );
33410/* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
33411** Since the ASCII version of these Windows API do not exist for WINCE,
33412** it's important to not reference them for WINCE builds.
33413*/
33414#if SQLITE_OS_WINCE==0
33415  }else{
33416    do{
33417      DeleteFileA(zConverted);
33418    }while(   (   ((rc = GetFileAttributesA(zConverted)) != INVALID_FILE_ATTRIBUTES)
33419               || ((error = GetLastError()) == ERROR_ACCESS_DENIED))
33420           && (++cnt < MX_DELETION_ATTEMPTS)
33421           && (Sleep(100), 1) );
33422#endif
33423  }
33424  free(zConverted);
33425  OSTRACE(("DELETE \"%s\" %s\n", zFilename,
33426       ( (rc==INVALID_FILE_ATTRIBUTES) && (error==ERROR_FILE_NOT_FOUND)) ?
33427         "ok" : "failed" ));
33428
33429  return (   (rc == INVALID_FILE_ATTRIBUTES)
33430          && (error == ERROR_FILE_NOT_FOUND)) ? SQLITE_OK : SQLITE_IOERR_DELETE;
33431}
33432
33433/*
33434** Check the existance and status of a file.
33435*/
33436static int winAccess(
33437  sqlite3_vfs *pVfs,         /* Not used on win32 */
33438  const char *zFilename,     /* Name of file to check */
33439  int flags,                 /* Type of test to make on this file */
33440  int *pResOut               /* OUT: Result */
33441){
33442  DWORD attr;
33443  int rc = 0;
33444  void *zConverted;
33445  UNUSED_PARAMETER(pVfs);
33446
33447  SimulateIOError( return SQLITE_IOERR_ACCESS; );
33448  zConverted = convertUtf8Filename(zFilename);
33449  if( zConverted==0 ){
33450    return SQLITE_NOMEM;
33451  }
33452  if( isNT() ){
33453    WIN32_FILE_ATTRIBUTE_DATA sAttrData;
33454    memset(&sAttrData, 0, sizeof(sAttrData));
33455    if( GetFileAttributesExW((WCHAR*)zConverted,
33456                             GetFileExInfoStandard,
33457                             &sAttrData) ){
33458      /* For an SQLITE_ACCESS_EXISTS query, treat a zero-length file
33459      ** as if it does not exist.
33460      */
33461      if(    flags==SQLITE_ACCESS_EXISTS
33462          && sAttrData.nFileSizeHigh==0
33463          && sAttrData.nFileSizeLow==0 ){
33464        attr = INVALID_FILE_ATTRIBUTES;
33465      }else{
33466        attr = sAttrData.dwFileAttributes;
33467      }
33468    }else{
33469      if( GetLastError()!=ERROR_FILE_NOT_FOUND ){
33470        free(zConverted);
33471        return SQLITE_IOERR_ACCESS;
33472      }else{
33473        attr = INVALID_FILE_ATTRIBUTES;
33474      }
33475    }
33476/* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
33477** Since the ASCII version of these Windows API do not exist for WINCE,
33478** it's important to not reference them for WINCE builds.
33479*/
33480#if SQLITE_OS_WINCE==0
33481  }else{
33482    attr = GetFileAttributesA((char*)zConverted);
33483#endif
33484  }
33485  free(zConverted);
33486  switch( flags ){
33487    case SQLITE_ACCESS_READ:
33488    case SQLITE_ACCESS_EXISTS:
33489      rc = attr!=INVALID_FILE_ATTRIBUTES;
33490      break;
33491    case SQLITE_ACCESS_READWRITE:
33492      rc = (attr & FILE_ATTRIBUTE_READONLY)==0;
33493      break;
33494    default:
33495      assert(!"Invalid flags argument");
33496  }
33497  *pResOut = rc;
33498  return SQLITE_OK;
33499}
33500
33501
33502/*
33503** Turn a relative pathname into a full pathname.  Write the full
33504** pathname into zOut[].  zOut[] will be at least pVfs->mxPathname
33505** bytes in size.
33506*/
33507static int winFullPathname(
33508  sqlite3_vfs *pVfs,            /* Pointer to vfs object */
33509  const char *zRelative,        /* Possibly relative input path */
33510  int nFull,                    /* Size of output buffer in bytes */
33511  char *zFull                   /* Output buffer */
33512){
33513
33514#if defined(__CYGWIN__)
33515  SimulateIOError( return SQLITE_ERROR );
33516  UNUSED_PARAMETER(nFull);
33517  cygwin_conv_to_full_win32_path(zRelative, zFull);
33518  return SQLITE_OK;
33519#endif
33520
33521#if SQLITE_OS_WINCE
33522  SimulateIOError( return SQLITE_ERROR );
33523  UNUSED_PARAMETER(nFull);
33524  /* WinCE has no concept of a relative pathname, or so I am told. */
33525  sqlite3_snprintf(pVfs->mxPathname, zFull, "%s", zRelative);
33526  return SQLITE_OK;
33527#endif
33528
33529#if !SQLITE_OS_WINCE && !defined(__CYGWIN__)
33530  int nByte;
33531  void *zConverted;
33532  char *zOut;
33533
33534  /* It's odd to simulate an io-error here, but really this is just
33535  ** using the io-error infrastructure to test that SQLite handles this
33536  ** function failing. This function could fail if, for example, the
33537  ** current working directory has been unlinked.
33538  */
33539  SimulateIOError( return SQLITE_ERROR );
33540  UNUSED_PARAMETER(nFull);
33541  zConverted = convertUtf8Filename(zRelative);
33542  if( isNT() ){
33543    WCHAR *zTemp;
33544    nByte = GetFullPathNameW((WCHAR*)zConverted, 0, 0, 0) + 3;
33545    zTemp = malloc( nByte*sizeof(zTemp[0]) );
33546    if( zTemp==0 ){
33547      free(zConverted);
33548      return SQLITE_NOMEM;
33549    }
33550    GetFullPathNameW((WCHAR*)zConverted, nByte, zTemp, 0);
33551    free(zConverted);
33552    zOut = unicodeToUtf8(zTemp);
33553    free(zTemp);
33554/* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
33555** Since the ASCII version of these Windows API do not exist for WINCE,
33556** it's important to not reference them for WINCE builds.
33557*/
33558#if SQLITE_OS_WINCE==0
33559  }else{
33560    char *zTemp;
33561    nByte = GetFullPathNameA((char*)zConverted, 0, 0, 0) + 3;
33562    zTemp = malloc( nByte*sizeof(zTemp[0]) );
33563    if( zTemp==0 ){
33564      free(zConverted);
33565      return SQLITE_NOMEM;
33566    }
33567    GetFullPathNameA((char*)zConverted, nByte, zTemp, 0);
33568    free(zConverted);
33569    zOut = sqlite3_win32_mbcs_to_utf8(zTemp);
33570    free(zTemp);
33571#endif
33572  }
33573  if( zOut ){
33574    sqlite3_snprintf(pVfs->mxPathname, zFull, "%s", zOut);
33575    free(zOut);
33576    return SQLITE_OK;
33577  }else{
33578    return SQLITE_NOMEM;
33579  }
33580#endif
33581}
33582
33583/*
33584** Get the sector size of the device used to store
33585** file.
33586*/
33587static int getSectorSize(
33588    sqlite3_vfs *pVfs,
33589    const char *zRelative     /* UTF-8 file name */
33590){
33591  DWORD bytesPerSector = SQLITE_DEFAULT_SECTOR_SIZE;
33592  /* GetDiskFreeSpace is not supported under WINCE */
33593#if SQLITE_OS_WINCE
33594  UNUSED_PARAMETER(pVfs);
33595  UNUSED_PARAMETER(zRelative);
33596#else
33597  char zFullpath[MAX_PATH+1];
33598  int rc;
33599  DWORD dwRet = 0;
33600  DWORD dwDummy;
33601
33602  /*
33603  ** We need to get the full path name of the file
33604  ** to get the drive letter to look up the sector
33605  ** size.
33606  */
33607  SimulateIOErrorBenign(1);
33608  rc = winFullPathname(pVfs, zRelative, MAX_PATH, zFullpath);
33609  SimulateIOErrorBenign(0);
33610  if( rc == SQLITE_OK )
33611  {
33612    void *zConverted = convertUtf8Filename(zFullpath);
33613    if( zConverted ){
33614      if( isNT() ){
33615        /* trim path to just drive reference */
33616        WCHAR *p = zConverted;
33617        for(;*p;p++){
33618          if( *p == '\\' ){
33619            *p = '\0';
33620            break;
33621          }
33622        }
33623        dwRet = GetDiskFreeSpaceW((WCHAR*)zConverted,
33624                                  &dwDummy,
33625                                  &bytesPerSector,
33626                                  &dwDummy,
33627                                  &dwDummy);
33628      }else{
33629        /* trim path to just drive reference */
33630        char *p = (char *)zConverted;
33631        for(;*p;p++){
33632          if( *p == '\\' ){
33633            *p = '\0';
33634            break;
33635          }
33636        }
33637        dwRet = GetDiskFreeSpaceA((char*)zConverted,
33638                                  &dwDummy,
33639                                  &bytesPerSector,
33640                                  &dwDummy,
33641                                  &dwDummy);
33642      }
33643      free(zConverted);
33644    }
33645    if( !dwRet ){
33646      bytesPerSector = SQLITE_DEFAULT_SECTOR_SIZE;
33647    }
33648  }
33649#endif
33650  return (int) bytesPerSector;
33651}
33652
33653#ifndef SQLITE_OMIT_LOAD_EXTENSION
33654/*
33655** Interfaces for opening a shared library, finding entry points
33656** within the shared library, and closing the shared library.
33657*/
33658/*
33659** Interfaces for opening a shared library, finding entry points
33660** within the shared library, and closing the shared library.
33661*/
33662static void *winDlOpen(sqlite3_vfs *pVfs, const char *zFilename){
33663  HANDLE h;
33664  void *zConverted = convertUtf8Filename(zFilename);
33665  UNUSED_PARAMETER(pVfs);
33666  if( zConverted==0 ){
33667    return 0;
33668  }
33669  if( isNT() ){
33670    h = LoadLibraryW((WCHAR*)zConverted);
33671/* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
33672** Since the ASCII version of these Windows API do not exist for WINCE,
33673** it's important to not reference them for WINCE builds.
33674*/
33675#if SQLITE_OS_WINCE==0
33676  }else{
33677    h = LoadLibraryA((char*)zConverted);
33678#endif
33679  }
33680  free(zConverted);
33681  return (void*)h;
33682}
33683static void winDlError(sqlite3_vfs *pVfs, int nBuf, char *zBufOut){
33684  UNUSED_PARAMETER(pVfs);
33685  getLastErrorMsg(nBuf, zBufOut);
33686}
33687void (*winDlSym(sqlite3_vfs *pVfs, void *pHandle, const char *zSymbol))(void){
33688  UNUSED_PARAMETER(pVfs);
33689#if SQLITE_OS_WINCE
33690  /* The GetProcAddressA() routine is only available on wince. */
33691  return (void(*)(void))GetProcAddressA((HANDLE)pHandle, zSymbol);
33692#else
33693  /* All other windows platforms expect GetProcAddress() to take
33694  ** an Ansi string regardless of the _UNICODE setting */
33695  return (void(*)(void))GetProcAddress((HANDLE)pHandle, zSymbol);
33696#endif
33697}
33698void winDlClose(sqlite3_vfs *pVfs, void *pHandle){
33699  UNUSED_PARAMETER(pVfs);
33700  FreeLibrary((HANDLE)pHandle);
33701}
33702#else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
33703  #define winDlOpen  0
33704  #define winDlError 0
33705  #define winDlSym   0
33706  #define winDlClose 0
33707#endif
33708
33709
33710/*
33711** Write up to nBuf bytes of randomness into zBuf.
33712*/
33713static int winRandomness(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
33714  int n = 0;
33715  UNUSED_PARAMETER(pVfs);
33716#if defined(SQLITE_TEST)
33717  n = nBuf;
33718  memset(zBuf, 0, nBuf);
33719#else
33720  if( sizeof(SYSTEMTIME)<=nBuf-n ){
33721    SYSTEMTIME x;
33722    GetSystemTime(&x);
33723    memcpy(&zBuf[n], &x, sizeof(x));
33724    n += sizeof(x);
33725  }
33726  if( sizeof(DWORD)<=nBuf-n ){
33727    DWORD pid = GetCurrentProcessId();
33728    memcpy(&zBuf[n], &pid, sizeof(pid));
33729    n += sizeof(pid);
33730  }
33731  if( sizeof(DWORD)<=nBuf-n ){
33732    DWORD cnt = GetTickCount();
33733    memcpy(&zBuf[n], &cnt, sizeof(cnt));
33734    n += sizeof(cnt);
33735  }
33736  if( sizeof(LARGE_INTEGER)<=nBuf-n ){
33737    LARGE_INTEGER i;
33738    QueryPerformanceCounter(&i);
33739    memcpy(&zBuf[n], &i, sizeof(i));
33740    n += sizeof(i);
33741  }
33742#endif
33743  return n;
33744}
33745
33746
33747/*
33748** Sleep for a little while.  Return the amount of time slept.
33749*/
33750static int winSleep(sqlite3_vfs *pVfs, int microsec){
33751  Sleep((microsec+999)/1000);
33752  UNUSED_PARAMETER(pVfs);
33753  return ((microsec+999)/1000)*1000;
33754}
33755
33756/*
33757** The following variable, if set to a non-zero value, is interpreted as
33758** the number of seconds since 1970 and is used to set the result of
33759** sqlite3OsCurrentTime() during testing.
33760*/
33761#ifdef SQLITE_TEST
33762SQLITE_API int sqlite3_current_time = 0;  /* Fake system time in seconds since 1970. */
33763#endif
33764
33765/*
33766** Find the current time (in Universal Coordinated Time).  Write into *piNow
33767** the current time and date as a Julian Day number times 86_400_000.  In
33768** other words, write into *piNow the number of milliseconds since the Julian
33769** epoch of noon in Greenwich on November 24, 4714 B.C according to the
33770** proleptic Gregorian calendar.
33771**
33772** On success, return 0.  Return 1 if the time and date cannot be found.
33773*/
33774static int winCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *piNow){
33775  /* FILETIME structure is a 64-bit value representing the number of
33776     100-nanosecond intervals since January 1, 1601 (= JD 2305813.5).
33777  */
33778  FILETIME ft;
33779  static const sqlite3_int64 winFiletimeEpoch = 23058135*(sqlite3_int64)8640000;
33780#ifdef SQLITE_TEST
33781  static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
33782#endif
33783  /* 2^32 - to avoid use of LL and warnings in gcc */
33784  static const sqlite3_int64 max32BitValue =
33785      (sqlite3_int64)2000000000 + (sqlite3_int64)2000000000 + (sqlite3_int64)294967296;
33786
33787#if SQLITE_OS_WINCE
33788  SYSTEMTIME time;
33789  GetSystemTime(&time);
33790  /* if SystemTimeToFileTime() fails, it returns zero. */
33791  if (!SystemTimeToFileTime(&time,&ft)){
33792    return 1;
33793  }
33794#else
33795  GetSystemTimeAsFileTime( &ft );
33796#endif
33797
33798  *piNow = winFiletimeEpoch +
33799            ((((sqlite3_int64)ft.dwHighDateTime)*max32BitValue) +
33800               (sqlite3_int64)ft.dwLowDateTime)/(sqlite3_int64)10000;
33801
33802#ifdef SQLITE_TEST
33803  if( sqlite3_current_time ){
33804    *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
33805  }
33806#endif
33807  UNUSED_PARAMETER(pVfs);
33808  return 0;
33809}
33810
33811/*
33812** Find the current time (in Universal Coordinated Time).  Write the
33813** current time and date as a Julian Day number into *prNow and
33814** return 0.  Return 1 if the time and date cannot be found.
33815*/
33816int winCurrentTime(sqlite3_vfs *pVfs, double *prNow){
33817  int rc;
33818  sqlite3_int64 i;
33819  rc = winCurrentTimeInt64(pVfs, &i);
33820  if( !rc ){
33821    *prNow = i/86400000.0;
33822  }
33823  return rc;
33824}
33825
33826/*
33827** The idea is that this function works like a combination of
33828** GetLastError() and FormatMessage() on windows (or errno and
33829** strerror_r() on unix). After an error is returned by an OS
33830** function, SQLite calls this function with zBuf pointing to
33831** a buffer of nBuf bytes. The OS layer should populate the
33832** buffer with a nul-terminated UTF-8 encoded error message
33833** describing the last IO error to have occurred within the calling
33834** thread.
33835**
33836** If the error message is too large for the supplied buffer,
33837** it should be truncated. The return value of xGetLastError
33838** is zero if the error message fits in the buffer, or non-zero
33839** otherwise (if the message was truncated). If non-zero is returned,
33840** then it is not necessary to include the nul-terminator character
33841** in the output buffer.
33842**
33843** Not supplying an error message will have no adverse effect
33844** on SQLite. It is fine to have an implementation that never
33845** returns an error message:
33846**
33847**   int xGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
33848**     assert(zBuf[0]=='\0');
33849**     return 0;
33850**   }
33851**
33852** However if an error message is supplied, it will be incorporated
33853** by sqlite into the error message available to the user using
33854** sqlite3_errmsg(), possibly making IO errors easier to debug.
33855*/
33856static int winGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
33857  UNUSED_PARAMETER(pVfs);
33858  return getLastErrorMsg(nBuf, zBuf);
33859}
33860
33861
33862
33863/*
33864** Initialize and deinitialize the operating system interface.
33865*/
33866SQLITE_API int sqlite3_os_init(void){
33867  static sqlite3_vfs winVfs = {
33868    3,                   /* iVersion */
33869    sizeof(winFile),     /* szOsFile */
33870    MAX_PATH,            /* mxPathname */
33871    0,                   /* pNext */
33872    "win32",             /* zName */
33873    0,                   /* pAppData */
33874    winOpen,             /* xOpen */
33875    winDelete,           /* xDelete */
33876    winAccess,           /* xAccess */
33877    winFullPathname,     /* xFullPathname */
33878    winDlOpen,           /* xDlOpen */
33879    winDlError,          /* xDlError */
33880    winDlSym,            /* xDlSym */
33881    winDlClose,          /* xDlClose */
33882    winRandomness,       /* xRandomness */
33883    winSleep,            /* xSleep */
33884    winCurrentTime,      /* xCurrentTime */
33885    winGetLastError,     /* xGetLastError */
33886    winCurrentTimeInt64, /* xCurrentTimeInt64 */
33887    0,                   /* xSetSystemCall */
33888    0,                   /* xGetSystemCall */
33889    0,                   /* xNextSystemCall */
33890  };
33891
33892#ifndef SQLITE_OMIT_WAL
33893  /* get memory map allocation granularity */
33894  memset(&winSysInfo, 0, sizeof(SYSTEM_INFO));
33895  GetSystemInfo(&winSysInfo);
33896  assert(winSysInfo.dwAllocationGranularity > 0);
33897#endif
33898
33899  sqlite3_vfs_register(&winVfs, 1);
33900  return SQLITE_OK;
33901}
33902SQLITE_API int sqlite3_os_end(void){
33903  return SQLITE_OK;
33904}
33905
33906void chromium_sqlite3_initialize_win_sqlite3_file(sqlite3_file* file, HANDLE handle) {
33907  winFile* winSQLite3File = (winFile*)file;
33908  memset(file, 0, sizeof(*file));
33909  winSQLite3File->pMethod = &winIoMethod;
33910  winSQLite3File->h = handle;
33911}
33912
33913#endif /* SQLITE_OS_WIN */
33914
33915/************** End of os_win.c **********************************************/
33916/************** Begin file bitvec.c ******************************************/
33917/*
33918** 2008 February 16
33919**
33920** The author disclaims copyright to this source code.  In place of
33921** a legal notice, here is a blessing:
33922**
33923**    May you do good and not evil.
33924**    May you find forgiveness for yourself and forgive others.
33925**    May you share freely, never taking more than you give.
33926**
33927*************************************************************************
33928** This file implements an object that represents a fixed-length
33929** bitmap.  Bits are numbered starting with 1.
33930**
33931** A bitmap is used to record which pages of a database file have been
33932** journalled during a transaction, or which pages have the "dont-write"
33933** property.  Usually only a few pages are meet either condition.
33934** So the bitmap is usually sparse and has low cardinality.
33935** But sometimes (for example when during a DROP of a large table) most
33936** or all of the pages in a database can get journalled.  In those cases,
33937** the bitmap becomes dense with high cardinality.  The algorithm needs
33938** to handle both cases well.
33939**
33940** The size of the bitmap is fixed when the object is created.
33941**
33942** All bits are clear when the bitmap is created.  Individual bits
33943** may be set or cleared one at a time.
33944**
33945** Test operations are about 100 times more common that set operations.
33946** Clear operations are exceedingly rare.  There are usually between
33947** 5 and 500 set operations per Bitvec object, though the number of sets can
33948** sometimes grow into tens of thousands or larger.  The size of the
33949** Bitvec object is the number of pages in the database file at the
33950** start of a transaction, and is thus usually less than a few thousand,
33951** but can be as large as 2 billion for a really big database.
33952*/
33953
33954/* Size of the Bitvec structure in bytes. */
33955#define BITVEC_SZ        512
33956
33957/* Round the union size down to the nearest pointer boundary, since that's how
33958** it will be aligned within the Bitvec struct. */
33959#define BITVEC_USIZE     (((BITVEC_SZ-(3*sizeof(u32)))/sizeof(Bitvec*))*sizeof(Bitvec*))
33960
33961/* Type of the array "element" for the bitmap representation.
33962** Should be a power of 2, and ideally, evenly divide into BITVEC_USIZE.
33963** Setting this to the "natural word" size of your CPU may improve
33964** performance. */
33965#define BITVEC_TELEM     u8
33966/* Size, in bits, of the bitmap element. */
33967#define BITVEC_SZELEM    8
33968/* Number of elements in a bitmap array. */
33969#define BITVEC_NELEM     (BITVEC_USIZE/sizeof(BITVEC_TELEM))
33970/* Number of bits in the bitmap array. */
33971#define BITVEC_NBIT      (BITVEC_NELEM*BITVEC_SZELEM)
33972
33973/* Number of u32 values in hash table. */
33974#define BITVEC_NINT      (BITVEC_USIZE/sizeof(u32))
33975/* Maximum number of entries in hash table before
33976** sub-dividing and re-hashing. */
33977#define BITVEC_MXHASH    (BITVEC_NINT/2)
33978/* Hashing function for the aHash representation.
33979** Empirical testing showed that the *37 multiplier
33980** (an arbitrary prime)in the hash function provided
33981** no fewer collisions than the no-op *1. */
33982#define BITVEC_HASH(X)   (((X)*1)%BITVEC_NINT)
33983
33984#define BITVEC_NPTR      (BITVEC_USIZE/sizeof(Bitvec *))
33985
33986
33987/*
33988** A bitmap is an instance of the following structure.
33989**
33990** This bitmap records the existance of zero or more bits
33991** with values between 1 and iSize, inclusive.
33992**
33993** There are three possible representations of the bitmap.
33994** If iSize<=BITVEC_NBIT, then Bitvec.u.aBitmap[] is a straight
33995** bitmap.  The least significant bit is bit 1.
33996**
33997** If iSize>BITVEC_NBIT and iDivisor==0 then Bitvec.u.aHash[] is
33998** a hash table that will hold up to BITVEC_MXHASH distinct values.
33999**
34000** Otherwise, the value i is redirected into one of BITVEC_NPTR
34001** sub-bitmaps pointed to by Bitvec.u.apSub[].  Each subbitmap
34002** handles up to iDivisor separate values of i.  apSub[0] holds
34003** values between 1 and iDivisor.  apSub[1] holds values between
34004** iDivisor+1 and 2*iDivisor.  apSub[N] holds values between
34005** N*iDivisor+1 and (N+1)*iDivisor.  Each subbitmap is normalized
34006** to hold deal with values between 1 and iDivisor.
34007*/
34008struct Bitvec {
34009  u32 iSize;      /* Maximum bit index.  Max iSize is 4,294,967,296. */
34010  u32 nSet;       /* Number of bits that are set - only valid for aHash
34011                  ** element.  Max is BITVEC_NINT.  For BITVEC_SZ of 512,
34012                  ** this would be 125. */
34013  u32 iDivisor;   /* Number of bits handled by each apSub[] entry. */
34014                  /* Should >=0 for apSub element. */
34015                  /* Max iDivisor is max(u32) / BITVEC_NPTR + 1.  */
34016                  /* For a BITVEC_SZ of 512, this would be 34,359,739. */
34017  union {
34018    BITVEC_TELEM aBitmap[BITVEC_NELEM];    /* Bitmap representation */
34019    u32 aHash[BITVEC_NINT];      /* Hash table representation */
34020    Bitvec *apSub[BITVEC_NPTR];  /* Recursive representation */
34021  } u;
34022};
34023
34024/*
34025** Create a new bitmap object able to handle bits between 0 and iSize,
34026** inclusive.  Return a pointer to the new object.  Return NULL if
34027** malloc fails.
34028*/
34029SQLITE_PRIVATE Bitvec *sqlite3BitvecCreate(u32 iSize){
34030  Bitvec *p;
34031  assert( sizeof(*p)==BITVEC_SZ );
34032  p = sqlite3MallocZero( sizeof(*p) );
34033  if( p ){
34034    p->iSize = iSize;
34035  }
34036  return p;
34037}
34038
34039/*
34040** Check to see if the i-th bit is set.  Return true or false.
34041** If p is NULL (if the bitmap has not been created) or if
34042** i is out of range, then return false.
34043*/
34044SQLITE_PRIVATE int sqlite3BitvecTest(Bitvec *p, u32 i){
34045  if( p==0 ) return 0;
34046  if( i>p->iSize || i==0 ) return 0;
34047  i--;
34048  while( p->iDivisor ){
34049    u32 bin = i/p->iDivisor;
34050    i = i%p->iDivisor;
34051    p = p->u.apSub[bin];
34052    if (!p) {
34053      return 0;
34054    }
34055  }
34056  if( p->iSize<=BITVEC_NBIT ){
34057    return (p->u.aBitmap[i/BITVEC_SZELEM] & (1<<(i&(BITVEC_SZELEM-1))))!=0;
34058  } else{
34059    u32 h = BITVEC_HASH(i++);
34060    while( p->u.aHash[h] ){
34061      if( p->u.aHash[h]==i ) return 1;
34062      h = (h+1) % BITVEC_NINT;
34063    }
34064    return 0;
34065  }
34066}
34067
34068/*
34069** Set the i-th bit.  Return 0 on success and an error code if
34070** anything goes wrong.
34071**
34072** This routine might cause sub-bitmaps to be allocated.  Failing
34073** to get the memory needed to hold the sub-bitmap is the only
34074** that can go wrong with an insert, assuming p and i are valid.
34075**
34076** The calling function must ensure that p is a valid Bitvec object
34077** and that the value for "i" is within range of the Bitvec object.
34078** Otherwise the behavior is undefined.
34079*/
34080SQLITE_PRIVATE int sqlite3BitvecSet(Bitvec *p, u32 i){
34081  u32 h;
34082  if( p==0 ) return SQLITE_OK;
34083  assert( i>0 );
34084  assert( i<=p->iSize );
34085  i--;
34086  while((p->iSize > BITVEC_NBIT) && p->iDivisor) {
34087    u32 bin = i/p->iDivisor;
34088    i = i%p->iDivisor;
34089    if( p->u.apSub[bin]==0 ){
34090      p->u.apSub[bin] = sqlite3BitvecCreate( p->iDivisor );
34091      if( p->u.apSub[bin]==0 ) return SQLITE_NOMEM;
34092    }
34093    p = p->u.apSub[bin];
34094  }
34095  if( p->iSize<=BITVEC_NBIT ){
34096    p->u.aBitmap[i/BITVEC_SZELEM] |= 1 << (i&(BITVEC_SZELEM-1));
34097    return SQLITE_OK;
34098  }
34099  h = BITVEC_HASH(i++);
34100  /* if there wasn't a hash collision, and this doesn't */
34101  /* completely fill the hash, then just add it without */
34102  /* worring about sub-dividing and re-hashing. */
34103  if( !p->u.aHash[h] ){
34104    if (p->nSet<(BITVEC_NINT-1)) {
34105      goto bitvec_set_end;
34106    } else {
34107      goto bitvec_set_rehash;
34108    }
34109  }
34110  /* there was a collision, check to see if it's already */
34111  /* in hash, if not, try to find a spot for it */
34112  do {
34113    if( p->u.aHash[h]==i ) return SQLITE_OK;
34114    h++;
34115    if( h>=BITVEC_NINT ) h = 0;
34116  } while( p->u.aHash[h] );
34117  /* we didn't find it in the hash.  h points to the first */
34118  /* available free spot. check to see if this is going to */
34119  /* make our hash too "full".  */
34120bitvec_set_rehash:
34121  if( p->nSet>=BITVEC_MXHASH ){
34122    unsigned int j;
34123    int rc;
34124    u32 *aiValues = sqlite3StackAllocRaw(0, sizeof(p->u.aHash));
34125    if( aiValues==0 ){
34126      return SQLITE_NOMEM;
34127    }else{
34128      memcpy(aiValues, p->u.aHash, sizeof(p->u.aHash));
34129      memset(p->u.apSub, 0, sizeof(p->u.apSub));
34130      p->iDivisor = (p->iSize + BITVEC_NPTR - 1)/BITVEC_NPTR;
34131      rc = sqlite3BitvecSet(p, i);
34132      for(j=0; j<BITVEC_NINT; j++){
34133        if( aiValues[j] ) rc |= sqlite3BitvecSet(p, aiValues[j]);
34134      }
34135      sqlite3StackFree(0, aiValues);
34136      return rc;
34137    }
34138  }
34139bitvec_set_end:
34140  p->nSet++;
34141  p->u.aHash[h] = i;
34142  return SQLITE_OK;
34143}
34144
34145/*
34146** Clear the i-th bit.
34147**
34148** pBuf must be a pointer to at least BITVEC_SZ bytes of temporary storage
34149** that BitvecClear can use to rebuilt its hash table.
34150*/
34151SQLITE_PRIVATE void sqlite3BitvecClear(Bitvec *p, u32 i, void *pBuf){
34152  if( p==0 ) return;
34153  assert( i>0 );
34154  i--;
34155  while( p->iDivisor ){
34156    u32 bin = i/p->iDivisor;
34157    i = i%p->iDivisor;
34158    p = p->u.apSub[bin];
34159    if (!p) {
34160      return;
34161    }
34162  }
34163  if( p->iSize<=BITVEC_NBIT ){
34164    p->u.aBitmap[i/BITVEC_SZELEM] &= ~(1 << (i&(BITVEC_SZELEM-1)));
34165  }else{
34166    unsigned int j;
34167    u32 *aiValues = pBuf;
34168    memcpy(aiValues, p->u.aHash, sizeof(p->u.aHash));
34169    memset(p->u.aHash, 0, sizeof(p->u.aHash));
34170    p->nSet = 0;
34171    for(j=0; j<BITVEC_NINT; j++){
34172      if( aiValues[j] && aiValues[j]!=(i+1) ){
34173        u32 h = BITVEC_HASH(aiValues[j]-1);
34174        p->nSet++;
34175        while( p->u.aHash[h] ){
34176          h++;
34177          if( h>=BITVEC_NINT ) h = 0;
34178        }
34179        p->u.aHash[h] = aiValues[j];
34180      }
34181    }
34182  }
34183}
34184
34185/*
34186** Destroy a bitmap object.  Reclaim all memory used.
34187*/
34188SQLITE_PRIVATE void sqlite3BitvecDestroy(Bitvec *p){
34189  if( p==0 ) return;
34190  if( p->iDivisor ){
34191    unsigned int i;
34192    for(i=0; i<BITVEC_NPTR; i++){
34193      sqlite3BitvecDestroy(p->u.apSub[i]);
34194    }
34195  }
34196  sqlite3_free(p);
34197}
34198
34199/*
34200** Return the value of the iSize parameter specified when Bitvec *p
34201** was created.
34202*/
34203SQLITE_PRIVATE u32 sqlite3BitvecSize(Bitvec *p){
34204  return p->iSize;
34205}
34206
34207#ifndef SQLITE_OMIT_BUILTIN_TEST
34208/*
34209** Let V[] be an array of unsigned characters sufficient to hold
34210** up to N bits.  Let I be an integer between 0 and N.  0<=I<N.
34211** Then the following macros can be used to set, clear, or test
34212** individual bits within V.
34213*/
34214#define SETBIT(V,I)      V[I>>3] |= (1<<(I&7))
34215#define CLEARBIT(V,I)    V[I>>3] &= ~(1<<(I&7))
34216#define TESTBIT(V,I)     (V[I>>3]&(1<<(I&7)))!=0
34217
34218/*
34219** This routine runs an extensive test of the Bitvec code.
34220**
34221** The input is an array of integers that acts as a program
34222** to test the Bitvec.  The integers are opcodes followed
34223** by 0, 1, or 3 operands, depending on the opcode.  Another
34224** opcode follows immediately after the last operand.
34225**
34226** There are 6 opcodes numbered from 0 through 5.  0 is the
34227** "halt" opcode and causes the test to end.
34228**
34229**    0          Halt and return the number of errors
34230**    1 N S X    Set N bits beginning with S and incrementing by X
34231**    2 N S X    Clear N bits beginning with S and incrementing by X
34232**    3 N        Set N randomly chosen bits
34233**    4 N        Clear N randomly chosen bits
34234**    5 N S X    Set N bits from S increment X in array only, not in bitvec
34235**
34236** The opcodes 1 through 4 perform set and clear operations are performed
34237** on both a Bitvec object and on a linear array of bits obtained from malloc.
34238** Opcode 5 works on the linear array only, not on the Bitvec.
34239** Opcode 5 is used to deliberately induce a fault in order to
34240** confirm that error detection works.
34241**
34242** At the conclusion of the test the linear array is compared
34243** against the Bitvec object.  If there are any differences,
34244** an error is returned.  If they are the same, zero is returned.
34245**
34246** If a memory allocation error occurs, return -1.
34247*/
34248SQLITE_PRIVATE int sqlite3BitvecBuiltinTest(int sz, int *aOp){
34249  Bitvec *pBitvec = 0;
34250  unsigned char *pV = 0;
34251  int rc = -1;
34252  int i, nx, pc, op;
34253  void *pTmpSpace;
34254
34255  /* Allocate the Bitvec to be tested and a linear array of
34256  ** bits to act as the reference */
34257  pBitvec = sqlite3BitvecCreate( sz );
34258  pV = sqlite3_malloc( (sz+7)/8 + 1 );
34259  pTmpSpace = sqlite3_malloc(BITVEC_SZ);
34260  if( pBitvec==0 || pV==0 || pTmpSpace==0  ) goto bitvec_end;
34261  memset(pV, 0, (sz+7)/8 + 1);
34262
34263  /* NULL pBitvec tests */
34264  sqlite3BitvecSet(0, 1);
34265  sqlite3BitvecClear(0, 1, pTmpSpace);
34266
34267  /* Run the program */
34268  pc = 0;
34269  while( (op = aOp[pc])!=0 ){
34270    switch( op ){
34271      case 1:
34272      case 2:
34273      case 5: {
34274        nx = 4;
34275        i = aOp[pc+2] - 1;
34276        aOp[pc+2] += aOp[pc+3];
34277        break;
34278      }
34279      case 3:
34280      case 4:
34281      default: {
34282        nx = 2;
34283        sqlite3_randomness(sizeof(i), &i);
34284        break;
34285      }
34286    }
34287    if( (--aOp[pc+1]) > 0 ) nx = 0;
34288    pc += nx;
34289    i = (i & 0x7fffffff)%sz;
34290    if( (op & 1)!=0 ){
34291      SETBIT(pV, (i+1));
34292      if( op!=5 ){
34293        if( sqlite3BitvecSet(pBitvec, i+1) ) goto bitvec_end;
34294      }
34295    }else{
34296      CLEARBIT(pV, (i+1));
34297      sqlite3BitvecClear(pBitvec, i+1, pTmpSpace);
34298    }
34299  }
34300
34301  /* Test to make sure the linear array exactly matches the
34302  ** Bitvec object.  Start with the assumption that they do
34303  ** match (rc==0).  Change rc to non-zero if a discrepancy
34304  ** is found.
34305  */
34306  rc = sqlite3BitvecTest(0,0) + sqlite3BitvecTest(pBitvec, sz+1)
34307          + sqlite3BitvecTest(pBitvec, 0)
34308          + (sqlite3BitvecSize(pBitvec) - sz);
34309  for(i=1; i<=sz; i++){
34310    if(  (TESTBIT(pV,i))!=sqlite3BitvecTest(pBitvec,i) ){
34311      rc = i;
34312      break;
34313    }
34314  }
34315
34316  /* Free allocated structure */
34317bitvec_end:
34318  sqlite3_free(pTmpSpace);
34319  sqlite3_free(pV);
34320  sqlite3BitvecDestroy(pBitvec);
34321  return rc;
34322}
34323#endif /* SQLITE_OMIT_BUILTIN_TEST */
34324
34325/************** End of bitvec.c **********************************************/
34326/************** Begin file pcache.c ******************************************/
34327/*
34328** 2008 August 05
34329**
34330** The author disclaims copyright to this source code.  In place of
34331** a legal notice, here is a blessing:
34332**
34333**    May you do good and not evil.
34334**    May you find forgiveness for yourself and forgive others.
34335**    May you share freely, never taking more than you give.
34336**
34337*************************************************************************
34338** This file implements that page cache.
34339*/
34340
34341/*
34342** A complete page cache is an instance of this structure.
34343*/
34344struct PCache {
34345  PgHdr *pDirty, *pDirtyTail;         /* List of dirty pages in LRU order */
34346  PgHdr *pSynced;                     /* Last synced page in dirty page list */
34347  int nRef;                           /* Number of referenced pages */
34348  int nMax;                           /* Configured cache size */
34349  int szPage;                         /* Size of every page in this cache */
34350  int szExtra;                        /* Size of extra space for each page */
34351  int bPurgeable;                     /* True if pages are on backing store */
34352  int (*xStress)(void*,PgHdr*);       /* Call to try make a page clean */
34353  void *pStress;                      /* Argument to xStress */
34354  sqlite3_pcache *pCache;             /* Pluggable cache module */
34355  PgHdr *pPage1;                      /* Reference to page 1 */
34356};
34357
34358/*
34359** Some of the assert() macros in this code are too expensive to run
34360** even during normal debugging.  Use them only rarely on long-running
34361** tests.  Enable the expensive asserts using the
34362** -DSQLITE_ENABLE_EXPENSIVE_ASSERT=1 compile-time option.
34363*/
34364#ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
34365# define expensive_assert(X)  assert(X)
34366#else
34367# define expensive_assert(X)
34368#endif
34369
34370/********************************** Linked List Management ********************/
34371
34372#if !defined(NDEBUG) && defined(SQLITE_ENABLE_EXPENSIVE_ASSERT)
34373/*
34374** Check that the pCache->pSynced variable is set correctly. If it
34375** is not, either fail an assert or return zero. Otherwise, return
34376** non-zero. This is only used in debugging builds, as follows:
34377**
34378**   expensive_assert( pcacheCheckSynced(pCache) );
34379*/
34380static int pcacheCheckSynced(PCache *pCache){
34381  PgHdr *p;
34382  for(p=pCache->pDirtyTail; p!=pCache->pSynced; p=p->pDirtyPrev){
34383    assert( p->nRef || (p->flags&PGHDR_NEED_SYNC) );
34384  }
34385  return (p==0 || p->nRef || (p->flags&PGHDR_NEED_SYNC)==0);
34386}
34387#endif /* !NDEBUG && SQLITE_ENABLE_EXPENSIVE_ASSERT */
34388
34389/*
34390** Remove page pPage from the list of dirty pages.
34391*/
34392static void pcacheRemoveFromDirtyList(PgHdr *pPage){
34393  PCache *p = pPage->pCache;
34394
34395  assert( pPage->pDirtyNext || pPage==p->pDirtyTail );
34396  assert( pPage->pDirtyPrev || pPage==p->pDirty );
34397
34398  /* Update the PCache1.pSynced variable if necessary. */
34399  if( p->pSynced==pPage ){
34400    PgHdr *pSynced = pPage->pDirtyPrev;
34401    while( pSynced && (pSynced->flags&PGHDR_NEED_SYNC) ){
34402      pSynced = pSynced->pDirtyPrev;
34403    }
34404    p->pSynced = pSynced;
34405  }
34406
34407  if( pPage->pDirtyNext ){
34408    pPage->pDirtyNext->pDirtyPrev = pPage->pDirtyPrev;
34409  }else{
34410    assert( pPage==p->pDirtyTail );
34411    p->pDirtyTail = pPage->pDirtyPrev;
34412  }
34413  if( pPage->pDirtyPrev ){
34414    pPage->pDirtyPrev->pDirtyNext = pPage->pDirtyNext;
34415  }else{
34416    assert( pPage==p->pDirty );
34417    p->pDirty = pPage->pDirtyNext;
34418  }
34419  pPage->pDirtyNext = 0;
34420  pPage->pDirtyPrev = 0;
34421
34422  expensive_assert( pcacheCheckSynced(p) );
34423}
34424
34425/*
34426** Add page pPage to the head of the dirty list (PCache1.pDirty is set to
34427** pPage).
34428*/
34429static void pcacheAddToDirtyList(PgHdr *pPage){
34430  PCache *p = pPage->pCache;
34431
34432  assert( pPage->pDirtyNext==0 && pPage->pDirtyPrev==0 && p->pDirty!=pPage );
34433
34434  pPage->pDirtyNext = p->pDirty;
34435  if( pPage->pDirtyNext ){
34436    assert( pPage->pDirtyNext->pDirtyPrev==0 );
34437    pPage->pDirtyNext->pDirtyPrev = pPage;
34438  }
34439  p->pDirty = pPage;
34440  if( !p->pDirtyTail ){
34441    p->pDirtyTail = pPage;
34442  }
34443  if( !p->pSynced && 0==(pPage->flags&PGHDR_NEED_SYNC) ){
34444    p->pSynced = pPage;
34445  }
34446  expensive_assert( pcacheCheckSynced(p) );
34447}
34448
34449/*
34450** Wrapper around the pluggable caches xUnpin method. If the cache is
34451** being used for an in-memory database, this function is a no-op.
34452*/
34453static void pcacheUnpin(PgHdr *p){
34454  PCache *pCache = p->pCache;
34455  if( pCache->bPurgeable ){
34456    if( p->pgno==1 ){
34457      pCache->pPage1 = 0;
34458    }
34459    sqlite3GlobalConfig.pcache.xUnpin(pCache->pCache, p, 0);
34460  }
34461}
34462
34463/*************************************************** General Interfaces ******
34464**
34465** Initialize and shutdown the page cache subsystem. Neither of these
34466** functions are threadsafe.
34467*/
34468SQLITE_PRIVATE int sqlite3PcacheInitialize(void){
34469  if( sqlite3GlobalConfig.pcache.xInit==0 ){
34470    /* IMPLEMENTATION-OF: R-26801-64137 If the xInit() method is NULL, then the
34471    ** built-in default page cache is used instead of the application defined
34472    ** page cache. */
34473    sqlite3PCacheSetDefault();
34474  }
34475  return sqlite3GlobalConfig.pcache.xInit(sqlite3GlobalConfig.pcache.pArg);
34476}
34477SQLITE_PRIVATE void sqlite3PcacheShutdown(void){
34478  if( sqlite3GlobalConfig.pcache.xShutdown ){
34479    /* IMPLEMENTATION-OF: R-26000-56589 The xShutdown() method may be NULL. */
34480    sqlite3GlobalConfig.pcache.xShutdown(sqlite3GlobalConfig.pcache.pArg);
34481  }
34482}
34483
34484/*
34485** Return the size in bytes of a PCache object.
34486*/
34487SQLITE_PRIVATE int sqlite3PcacheSize(void){ return sizeof(PCache); }
34488
34489/*
34490** Create a new PCache object. Storage space to hold the object
34491** has already been allocated and is passed in as the p pointer.
34492** The caller discovers how much space needs to be allocated by
34493** calling sqlite3PcacheSize().
34494*/
34495SQLITE_PRIVATE void sqlite3PcacheOpen(
34496  int szPage,                  /* Size of every page */
34497  int szExtra,                 /* Extra space associated with each page */
34498  int bPurgeable,              /* True if pages are on backing store */
34499  int (*xStress)(void*,PgHdr*),/* Call to try to make pages clean */
34500  void *pStress,               /* Argument to xStress */
34501  PCache *p                    /* Preallocated space for the PCache */
34502){
34503  memset(p, 0, sizeof(PCache));
34504  p->szPage = szPage;
34505  p->szExtra = szExtra;
34506  p->bPurgeable = bPurgeable;
34507  p->xStress = xStress;
34508  p->pStress = pStress;
34509  p->nMax = 100;
34510}
34511
34512/*
34513** Change the page size for PCache object. The caller must ensure that there
34514** are no outstanding page references when this function is called.
34515*/
34516SQLITE_PRIVATE void sqlite3PcacheSetPageSize(PCache *pCache, int szPage){
34517  assert( pCache->nRef==0 && pCache->pDirty==0 );
34518  if( pCache->pCache ){
34519    sqlite3GlobalConfig.pcache.xDestroy(pCache->pCache);
34520    pCache->pCache = 0;
34521    pCache->pPage1 = 0;
34522  }
34523  pCache->szPage = szPage;
34524}
34525
34526/*
34527** Try to obtain a page from the cache.
34528*/
34529SQLITE_PRIVATE int sqlite3PcacheFetch(
34530  PCache *pCache,       /* Obtain the page from this cache */
34531  Pgno pgno,            /* Page number to obtain */
34532  int createFlag,       /* If true, create page if it does not exist already */
34533  PgHdr **ppPage        /* Write the page here */
34534){
34535  PgHdr *pPage = 0;
34536  int eCreate;
34537
34538  assert( pCache!=0 );
34539  assert( createFlag==1 || createFlag==0 );
34540  assert( pgno>0 );
34541
34542  /* If the pluggable cache (sqlite3_pcache*) has not been allocated,
34543  ** allocate it now.
34544  */
34545  if( !pCache->pCache && createFlag ){
34546    sqlite3_pcache *p;
34547    int nByte;
34548    nByte = pCache->szPage + pCache->szExtra + sizeof(PgHdr);
34549    p = sqlite3GlobalConfig.pcache.xCreate(nByte, pCache->bPurgeable);
34550    if( !p ){
34551      return SQLITE_NOMEM;
34552    }
34553    sqlite3GlobalConfig.pcache.xCachesize(p, pCache->nMax);
34554    pCache->pCache = p;
34555  }
34556
34557  eCreate = createFlag * (1 + (!pCache->bPurgeable || !pCache->pDirty));
34558  if( pCache->pCache ){
34559    pPage = sqlite3GlobalConfig.pcache.xFetch(pCache->pCache, pgno, eCreate);
34560  }
34561
34562  if( !pPage && eCreate==1 ){
34563    PgHdr *pPg;
34564
34565    /* Find a dirty page to write-out and recycle. First try to find a
34566    ** page that does not require a journal-sync (one with PGHDR_NEED_SYNC
34567    ** cleared), but if that is not possible settle for any other
34568    ** unreferenced dirty page.
34569    */
34570    expensive_assert( pcacheCheckSynced(pCache) );
34571    for(pPg=pCache->pSynced;
34572        pPg && (pPg->nRef || (pPg->flags&PGHDR_NEED_SYNC));
34573        pPg=pPg->pDirtyPrev
34574    );
34575    pCache->pSynced = pPg;
34576    if( !pPg ){
34577      for(pPg=pCache->pDirtyTail; pPg && pPg->nRef; pPg=pPg->pDirtyPrev);
34578    }
34579    if( pPg ){
34580      int rc;
34581      rc = pCache->xStress(pCache->pStress, pPg);
34582      if( rc!=SQLITE_OK && rc!=SQLITE_BUSY ){
34583        return rc;
34584      }
34585    }
34586
34587    pPage = sqlite3GlobalConfig.pcache.xFetch(pCache->pCache, pgno, 2);
34588  }
34589
34590  if( pPage ){
34591    if( !pPage->pData ){
34592      memset(pPage, 0, sizeof(PgHdr));
34593      pPage->pData = (void *)&pPage[1];
34594      pPage->pExtra = (void*)&((char *)pPage->pData)[pCache->szPage];
34595      memset(pPage->pExtra, 0, pCache->szExtra);
34596      pPage->pCache = pCache;
34597      pPage->pgno = pgno;
34598    }
34599    assert( pPage->pCache==pCache );
34600    assert( pPage->pgno==pgno );
34601    assert( pPage->pData==(void *)&pPage[1] );
34602    assert( pPage->pExtra==(void *)&((char *)&pPage[1])[pCache->szPage] );
34603
34604    if( 0==pPage->nRef ){
34605      pCache->nRef++;
34606    }
34607    pPage->nRef++;
34608    if( pgno==1 ){
34609      pCache->pPage1 = pPage;
34610    }
34611  }
34612  *ppPage = pPage;
34613  return (pPage==0 && eCreate) ? SQLITE_NOMEM : SQLITE_OK;
34614}
34615
34616/*
34617** Decrement the reference count on a page. If the page is clean and the
34618** reference count drops to 0, then it is made elible for recycling.
34619*/
34620SQLITE_PRIVATE void sqlite3PcacheRelease(PgHdr *p){
34621  assert( p->nRef>0 );
34622  p->nRef--;
34623  if( p->nRef==0 ){
34624    PCache *pCache = p->pCache;
34625    pCache->nRef--;
34626    if( (p->flags&PGHDR_DIRTY)==0 ){
34627      pcacheUnpin(p);
34628    }else{
34629      /* Move the page to the head of the dirty list. */
34630      pcacheRemoveFromDirtyList(p);
34631      pcacheAddToDirtyList(p);
34632    }
34633  }
34634}
34635
34636/*
34637** Increase the reference count of a supplied page by 1.
34638*/
34639SQLITE_PRIVATE void sqlite3PcacheRef(PgHdr *p){
34640  assert(p->nRef>0);
34641  p->nRef++;
34642}
34643
34644/*
34645** Drop a page from the cache. There must be exactly one reference to the
34646** page. This function deletes that reference, so after it returns the
34647** page pointed to by p is invalid.
34648*/
34649SQLITE_PRIVATE void sqlite3PcacheDrop(PgHdr *p){
34650  PCache *pCache;
34651  assert( p->nRef==1 );
34652  if( p->flags&PGHDR_DIRTY ){
34653    pcacheRemoveFromDirtyList(p);
34654  }
34655  pCache = p->pCache;
34656  pCache->nRef--;
34657  if( p->pgno==1 ){
34658    pCache->pPage1 = 0;
34659  }
34660  sqlite3GlobalConfig.pcache.xUnpin(pCache->pCache, p, 1);
34661}
34662
34663/*
34664** Make sure the page is marked as dirty. If it isn't dirty already,
34665** make it so.
34666*/
34667SQLITE_PRIVATE void sqlite3PcacheMakeDirty(PgHdr *p){
34668  p->flags &= ~PGHDR_DONT_WRITE;
34669  assert( p->nRef>0 );
34670  if( 0==(p->flags & PGHDR_DIRTY) ){
34671    p->flags |= PGHDR_DIRTY;
34672    pcacheAddToDirtyList( p);
34673  }
34674}
34675
34676/*
34677** Make sure the page is marked as clean. If it isn't clean already,
34678** make it so.
34679*/
34680SQLITE_PRIVATE void sqlite3PcacheMakeClean(PgHdr *p){
34681  if( (p->flags & PGHDR_DIRTY) ){
34682    pcacheRemoveFromDirtyList(p);
34683    p->flags &= ~(PGHDR_DIRTY|PGHDR_NEED_SYNC);
34684    if( p->nRef==0 ){
34685      pcacheUnpin(p);
34686    }
34687  }
34688}
34689
34690/*
34691** Make every page in the cache clean.
34692*/
34693SQLITE_PRIVATE void sqlite3PcacheCleanAll(PCache *pCache){
34694  PgHdr *p;
34695  while( (p = pCache->pDirty)!=0 ){
34696    sqlite3PcacheMakeClean(p);
34697  }
34698}
34699
34700/*
34701** Clear the PGHDR_NEED_SYNC flag from all dirty pages.
34702*/
34703SQLITE_PRIVATE void sqlite3PcacheClearSyncFlags(PCache *pCache){
34704  PgHdr *p;
34705  for(p=pCache->pDirty; p; p=p->pDirtyNext){
34706    p->flags &= ~PGHDR_NEED_SYNC;
34707  }
34708  pCache->pSynced = pCache->pDirtyTail;
34709}
34710
34711/*
34712** Change the page number of page p to newPgno.
34713*/
34714SQLITE_PRIVATE void sqlite3PcacheMove(PgHdr *p, Pgno newPgno){
34715  PCache *pCache = p->pCache;
34716  assert( p->nRef>0 );
34717  assert( newPgno>0 );
34718  sqlite3GlobalConfig.pcache.xRekey(pCache->pCache, p, p->pgno, newPgno);
34719  p->pgno = newPgno;
34720  if( (p->flags&PGHDR_DIRTY) && (p->flags&PGHDR_NEED_SYNC) ){
34721    pcacheRemoveFromDirtyList(p);
34722    pcacheAddToDirtyList(p);
34723  }
34724}
34725
34726/*
34727** Drop every cache entry whose page number is greater than "pgno". The
34728** caller must ensure that there are no outstanding references to any pages
34729** other than page 1 with a page number greater than pgno.
34730**
34731** If there is a reference to page 1 and the pgno parameter passed to this
34732** function is 0, then the data area associated with page 1 is zeroed, but
34733** the page object is not dropped.
34734*/
34735SQLITE_PRIVATE void sqlite3PcacheTruncate(PCache *pCache, Pgno pgno){
34736  if( pCache->pCache ){
34737    PgHdr *p;
34738    PgHdr *pNext;
34739    for(p=pCache->pDirty; p; p=pNext){
34740      pNext = p->pDirtyNext;
34741      /* This routine never gets call with a positive pgno except right
34742      ** after sqlite3PcacheCleanAll().  So if there are dirty pages,
34743      ** it must be that pgno==0.
34744      */
34745      assert( p->pgno>0 );
34746      if( ALWAYS(p->pgno>pgno) ){
34747        assert( p->flags&PGHDR_DIRTY );
34748        sqlite3PcacheMakeClean(p);
34749      }
34750    }
34751    if( pgno==0 && pCache->pPage1 ){
34752      memset(pCache->pPage1->pData, 0, pCache->szPage);
34753      pgno = 1;
34754    }
34755    sqlite3GlobalConfig.pcache.xTruncate(pCache->pCache, pgno+1);
34756  }
34757}
34758
34759/*
34760** Close a cache.
34761*/
34762SQLITE_PRIVATE void sqlite3PcacheClose(PCache *pCache){
34763  if( pCache->pCache ){
34764    sqlite3GlobalConfig.pcache.xDestroy(pCache->pCache);
34765  }
34766}
34767
34768/*
34769** Discard the contents of the cache.
34770*/
34771SQLITE_PRIVATE void sqlite3PcacheClear(PCache *pCache){
34772  sqlite3PcacheTruncate(pCache, 0);
34773}
34774
34775/*
34776** Merge two lists of pages connected by pDirty and in pgno order.
34777** Do not both fixing the pDirtyPrev pointers.
34778*/
34779static PgHdr *pcacheMergeDirtyList(PgHdr *pA, PgHdr *pB){
34780  PgHdr result, *pTail;
34781  pTail = &result;
34782  while( pA && pB ){
34783    if( pA->pgno<pB->pgno ){
34784      pTail->pDirty = pA;
34785      pTail = pA;
34786      pA = pA->pDirty;
34787    }else{
34788      pTail->pDirty = pB;
34789      pTail = pB;
34790      pB = pB->pDirty;
34791    }
34792  }
34793  if( pA ){
34794    pTail->pDirty = pA;
34795  }else if( pB ){
34796    pTail->pDirty = pB;
34797  }else{
34798    pTail->pDirty = 0;
34799  }
34800  return result.pDirty;
34801}
34802
34803/*
34804** Sort the list of pages in accending order by pgno.  Pages are
34805** connected by pDirty pointers.  The pDirtyPrev pointers are
34806** corrupted by this sort.
34807**
34808** Since there cannot be more than 2^31 distinct pages in a database,
34809** there cannot be more than 31 buckets required by the merge sorter.
34810** One extra bucket is added to catch overflow in case something
34811** ever changes to make the previous sentence incorrect.
34812*/
34813#define N_SORT_BUCKET  32
34814static PgHdr *pcacheSortDirtyList(PgHdr *pIn){
34815  PgHdr *a[N_SORT_BUCKET], *p;
34816  int i;
34817  memset(a, 0, sizeof(a));
34818  while( pIn ){
34819    p = pIn;
34820    pIn = p->pDirty;
34821    p->pDirty = 0;
34822    for(i=0; ALWAYS(i<N_SORT_BUCKET-1); i++){
34823      if( a[i]==0 ){
34824        a[i] = p;
34825        break;
34826      }else{
34827        p = pcacheMergeDirtyList(a[i], p);
34828        a[i] = 0;
34829      }
34830    }
34831    if( NEVER(i==N_SORT_BUCKET-1) ){
34832      /* To get here, there need to be 2^(N_SORT_BUCKET) elements in
34833      ** the input list.  But that is impossible.
34834      */
34835      a[i] = pcacheMergeDirtyList(a[i], p);
34836    }
34837  }
34838  p = a[0];
34839  for(i=1; i<N_SORT_BUCKET; i++){
34840    p = pcacheMergeDirtyList(p, a[i]);
34841  }
34842  return p;
34843}
34844
34845/*
34846** Return a list of all dirty pages in the cache, sorted by page number.
34847*/
34848SQLITE_PRIVATE PgHdr *sqlite3PcacheDirtyList(PCache *pCache){
34849  PgHdr *p;
34850  for(p=pCache->pDirty; p; p=p->pDirtyNext){
34851    p->pDirty = p->pDirtyNext;
34852  }
34853  return pcacheSortDirtyList(pCache->pDirty);
34854}
34855
34856/*
34857** Return the total number of referenced pages held by the cache.
34858*/
34859SQLITE_PRIVATE int sqlite3PcacheRefCount(PCache *pCache){
34860  return pCache->nRef;
34861}
34862
34863/*
34864** Return the number of references to the page supplied as an argument.
34865*/
34866SQLITE_PRIVATE int sqlite3PcachePageRefcount(PgHdr *p){
34867  return p->nRef;
34868}
34869
34870/*
34871** Return the total number of pages in the cache.
34872*/
34873SQLITE_PRIVATE int sqlite3PcachePagecount(PCache *pCache){
34874  int nPage = 0;
34875  if( pCache->pCache ){
34876    nPage = sqlite3GlobalConfig.pcache.xPagecount(pCache->pCache);
34877  }
34878  return nPage;
34879}
34880
34881#ifdef SQLITE_TEST
34882/*
34883** Get the suggested cache-size value.
34884*/
34885SQLITE_PRIVATE int sqlite3PcacheGetCachesize(PCache *pCache){
34886  return pCache->nMax;
34887}
34888#endif
34889
34890/*
34891** Set the suggested cache-size value.
34892*/
34893SQLITE_PRIVATE void sqlite3PcacheSetCachesize(PCache *pCache, int mxPage){
34894  pCache->nMax = mxPage;
34895  if( pCache->pCache ){
34896    sqlite3GlobalConfig.pcache.xCachesize(pCache->pCache, mxPage);
34897  }
34898}
34899
34900#if defined(SQLITE_CHECK_PAGES) || defined(SQLITE_DEBUG)
34901/*
34902** For all dirty pages currently in the cache, invoke the specified
34903** callback. This is only used if the SQLITE_CHECK_PAGES macro is
34904** defined.
34905*/
34906SQLITE_PRIVATE void sqlite3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHdr *)){
34907  PgHdr *pDirty;
34908  for(pDirty=pCache->pDirty; pDirty; pDirty=pDirty->pDirtyNext){
34909    xIter(pDirty);
34910  }
34911}
34912#endif
34913
34914/************** End of pcache.c **********************************************/
34915/************** Begin file pcache1.c *****************************************/
34916/*
34917** 2008 November 05
34918**
34919** The author disclaims copyright to this source code.  In place of
34920** a legal notice, here is a blessing:
34921**
34922**    May you do good and not evil.
34923**    May you find forgiveness for yourself and forgive others.
34924**    May you share freely, never taking more than you give.
34925**
34926*************************************************************************
34927**
34928** This file implements the default page cache implementation (the
34929** sqlite3_pcache interface). It also contains part of the implementation
34930** of the SQLITE_CONFIG_PAGECACHE and sqlite3_release_memory() features.
34931** If the default page cache implementation is overriden, then neither of
34932** these two features are available.
34933*/
34934
34935
34936typedef struct PCache1 PCache1;
34937typedef struct PgHdr1 PgHdr1;
34938typedef struct PgFreeslot PgFreeslot;
34939typedef struct PGroup PGroup;
34940
34941/* Each page cache (or PCache) belongs to a PGroup.  A PGroup is a set
34942** of one or more PCaches that are able to recycle each others unpinned
34943** pages when they are under memory pressure.  A PGroup is an instance of
34944** the following object.
34945**
34946** This page cache implementation works in one of two modes:
34947**
34948**   (1)  Every PCache is the sole member of its own PGroup.  There is
34949**        one PGroup per PCache.
34950**
34951**   (2)  There is a single global PGroup that all PCaches are a member
34952**        of.
34953**
34954** Mode 1 uses more memory (since PCache instances are not able to rob
34955** unused pages from other PCaches) but it also operates without a mutex,
34956** and is therefore often faster.  Mode 2 requires a mutex in order to be
34957** threadsafe, but is able recycle pages more efficient.
34958**
34959** For mode (1), PGroup.mutex is NULL.  For mode (2) there is only a single
34960** PGroup which is the pcache1.grp global variable and its mutex is
34961** SQLITE_MUTEX_STATIC_LRU.
34962*/
34963struct PGroup {
34964  sqlite3_mutex *mutex;          /* MUTEX_STATIC_LRU or NULL */
34965  int nMaxPage;                  /* Sum of nMax for purgeable caches */
34966  int nMinPage;                  /* Sum of nMin for purgeable caches */
34967  int mxPinned;                  /* nMaxpage + 10 - nMinPage */
34968  int nCurrentPage;              /* Number of purgeable pages allocated */
34969  PgHdr1 *pLruHead, *pLruTail;   /* LRU list of unpinned pages */
34970};
34971
34972/* Each page cache is an instance of the following object.  Every
34973** open database file (including each in-memory database and each
34974** temporary or transient database) has a single page cache which
34975** is an instance of this object.
34976**
34977** Pointers to structures of this type are cast and returned as
34978** opaque sqlite3_pcache* handles.
34979*/
34980struct PCache1 {
34981  /* Cache configuration parameters. Page size (szPage) and the purgeable
34982  ** flag (bPurgeable) are set when the cache is created. nMax may be
34983  ** modified at any time by a call to the pcache1CacheSize() method.
34984  ** The PGroup mutex must be held when accessing nMax.
34985  */
34986  PGroup *pGroup;                     /* PGroup this cache belongs to */
34987  int szPage;                         /* Size of allocated pages in bytes */
34988  int bPurgeable;                     /* True if cache is purgeable */
34989  unsigned int nMin;                  /* Minimum number of pages reserved */
34990  unsigned int nMax;                  /* Configured "cache_size" value */
34991  unsigned int n90pct;                /* nMax*9/10 */
34992
34993  /* Hash table of all pages. The following variables may only be accessed
34994  ** when the accessor is holding the PGroup mutex.
34995  */
34996  unsigned int nRecyclable;           /* Number of pages in the LRU list */
34997  unsigned int nPage;                 /* Total number of pages in apHash */
34998  unsigned int nHash;                 /* Number of slots in apHash[] */
34999  PgHdr1 **apHash;                    /* Hash table for fast lookup by key */
35000
35001  unsigned int iMaxKey;               /* Largest key seen since xTruncate() */
35002};
35003
35004/*
35005** Each cache entry is represented by an instance of the following
35006** structure. A buffer of PgHdr1.pCache->szPage bytes is allocated
35007** directly before this structure in memory (see the PGHDR1_TO_PAGE()
35008** macro below).
35009*/
35010struct PgHdr1 {
35011  unsigned int iKey;             /* Key value (page number) */
35012  PgHdr1 *pNext;                 /* Next in hash table chain */
35013  PCache1 *pCache;               /* Cache that currently owns this page */
35014  PgHdr1 *pLruNext;              /* Next in LRU list of unpinned pages */
35015  PgHdr1 *pLruPrev;              /* Previous in LRU list of unpinned pages */
35016};
35017
35018/*
35019** Free slots in the allocator used to divide up the buffer provided using
35020** the SQLITE_CONFIG_PAGECACHE mechanism.
35021*/
35022struct PgFreeslot {
35023  PgFreeslot *pNext;  /* Next free slot */
35024};
35025
35026/*
35027** Global data used by this cache.
35028*/
35029static SQLITE_WSD struct PCacheGlobal {
35030  PGroup grp;                    /* The global PGroup for mode (2) */
35031
35032  /* Variables related to SQLITE_CONFIG_PAGECACHE settings.  The
35033  ** szSlot, nSlot, pStart, pEnd, nReserve, and isInit values are all
35034  ** fixed at sqlite3_initialize() time and do not require mutex protection.
35035  ** The nFreeSlot and pFree values do require mutex protection.
35036  */
35037  int isInit;                    /* True if initialized */
35038  int szSlot;                    /* Size of each free slot */
35039  int nSlot;                     /* The number of pcache slots */
35040  int nReserve;                  /* Try to keep nFreeSlot above this */
35041  void *pStart, *pEnd;           /* Bounds of pagecache malloc range */
35042  /* Above requires no mutex.  Use mutex below for variable that follow. */
35043  sqlite3_mutex *mutex;          /* Mutex for accessing the following: */
35044  int nFreeSlot;                 /* Number of unused pcache slots */
35045  PgFreeslot *pFree;             /* Free page blocks */
35046  /* The following value requires a mutex to change.  We skip the mutex on
35047  ** reading because (1) most platforms read a 32-bit integer atomically and
35048  ** (2) even if an incorrect value is read, no great harm is done since this
35049  ** is really just an optimization. */
35050  int bUnderPressure;            /* True if low on PAGECACHE memory */
35051} pcache1_g;
35052
35053/*
35054** All code in this file should access the global structure above via the
35055** alias "pcache1". This ensures that the WSD emulation is used when
35056** compiling for systems that do not support real WSD.
35057*/
35058#define pcache1 (GLOBAL(struct PCacheGlobal, pcache1_g))
35059
35060/*
35061** When a PgHdr1 structure is allocated, the associated PCache1.szPage
35062** bytes of data are located directly before it in memory (i.e. the total
35063** size of the allocation is sizeof(PgHdr1)+PCache1.szPage byte). The
35064** PGHDR1_TO_PAGE() macro takes a pointer to a PgHdr1 structure as
35065** an argument and returns a pointer to the associated block of szPage
35066** bytes. The PAGE_TO_PGHDR1() macro does the opposite: its argument is
35067** a pointer to a block of szPage bytes of data and the return value is
35068** a pointer to the associated PgHdr1 structure.
35069**
35070**   assert( PGHDR1_TO_PAGE(PAGE_TO_PGHDR1(pCache, X))==X );
35071*/
35072#define PGHDR1_TO_PAGE(p)    (void*)(((char*)p) - p->pCache->szPage)
35073#define PAGE_TO_PGHDR1(c, p) (PgHdr1*)(((char*)p) + c->szPage)
35074
35075/*
35076** Macros to enter and leave the PCache LRU mutex.
35077*/
35078#define pcache1EnterMutex(X) sqlite3_mutex_enter((X)->mutex)
35079#define pcache1LeaveMutex(X) sqlite3_mutex_leave((X)->mutex)
35080
35081/******************************************************************************/
35082/******** Page Allocation/SQLITE_CONFIG_PCACHE Related Functions **************/
35083
35084/*
35085** This function is called during initialization if a static buffer is
35086** supplied to use for the page-cache by passing the SQLITE_CONFIG_PAGECACHE
35087** verb to sqlite3_config(). Parameter pBuf points to an allocation large
35088** enough to contain 'n' buffers of 'sz' bytes each.
35089**
35090** This routine is called from sqlite3_initialize() and so it is guaranteed
35091** to be serialized already.  There is no need for further mutexing.
35092*/
35093SQLITE_PRIVATE void sqlite3PCacheBufferSetup(void *pBuf, int sz, int n){
35094  if( pcache1.isInit ){
35095    PgFreeslot *p;
35096    sz = ROUNDDOWN8(sz);
35097    pcache1.szSlot = sz;
35098    pcache1.nSlot = pcache1.nFreeSlot = n;
35099    pcache1.nReserve = n>90 ? 10 : (n/10 + 1);
35100    pcache1.pStart = pBuf;
35101    pcache1.pFree = 0;
35102    pcache1.bUnderPressure = 0;
35103    while( n-- ){
35104      p = (PgFreeslot*)pBuf;
35105      p->pNext = pcache1.pFree;
35106      pcache1.pFree = p;
35107      pBuf = (void*)&((char*)pBuf)[sz];
35108    }
35109    pcache1.pEnd = pBuf;
35110  }
35111}
35112
35113/*
35114** Malloc function used within this file to allocate space from the buffer
35115** configured using sqlite3_config(SQLITE_CONFIG_PAGECACHE) option. If no
35116** such buffer exists or there is no space left in it, this function falls
35117** back to sqlite3Malloc().
35118**
35119** Multiple threads can run this routine at the same time.  Global variables
35120** in pcache1 need to be protected via mutex.
35121*/
35122static void *pcache1Alloc(int nByte){
35123  void *p = 0;
35124  assert( sqlite3_mutex_notheld(pcache1.grp.mutex) );
35125  sqlite3StatusSet(SQLITE_STATUS_PAGECACHE_SIZE, nByte);
35126  if( nByte<=pcache1.szSlot ){
35127    sqlite3_mutex_enter(pcache1.mutex);
35128    p = (PgHdr1 *)pcache1.pFree;
35129    if( p ){
35130      pcache1.pFree = pcache1.pFree->pNext;
35131      pcache1.nFreeSlot--;
35132      pcache1.bUnderPressure = pcache1.nFreeSlot<pcache1.nReserve;
35133      assert( pcache1.nFreeSlot>=0 );
35134      sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_USED, 1);
35135    }
35136    sqlite3_mutex_leave(pcache1.mutex);
35137  }
35138  if( p==0 ){
35139    /* Memory is not available in the SQLITE_CONFIG_PAGECACHE pool.  Get
35140    ** it from sqlite3Malloc instead.
35141    */
35142    p = sqlite3Malloc(nByte);
35143    if( p ){
35144      int sz = sqlite3MallocSize(p);
35145      sqlite3_mutex_enter(pcache1.mutex);
35146      sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_OVERFLOW, sz);
35147      sqlite3_mutex_leave(pcache1.mutex);
35148    }
35149    sqlite3MemdebugSetType(p, MEMTYPE_PCACHE);
35150  }
35151  return p;
35152}
35153
35154/*
35155** Free an allocated buffer obtained from pcache1Alloc().
35156*/
35157static void pcache1Free(void *p){
35158  if( p==0 ) return;
35159  if( p>=pcache1.pStart && p<pcache1.pEnd ){
35160    PgFreeslot *pSlot;
35161    sqlite3_mutex_enter(pcache1.mutex);
35162    sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_USED, -1);
35163    pSlot = (PgFreeslot*)p;
35164    pSlot->pNext = pcache1.pFree;
35165    pcache1.pFree = pSlot;
35166    pcache1.nFreeSlot++;
35167    pcache1.bUnderPressure = pcache1.nFreeSlot<pcache1.nReserve;
35168    assert( pcache1.nFreeSlot<=pcache1.nSlot );
35169    sqlite3_mutex_leave(pcache1.mutex);
35170  }else{
35171    int iSize;
35172    assert( sqlite3MemdebugHasType(p, MEMTYPE_PCACHE) );
35173    sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
35174    iSize = sqlite3MallocSize(p);
35175    sqlite3_mutex_enter(pcache1.mutex);
35176    sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_OVERFLOW, -iSize);
35177    sqlite3_mutex_leave(pcache1.mutex);
35178    sqlite3_free(p);
35179  }
35180}
35181
35182#ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
35183/*
35184** Return the size of a pcache allocation
35185*/
35186static int pcache1MemSize(void *p){
35187  if( p>=pcache1.pStart && p<pcache1.pEnd ){
35188    return pcache1.szSlot;
35189  }else{
35190    int iSize;
35191    assert( sqlite3MemdebugHasType(p, MEMTYPE_PCACHE) );
35192    sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
35193    iSize = sqlite3MallocSize(p);
35194    sqlite3MemdebugSetType(p, MEMTYPE_PCACHE);
35195    return iSize;
35196  }
35197}
35198#endif /* SQLITE_ENABLE_MEMORY_MANAGEMENT */
35199
35200/*
35201** Allocate a new page object initially associated with cache pCache.
35202*/
35203static PgHdr1 *pcache1AllocPage(PCache1 *pCache){
35204  int nByte = sizeof(PgHdr1) + pCache->szPage;
35205  void *pPg = pcache1Alloc(nByte);
35206  PgHdr1 *p;
35207  if( pPg ){
35208    p = PAGE_TO_PGHDR1(pCache, pPg);
35209    if( pCache->bPurgeable ){
35210      pCache->pGroup->nCurrentPage++;
35211    }
35212  }else{
35213    p = 0;
35214  }
35215  return p;
35216}
35217
35218/*
35219** Free a page object allocated by pcache1AllocPage().
35220**
35221** The pointer is allowed to be NULL, which is prudent.  But it turns out
35222** that the current implementation happens to never call this routine
35223** with a NULL pointer, so we mark the NULL test with ALWAYS().
35224*/
35225static void pcache1FreePage(PgHdr1 *p){
35226  if( ALWAYS(p) ){
35227    PCache1 *pCache = p->pCache;
35228    if( pCache->bPurgeable ){
35229      pCache->pGroup->nCurrentPage--;
35230    }
35231    pcache1Free(PGHDR1_TO_PAGE(p));
35232  }
35233}
35234
35235/*
35236** Malloc function used by SQLite to obtain space from the buffer configured
35237** using sqlite3_config(SQLITE_CONFIG_PAGECACHE) option. If no such buffer
35238** exists, this function falls back to sqlite3Malloc().
35239*/
35240SQLITE_PRIVATE void *sqlite3PageMalloc(int sz){
35241  return pcache1Alloc(sz);
35242}
35243
35244/*
35245** Free an allocated buffer obtained from sqlite3PageMalloc().
35246*/
35247SQLITE_PRIVATE void sqlite3PageFree(void *p){
35248  pcache1Free(p);
35249}
35250
35251
35252/*
35253** Return true if it desirable to avoid allocating a new page cache
35254** entry.
35255**
35256** If memory was allocated specifically to the page cache using
35257** SQLITE_CONFIG_PAGECACHE but that memory has all been used, then
35258** it is desirable to avoid allocating a new page cache entry because
35259** presumably SQLITE_CONFIG_PAGECACHE was suppose to be sufficient
35260** for all page cache needs and we should not need to spill the
35261** allocation onto the heap.
35262**
35263** Or, the heap is used for all page cache memory put the heap is
35264** under memory pressure, then again it is desirable to avoid
35265** allocating a new page cache entry in order to avoid stressing
35266** the heap even further.
35267*/
35268static int pcache1UnderMemoryPressure(PCache1 *pCache){
35269  if( pcache1.nSlot && pCache->szPage<=pcache1.szSlot ){
35270    return pcache1.bUnderPressure;
35271  }else{
35272    return sqlite3HeapNearlyFull();
35273  }
35274}
35275
35276/******************************************************************************/
35277/******** General Implementation Functions ************************************/
35278
35279/*
35280** This function is used to resize the hash table used by the cache passed
35281** as the first argument.
35282**
35283** The PCache mutex must be held when this function is called.
35284*/
35285static int pcache1ResizeHash(PCache1 *p){
35286  PgHdr1 **apNew;
35287  unsigned int nNew;
35288  unsigned int i;
35289
35290  assert( sqlite3_mutex_held(p->pGroup->mutex) );
35291
35292  nNew = p->nHash*2;
35293  if( nNew<256 ){
35294    nNew = 256;
35295  }
35296
35297  pcache1LeaveMutex(p->pGroup);
35298  if( p->nHash ){ sqlite3BeginBenignMalloc(); }
35299  apNew = (PgHdr1 **)sqlite3_malloc(sizeof(PgHdr1 *)*nNew);
35300  if( p->nHash ){ sqlite3EndBenignMalloc(); }
35301  pcache1EnterMutex(p->pGroup);
35302  if( apNew ){
35303    memset(apNew, 0, sizeof(PgHdr1 *)*nNew);
35304    for(i=0; i<p->nHash; i++){
35305      PgHdr1 *pPage;
35306      PgHdr1 *pNext = p->apHash[i];
35307      while( (pPage = pNext)!=0 ){
35308        unsigned int h = pPage->iKey % nNew;
35309        pNext = pPage->pNext;
35310        pPage->pNext = apNew[h];
35311        apNew[h] = pPage;
35312      }
35313    }
35314    sqlite3_free(p->apHash);
35315    p->apHash = apNew;
35316    p->nHash = nNew;
35317  }
35318
35319  return (p->apHash ? SQLITE_OK : SQLITE_NOMEM);
35320}
35321
35322/*
35323** This function is used internally to remove the page pPage from the
35324** PGroup LRU list, if is part of it. If pPage is not part of the PGroup
35325** LRU list, then this function is a no-op.
35326**
35327** The PGroup mutex must be held when this function is called.
35328**
35329** If pPage is NULL then this routine is a no-op.
35330*/
35331static void pcache1PinPage(PgHdr1 *pPage){
35332  PCache1 *pCache;
35333  PGroup *pGroup;
35334
35335  if( pPage==0 ) return;
35336  pCache = pPage->pCache;
35337  pGroup = pCache->pGroup;
35338  assert( sqlite3_mutex_held(pGroup->mutex) );
35339  if( pPage->pLruNext || pPage==pGroup->pLruTail ){
35340    if( pPage->pLruPrev ){
35341      pPage->pLruPrev->pLruNext = pPage->pLruNext;
35342    }
35343    if( pPage->pLruNext ){
35344      pPage->pLruNext->pLruPrev = pPage->pLruPrev;
35345    }
35346    if( pGroup->pLruHead==pPage ){
35347      pGroup->pLruHead = pPage->pLruNext;
35348    }
35349    if( pGroup->pLruTail==pPage ){
35350      pGroup->pLruTail = pPage->pLruPrev;
35351    }
35352    pPage->pLruNext = 0;
35353    pPage->pLruPrev = 0;
35354    pPage->pCache->nRecyclable--;
35355  }
35356}
35357
35358
35359/*
35360** Remove the page supplied as an argument from the hash table
35361** (PCache1.apHash structure) that it is currently stored in.
35362**
35363** The PGroup mutex must be held when this function is called.
35364*/
35365static void pcache1RemoveFromHash(PgHdr1 *pPage){
35366  unsigned int h;
35367  PCache1 *pCache = pPage->pCache;
35368  PgHdr1 **pp;
35369
35370  assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
35371  h = pPage->iKey % pCache->nHash;
35372  for(pp=&pCache->apHash[h]; (*pp)!=pPage; pp=&(*pp)->pNext);
35373  *pp = (*pp)->pNext;
35374
35375  pCache->nPage--;
35376}
35377
35378/*
35379** If there are currently more than nMaxPage pages allocated, try
35380** to recycle pages to reduce the number allocated to nMaxPage.
35381*/
35382static void pcache1EnforceMaxPage(PGroup *pGroup){
35383  assert( sqlite3_mutex_held(pGroup->mutex) );
35384  while( pGroup->nCurrentPage>pGroup->nMaxPage && pGroup->pLruTail ){
35385    PgHdr1 *p = pGroup->pLruTail;
35386    assert( p->pCache->pGroup==pGroup );
35387    pcache1PinPage(p);
35388    pcache1RemoveFromHash(p);
35389    pcache1FreePage(p);
35390  }
35391}
35392
35393/*
35394** Discard all pages from cache pCache with a page number (key value)
35395** greater than or equal to iLimit. Any pinned pages that meet this
35396** criteria are unpinned before they are discarded.
35397**
35398** The PCache mutex must be held when this function is called.
35399*/
35400static void pcache1TruncateUnsafe(
35401  PCache1 *pCache,             /* The cache to truncate */
35402  unsigned int iLimit          /* Drop pages with this pgno or larger */
35403){
35404  TESTONLY( unsigned int nPage = 0; )  /* To assert pCache->nPage is correct */
35405  unsigned int h;
35406  assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
35407  for(h=0; h<pCache->nHash; h++){
35408    PgHdr1 **pp = &pCache->apHash[h];
35409    PgHdr1 *pPage;
35410    while( (pPage = *pp)!=0 ){
35411      if( pPage->iKey>=iLimit ){
35412        pCache->nPage--;
35413        *pp = pPage->pNext;
35414        pcache1PinPage(pPage);
35415        pcache1FreePage(pPage);
35416      }else{
35417        pp = &pPage->pNext;
35418        TESTONLY( nPage++; )
35419      }
35420    }
35421  }
35422  assert( pCache->nPage==nPage );
35423}
35424
35425/******************************************************************************/
35426/******** sqlite3_pcache Methods **********************************************/
35427
35428/*
35429** Implementation of the sqlite3_pcache.xInit method.
35430*/
35431static int pcache1Init(void *NotUsed){
35432  UNUSED_PARAMETER(NotUsed);
35433  assert( pcache1.isInit==0 );
35434  memset(&pcache1, 0, sizeof(pcache1));
35435  if( sqlite3GlobalConfig.bCoreMutex ){
35436    pcache1.grp.mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_LRU);
35437    pcache1.mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_PMEM);
35438  }
35439  pcache1.grp.mxPinned = 10;
35440  pcache1.isInit = 1;
35441  return SQLITE_OK;
35442}
35443
35444/*
35445** Implementation of the sqlite3_pcache.xShutdown method.
35446** Note that the static mutex allocated in xInit does
35447** not need to be freed.
35448*/
35449static void pcache1Shutdown(void *NotUsed){
35450  UNUSED_PARAMETER(NotUsed);
35451  assert( pcache1.isInit!=0 );
35452  memset(&pcache1, 0, sizeof(pcache1));
35453}
35454
35455/*
35456** Implementation of the sqlite3_pcache.xCreate method.
35457**
35458** Allocate a new cache.
35459*/
35460static sqlite3_pcache *pcache1Create(int szPage, int bPurgeable){
35461  PCache1 *pCache;      /* The newly created page cache */
35462  PGroup *pGroup;       /* The group the new page cache will belong to */
35463  int sz;               /* Bytes of memory required to allocate the new cache */
35464
35465  /*
35466  ** The separateCache variable is true if each PCache has its own private
35467  ** PGroup.  In other words, separateCache is true for mode (1) where no
35468  ** mutexing is required.
35469  **
35470  **   *  Always use separate caches (mode-1) if SQLITE_SEPARATE_CACHE_POOLS
35471  **
35472  **   *  Always use a unified cache (mode-2) if ENABLE_MEMORY_MANAGEMENT
35473  **
35474  **   *  Always use a unified cache in single-threaded applications
35475  **
35476  **   *  Otherwise (if multi-threaded and ENABLE_MEMORY_MANAGEMENT is off)
35477  **      use separate caches (mode-1)
35478  */
35479#ifdef SQLITE_SEPARATE_CACHE_POOLS
35480  const int separateCache = 1;
35481#elif defined(SQLITE_ENABLE_MEMORY_MANAGEMENT) || SQLITE_THREADSAFE==0
35482  const int separateCache = 0;
35483#else
35484  int separateCache = sqlite3GlobalConfig.bCoreMutex>0;
35485#endif
35486
35487  sz = sizeof(PCache1) + sizeof(PGroup)*separateCache;
35488  pCache = (PCache1 *)sqlite3_malloc(sz);
35489  if( pCache ){
35490    memset(pCache, 0, sz);
35491    if( separateCache ){
35492      pGroup = (PGroup*)&pCache[1];
35493      pGroup->mxPinned = 10;
35494    }else{
35495      pGroup = &pcache1_g.grp;
35496    }
35497    pCache->pGroup = pGroup;
35498    pCache->szPage = szPage;
35499    pCache->bPurgeable = (bPurgeable ? 1 : 0);
35500    if( bPurgeable ){
35501      pCache->nMin = 10;
35502      pcache1EnterMutex(pGroup);
35503      pGroup->nMinPage += pCache->nMin;
35504      pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
35505      pcache1LeaveMutex(pGroup);
35506    }
35507  }
35508  return (sqlite3_pcache *)pCache;
35509}
35510
35511/*
35512** Implementation of the sqlite3_pcache.xCachesize method.
35513**
35514** Configure the cache_size limit for a cache.
35515*/
35516static void pcache1Cachesize(sqlite3_pcache *p, int nMax){
35517  PCache1 *pCache = (PCache1 *)p;
35518  if( pCache->bPurgeable ){
35519    PGroup *pGroup = pCache->pGroup;
35520    pcache1EnterMutex(pGroup);
35521    pGroup->nMaxPage += (nMax - pCache->nMax);
35522    pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
35523    pCache->nMax = nMax;
35524    pCache->n90pct = pCache->nMax*9/10;
35525    pcache1EnforceMaxPage(pGroup);
35526    pcache1LeaveMutex(pGroup);
35527  }
35528}
35529
35530/*
35531** Implementation of the sqlite3_pcache.xPagecount method.
35532*/
35533static int pcache1Pagecount(sqlite3_pcache *p){
35534  int n;
35535  PCache1 *pCache = (PCache1*)p;
35536  pcache1EnterMutex(pCache->pGroup);
35537  n = pCache->nPage;
35538  pcache1LeaveMutex(pCache->pGroup);
35539  return n;
35540}
35541
35542/*
35543** Implementation of the sqlite3_pcache.xFetch method.
35544**
35545** Fetch a page by key value.
35546**
35547** Whether or not a new page may be allocated by this function depends on
35548** the value of the createFlag argument.  0 means do not allocate a new
35549** page.  1 means allocate a new page if space is easily available.  2
35550** means to try really hard to allocate a new page.
35551**
35552** For a non-purgeable cache (a cache used as the storage for an in-memory
35553** database) there is really no difference between createFlag 1 and 2.  So
35554** the calling function (pcache.c) will never have a createFlag of 1 on
35555** a non-purgable cache.
35556**
35557** There are three different approaches to obtaining space for a page,
35558** depending on the value of parameter createFlag (which may be 0, 1 or 2).
35559**
35560**   1. Regardless of the value of createFlag, the cache is searched for a
35561**      copy of the requested page. If one is found, it is returned.
35562**
35563**   2. If createFlag==0 and the page is not already in the cache, NULL is
35564**      returned.
35565**
35566**   3. If createFlag is 1, and the page is not already in the cache, then
35567**      return NULL (do not allocate a new page) if any of the following
35568**      conditions are true:
35569**
35570**       (a) the number of pages pinned by the cache is greater than
35571**           PCache1.nMax, or
35572**
35573**       (b) the number of pages pinned by the cache is greater than
35574**           the sum of nMax for all purgeable caches, less the sum of
35575**           nMin for all other purgeable caches, or
35576**
35577**   4. If none of the first three conditions apply and the cache is marked
35578**      as purgeable, and if one of the following is true:
35579**
35580**       (a) The number of pages allocated for the cache is already
35581**           PCache1.nMax, or
35582**
35583**       (b) The number of pages allocated for all purgeable caches is
35584**           already equal to or greater than the sum of nMax for all
35585**           purgeable caches,
35586**
35587**       (c) The system is under memory pressure and wants to avoid
35588**           unnecessary pages cache entry allocations
35589**
35590**      then attempt to recycle a page from the LRU list. If it is the right
35591**      size, return the recycled buffer. Otherwise, free the buffer and
35592**      proceed to step 5.
35593**
35594**   5. Otherwise, allocate and return a new page buffer.
35595*/
35596static void *pcache1Fetch(sqlite3_pcache *p, unsigned int iKey, int createFlag){
35597  int nPinned;
35598  PCache1 *pCache = (PCache1 *)p;
35599  PGroup *pGroup;
35600  PgHdr1 *pPage = 0;
35601
35602  assert( pCache->bPurgeable || createFlag!=1 );
35603  assert( pCache->bPurgeable || pCache->nMin==0 );
35604  assert( pCache->bPurgeable==0 || pCache->nMin==10 );
35605  assert( pCache->nMin==0 || pCache->bPurgeable );
35606  pcache1EnterMutex(pGroup = pCache->pGroup);
35607
35608  /* Step 1: Search the hash table for an existing entry. */
35609  if( pCache->nHash>0 ){
35610    unsigned int h = iKey % pCache->nHash;
35611    for(pPage=pCache->apHash[h]; pPage&&pPage->iKey!=iKey; pPage=pPage->pNext);
35612  }
35613
35614  /* Step 2: Abort if no existing page is found and createFlag is 0 */
35615  if( pPage || createFlag==0 ){
35616    pcache1PinPage(pPage);
35617    goto fetch_out;
35618  }
35619
35620  /* The pGroup local variable will normally be initialized by the
35621  ** pcache1EnterMutex() macro above.  But if SQLITE_MUTEX_OMIT is defined,
35622  ** then pcache1EnterMutex() is a no-op, so we have to initialize the
35623  ** local variable here.  Delaying the initialization of pGroup is an
35624  ** optimization:  The common case is to exit the module before reaching
35625  ** this point.
35626  */
35627#ifdef SQLITE_MUTEX_OMIT
35628  pGroup = pCache->pGroup;
35629#endif
35630
35631
35632  /* Step 3: Abort if createFlag is 1 but the cache is nearly full */
35633  nPinned = pCache->nPage - pCache->nRecyclable;
35634  assert( nPinned>=0 );
35635  assert( pGroup->mxPinned == pGroup->nMaxPage + 10 - pGroup->nMinPage );
35636  assert( pCache->n90pct == pCache->nMax*9/10 );
35637  if( createFlag==1 && (
35638        nPinned>=pGroup->mxPinned
35639     || nPinned>=(int)pCache->n90pct
35640     || pcache1UnderMemoryPressure(pCache)
35641  )){
35642    goto fetch_out;
35643  }
35644
35645  if( pCache->nPage>=pCache->nHash && pcache1ResizeHash(pCache) ){
35646    goto fetch_out;
35647  }
35648
35649  /* Step 4. Try to recycle a page. */
35650  if( pCache->bPurgeable && pGroup->pLruTail && (
35651         (pCache->nPage+1>=pCache->nMax)
35652      || pGroup->nCurrentPage>=pGroup->nMaxPage
35653      || pcache1UnderMemoryPressure(pCache)
35654  )){
35655    PCache1 *pOtherCache;
35656    pPage = pGroup->pLruTail;
35657    pcache1RemoveFromHash(pPage);
35658    pcache1PinPage(pPage);
35659    if( (pOtherCache = pPage->pCache)->szPage!=pCache->szPage ){
35660      pcache1FreePage(pPage);
35661      pPage = 0;
35662    }else{
35663      pGroup->nCurrentPage -=
35664               (pOtherCache->bPurgeable - pCache->bPurgeable);
35665    }
35666  }
35667
35668  /* Step 5. If a usable page buffer has still not been found,
35669  ** attempt to allocate a new one.
35670  */
35671  if( !pPage ){
35672    if( createFlag==1 ) sqlite3BeginBenignMalloc();
35673    pcache1LeaveMutex(pGroup);
35674    pPage = pcache1AllocPage(pCache);
35675    pcache1EnterMutex(pGroup);
35676    if( createFlag==1 ) sqlite3EndBenignMalloc();
35677  }
35678
35679  if( pPage ){
35680    unsigned int h = iKey % pCache->nHash;
35681    pCache->nPage++;
35682    pPage->iKey = iKey;
35683    pPage->pNext = pCache->apHash[h];
35684    pPage->pCache = pCache;
35685    pPage->pLruPrev = 0;
35686    pPage->pLruNext = 0;
35687    *(void **)(PGHDR1_TO_PAGE(pPage)) = 0;
35688    pCache->apHash[h] = pPage;
35689  }
35690
35691fetch_out:
35692  if( pPage && iKey>pCache->iMaxKey ){
35693    pCache->iMaxKey = iKey;
35694  }
35695  pcache1LeaveMutex(pGroup);
35696  return (pPage ? PGHDR1_TO_PAGE(pPage) : 0);
35697}
35698
35699
35700/*
35701** Implementation of the sqlite3_pcache.xUnpin method.
35702**
35703** Mark a page as unpinned (eligible for asynchronous recycling).
35704*/
35705static void pcache1Unpin(sqlite3_pcache *p, void *pPg, int reuseUnlikely){
35706  PCache1 *pCache = (PCache1 *)p;
35707  PgHdr1 *pPage = PAGE_TO_PGHDR1(pCache, pPg);
35708  PGroup *pGroup = pCache->pGroup;
35709
35710  assert( pPage->pCache==pCache );
35711  pcache1EnterMutex(pGroup);
35712
35713  /* It is an error to call this function if the page is already
35714  ** part of the PGroup LRU list.
35715  */
35716  assert( pPage->pLruPrev==0 && pPage->pLruNext==0 );
35717  assert( pGroup->pLruHead!=pPage && pGroup->pLruTail!=pPage );
35718
35719  if( reuseUnlikely || pGroup->nCurrentPage>pGroup->nMaxPage ){
35720    pcache1RemoveFromHash(pPage);
35721    pcache1FreePage(pPage);
35722  }else{
35723    /* Add the page to the PGroup LRU list. */
35724    if( pGroup->pLruHead ){
35725      pGroup->pLruHead->pLruPrev = pPage;
35726      pPage->pLruNext = pGroup->pLruHead;
35727      pGroup->pLruHead = pPage;
35728    }else{
35729      pGroup->pLruTail = pPage;
35730      pGroup->pLruHead = pPage;
35731    }
35732    pCache->nRecyclable++;
35733  }
35734
35735  pcache1LeaveMutex(pCache->pGroup);
35736}
35737
35738/*
35739** Implementation of the sqlite3_pcache.xRekey method.
35740*/
35741static void pcache1Rekey(
35742  sqlite3_pcache *p,
35743  void *pPg,
35744  unsigned int iOld,
35745  unsigned int iNew
35746){
35747  PCache1 *pCache = (PCache1 *)p;
35748  PgHdr1 *pPage = PAGE_TO_PGHDR1(pCache, pPg);
35749  PgHdr1 **pp;
35750  unsigned int h;
35751  assert( pPage->iKey==iOld );
35752  assert( pPage->pCache==pCache );
35753
35754  pcache1EnterMutex(pCache->pGroup);
35755
35756  h = iOld%pCache->nHash;
35757  pp = &pCache->apHash[h];
35758  while( (*pp)!=pPage ){
35759    pp = &(*pp)->pNext;
35760  }
35761  *pp = pPage->pNext;
35762
35763  h = iNew%pCache->nHash;
35764  pPage->iKey = iNew;
35765  pPage->pNext = pCache->apHash[h];
35766  pCache->apHash[h] = pPage;
35767  if( iNew>pCache->iMaxKey ){
35768    pCache->iMaxKey = iNew;
35769  }
35770
35771  pcache1LeaveMutex(pCache->pGroup);
35772}
35773
35774/*
35775** Implementation of the sqlite3_pcache.xTruncate method.
35776**
35777** Discard all unpinned pages in the cache with a page number equal to
35778** or greater than parameter iLimit. Any pinned pages with a page number
35779** equal to or greater than iLimit are implicitly unpinned.
35780*/
35781static void pcache1Truncate(sqlite3_pcache *p, unsigned int iLimit){
35782  PCache1 *pCache = (PCache1 *)p;
35783  pcache1EnterMutex(pCache->pGroup);
35784  if( iLimit<=pCache->iMaxKey ){
35785    pcache1TruncateUnsafe(pCache, iLimit);
35786    pCache->iMaxKey = iLimit-1;
35787  }
35788  pcache1LeaveMutex(pCache->pGroup);
35789}
35790
35791/*
35792** Implementation of the sqlite3_pcache.xDestroy method.
35793**
35794** Destroy a cache allocated using pcache1Create().
35795*/
35796static void pcache1Destroy(sqlite3_pcache *p){
35797  PCache1 *pCache = (PCache1 *)p;
35798  PGroup *pGroup = pCache->pGroup;
35799  assert( pCache->bPurgeable || (pCache->nMax==0 && pCache->nMin==0) );
35800  pcache1EnterMutex(pGroup);
35801  pcache1TruncateUnsafe(pCache, 0);
35802  pGroup->nMaxPage -= pCache->nMax;
35803  pGroup->nMinPage -= pCache->nMin;
35804  pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
35805  pcache1EnforceMaxPage(pGroup);
35806  pcache1LeaveMutex(pGroup);
35807  sqlite3_free(pCache->apHash);
35808  sqlite3_free(pCache);
35809}
35810
35811/*
35812** This function is called during initialization (sqlite3_initialize()) to
35813** install the default pluggable cache module, assuming the user has not
35814** already provided an alternative.
35815*/
35816SQLITE_PRIVATE void sqlite3PCacheSetDefault(void){
35817  static const sqlite3_pcache_methods defaultMethods = {
35818    0,                       /* pArg */
35819    pcache1Init,             /* xInit */
35820    pcache1Shutdown,         /* xShutdown */
35821    pcache1Create,           /* xCreate */
35822    pcache1Cachesize,        /* xCachesize */
35823    pcache1Pagecount,        /* xPagecount */
35824    pcache1Fetch,            /* xFetch */
35825    pcache1Unpin,            /* xUnpin */
35826    pcache1Rekey,            /* xRekey */
35827    pcache1Truncate,         /* xTruncate */
35828    pcache1Destroy           /* xDestroy */
35829  };
35830  sqlite3_config(SQLITE_CONFIG_PCACHE, &defaultMethods);
35831}
35832
35833#ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
35834/*
35835** This function is called to free superfluous dynamically allocated memory
35836** held by the pager system. Memory in use by any SQLite pager allocated
35837** by the current thread may be sqlite3_free()ed.
35838**
35839** nReq is the number of bytes of memory required. Once this much has
35840** been released, the function returns. The return value is the total number
35841** of bytes of memory released.
35842*/
35843SQLITE_PRIVATE int sqlite3PcacheReleaseMemory(int nReq){
35844  int nFree = 0;
35845  assert( sqlite3_mutex_notheld(pcache1.grp.mutex) );
35846  assert( sqlite3_mutex_notheld(pcache1.mutex) );
35847  if( pcache1.pStart==0 ){
35848    PgHdr1 *p;
35849    pcache1EnterMutex(&pcache1.grp);
35850    while( (nReq<0 || nFree<nReq) && ((p=pcache1.grp.pLruTail)!=0) ){
35851      nFree += pcache1MemSize(PGHDR1_TO_PAGE(p));
35852      pcache1PinPage(p);
35853      pcache1RemoveFromHash(p);
35854      pcache1FreePage(p);
35855    }
35856    pcache1LeaveMutex(&pcache1.grp);
35857  }
35858  return nFree;
35859}
35860#endif /* SQLITE_ENABLE_MEMORY_MANAGEMENT */
35861
35862#ifdef SQLITE_TEST
35863/*
35864** This function is used by test procedures to inspect the internal state
35865** of the global cache.
35866*/
35867SQLITE_PRIVATE void sqlite3PcacheStats(
35868  int *pnCurrent,      /* OUT: Total number of pages cached */
35869  int *pnMax,          /* OUT: Global maximum cache size */
35870  int *pnMin,          /* OUT: Sum of PCache1.nMin for purgeable caches */
35871  int *pnRecyclable    /* OUT: Total number of pages available for recycling */
35872){
35873  PgHdr1 *p;
35874  int nRecyclable = 0;
35875  for(p=pcache1.grp.pLruHead; p; p=p->pLruNext){
35876    nRecyclable++;
35877  }
35878  *pnCurrent = pcache1.grp.nCurrentPage;
35879  *pnMax = pcache1.grp.nMaxPage;
35880  *pnMin = pcache1.grp.nMinPage;
35881  *pnRecyclable = nRecyclable;
35882}
35883#endif
35884
35885/************** End of pcache1.c *********************************************/
35886/************** Begin file rowset.c ******************************************/
35887/*
35888** 2008 December 3
35889**
35890** The author disclaims copyright to this source code.  In place of
35891** a legal notice, here is a blessing:
35892**
35893**    May you do good and not evil.
35894**    May you find forgiveness for yourself and forgive others.
35895**    May you share freely, never taking more than you give.
35896**
35897*************************************************************************
35898**
35899** This module implements an object we call a "RowSet".
35900**
35901** The RowSet object is a collection of rowids.  Rowids
35902** are inserted into the RowSet in an arbitrary order.  Inserts
35903** can be intermixed with tests to see if a given rowid has been
35904** previously inserted into the RowSet.
35905**
35906** After all inserts are finished, it is possible to extract the
35907** elements of the RowSet in sorted order.  Once this extraction
35908** process has started, no new elements may be inserted.
35909**
35910** Hence, the primitive operations for a RowSet are:
35911**
35912**    CREATE
35913**    INSERT
35914**    TEST
35915**    SMALLEST
35916**    DESTROY
35917**
35918** The CREATE and DESTROY primitives are the constructor and destructor,
35919** obviously.  The INSERT primitive adds a new element to the RowSet.
35920** TEST checks to see if an element is already in the RowSet.  SMALLEST
35921** extracts the least value from the RowSet.
35922**
35923** The INSERT primitive might allocate additional memory.  Memory is
35924** allocated in chunks so most INSERTs do no allocation.  There is an
35925** upper bound on the size of allocated memory.  No memory is freed
35926** until DESTROY.
35927**
35928** The TEST primitive includes a "batch" number.  The TEST primitive
35929** will only see elements that were inserted before the last change
35930** in the batch number.  In other words, if an INSERT occurs between
35931** two TESTs where the TESTs have the same batch nubmer, then the
35932** value added by the INSERT will not be visible to the second TEST.
35933** The initial batch number is zero, so if the very first TEST contains
35934** a non-zero batch number, it will see all prior INSERTs.
35935**
35936** No INSERTs may occurs after a SMALLEST.  An assertion will fail if
35937** that is attempted.
35938**
35939** The cost of an INSERT is roughly constant.  (Sometime new memory
35940** has to be allocated on an INSERT.)  The cost of a TEST with a new
35941** batch number is O(NlogN) where N is the number of elements in the RowSet.
35942** The cost of a TEST using the same batch number is O(logN).  The cost
35943** of the first SMALLEST is O(NlogN).  Second and subsequent SMALLEST
35944** primitives are constant time.  The cost of DESTROY is O(N).
35945**
35946** There is an added cost of O(N) when switching between TEST and
35947** SMALLEST primitives.
35948*/
35949
35950
35951/*
35952** Target size for allocation chunks.
35953*/
35954#define ROWSET_ALLOCATION_SIZE 1024
35955
35956/*
35957** The number of rowset entries per allocation chunk.
35958*/
35959#define ROWSET_ENTRY_PER_CHUNK  \
35960                       ((ROWSET_ALLOCATION_SIZE-8)/sizeof(struct RowSetEntry))
35961
35962/*
35963** Each entry in a RowSet is an instance of the following object.
35964*/
35965struct RowSetEntry {
35966  i64 v;                        /* ROWID value for this entry */
35967  struct RowSetEntry *pRight;   /* Right subtree (larger entries) or list */
35968  struct RowSetEntry *pLeft;    /* Left subtree (smaller entries) */
35969};
35970
35971/*
35972** RowSetEntry objects are allocated in large chunks (instances of the
35973** following structure) to reduce memory allocation overhead.  The
35974** chunks are kept on a linked list so that they can be deallocated
35975** when the RowSet is destroyed.
35976*/
35977struct RowSetChunk {
35978  struct RowSetChunk *pNextChunk;        /* Next chunk on list of them all */
35979  struct RowSetEntry aEntry[ROWSET_ENTRY_PER_CHUNK]; /* Allocated entries */
35980};
35981
35982/*
35983** A RowSet in an instance of the following structure.
35984**
35985** A typedef of this structure if found in sqliteInt.h.
35986*/
35987struct RowSet {
35988  struct RowSetChunk *pChunk;    /* List of all chunk allocations */
35989  sqlite3 *db;                   /* The database connection */
35990  struct RowSetEntry *pEntry;    /* List of entries using pRight */
35991  struct RowSetEntry *pLast;     /* Last entry on the pEntry list */
35992  struct RowSetEntry *pFresh;    /* Source of new entry objects */
35993  struct RowSetEntry *pTree;     /* Binary tree of entries */
35994  u16 nFresh;                    /* Number of objects on pFresh */
35995  u8 isSorted;                   /* True if pEntry is sorted */
35996  u8 iBatch;                     /* Current insert batch */
35997};
35998
35999/*
36000** Turn bulk memory into a RowSet object.  N bytes of memory
36001** are available at pSpace.  The db pointer is used as a memory context
36002** for any subsequent allocations that need to occur.
36003** Return a pointer to the new RowSet object.
36004**
36005** It must be the case that N is sufficient to make a Rowset.  If not
36006** an assertion fault occurs.
36007**
36008** If N is larger than the minimum, use the surplus as an initial
36009** allocation of entries available to be filled.
36010*/
36011SQLITE_PRIVATE RowSet *sqlite3RowSetInit(sqlite3 *db, void *pSpace, unsigned int N){
36012  RowSet *p;
36013  assert( N >= ROUND8(sizeof(*p)) );
36014  p = pSpace;
36015  p->pChunk = 0;
36016  p->db = db;
36017  p->pEntry = 0;
36018  p->pLast = 0;
36019  p->pTree = 0;
36020  p->pFresh = (struct RowSetEntry*)(ROUND8(sizeof(*p)) + (char*)p);
36021  p->nFresh = (u16)((N - ROUND8(sizeof(*p)))/sizeof(struct RowSetEntry));
36022  p->isSorted = 1;
36023  p->iBatch = 0;
36024  return p;
36025}
36026
36027/*
36028** Deallocate all chunks from a RowSet.  This frees all memory that
36029** the RowSet has allocated over its lifetime.  This routine is
36030** the destructor for the RowSet.
36031*/
36032SQLITE_PRIVATE void sqlite3RowSetClear(RowSet *p){
36033  struct RowSetChunk *pChunk, *pNextChunk;
36034  for(pChunk=p->pChunk; pChunk; pChunk = pNextChunk){
36035    pNextChunk = pChunk->pNextChunk;
36036    sqlite3DbFree(p->db, pChunk);
36037  }
36038  p->pChunk = 0;
36039  p->nFresh = 0;
36040  p->pEntry = 0;
36041  p->pLast = 0;
36042  p->pTree = 0;
36043  p->isSorted = 1;
36044}
36045
36046/*
36047** Insert a new value into a RowSet.
36048**
36049** The mallocFailed flag of the database connection is set if a
36050** memory allocation fails.
36051*/
36052SQLITE_PRIVATE void sqlite3RowSetInsert(RowSet *p, i64 rowid){
36053  struct RowSetEntry *pEntry;  /* The new entry */
36054  struct RowSetEntry *pLast;   /* The last prior entry */
36055  assert( p!=0 );
36056  if( p->nFresh==0 ){
36057    struct RowSetChunk *pNew;
36058    pNew = sqlite3DbMallocRaw(p->db, sizeof(*pNew));
36059    if( pNew==0 ){
36060      return;
36061    }
36062    pNew->pNextChunk = p->pChunk;
36063    p->pChunk = pNew;
36064    p->pFresh = pNew->aEntry;
36065    p->nFresh = ROWSET_ENTRY_PER_CHUNK;
36066  }
36067  pEntry = p->pFresh++;
36068  p->nFresh--;
36069  pEntry->v = rowid;
36070  pEntry->pRight = 0;
36071  pLast = p->pLast;
36072  if( pLast ){
36073    if( p->isSorted && rowid<=pLast->v ){
36074      p->isSorted = 0;
36075    }
36076    pLast->pRight = pEntry;
36077  }else{
36078    assert( p->pEntry==0 ); /* Fires if INSERT after SMALLEST */
36079    p->pEntry = pEntry;
36080  }
36081  p->pLast = pEntry;
36082}
36083
36084/*
36085** Merge two lists of RowSetEntry objects.  Remove duplicates.
36086**
36087** The input lists are connected via pRight pointers and are
36088** assumed to each already be in sorted order.
36089*/
36090static struct RowSetEntry *rowSetMerge(
36091  struct RowSetEntry *pA,    /* First sorted list to be merged */
36092  struct RowSetEntry *pB     /* Second sorted list to be merged */
36093){
36094  struct RowSetEntry head;
36095  struct RowSetEntry *pTail;
36096
36097  pTail = &head;
36098  while( pA && pB ){
36099    assert( pA->pRight==0 || pA->v<=pA->pRight->v );
36100    assert( pB->pRight==0 || pB->v<=pB->pRight->v );
36101    if( pA->v<pB->v ){
36102      pTail->pRight = pA;
36103      pA = pA->pRight;
36104      pTail = pTail->pRight;
36105    }else if( pB->v<pA->v ){
36106      pTail->pRight = pB;
36107      pB = pB->pRight;
36108      pTail = pTail->pRight;
36109    }else{
36110      pA = pA->pRight;
36111    }
36112  }
36113  if( pA ){
36114    assert( pA->pRight==0 || pA->v<=pA->pRight->v );
36115    pTail->pRight = pA;
36116  }else{
36117    assert( pB==0 || pB->pRight==0 || pB->v<=pB->pRight->v );
36118    pTail->pRight = pB;
36119  }
36120  return head.pRight;
36121}
36122
36123/*
36124** Sort all elements on the pEntry list of the RowSet into ascending order.
36125*/
36126static void rowSetSort(RowSet *p){
36127  unsigned int i;
36128  struct RowSetEntry *pEntry;
36129  struct RowSetEntry *aBucket[40];
36130
36131  assert( p->isSorted==0 );
36132  memset(aBucket, 0, sizeof(aBucket));
36133  while( p->pEntry ){
36134    pEntry = p->pEntry;
36135    p->pEntry = pEntry->pRight;
36136    pEntry->pRight = 0;
36137    for(i=0; aBucket[i]; i++){
36138      pEntry = rowSetMerge(aBucket[i], pEntry);
36139      aBucket[i] = 0;
36140    }
36141    aBucket[i] = pEntry;
36142  }
36143  pEntry = 0;
36144  for(i=0; i<sizeof(aBucket)/sizeof(aBucket[0]); i++){
36145    pEntry = rowSetMerge(pEntry, aBucket[i]);
36146  }
36147  p->pEntry = pEntry;
36148  p->pLast = 0;
36149  p->isSorted = 1;
36150}
36151
36152
36153/*
36154** The input, pIn, is a binary tree (or subtree) of RowSetEntry objects.
36155** Convert this tree into a linked list connected by the pRight pointers
36156** and return pointers to the first and last elements of the new list.
36157*/
36158static void rowSetTreeToList(
36159  struct RowSetEntry *pIn,         /* Root of the input tree */
36160  struct RowSetEntry **ppFirst,    /* Write head of the output list here */
36161  struct RowSetEntry **ppLast      /* Write tail of the output list here */
36162){
36163  assert( pIn!=0 );
36164  if( pIn->pLeft ){
36165    struct RowSetEntry *p;
36166    rowSetTreeToList(pIn->pLeft, ppFirst, &p);
36167    p->pRight = pIn;
36168  }else{
36169    *ppFirst = pIn;
36170  }
36171  if( pIn->pRight ){
36172    rowSetTreeToList(pIn->pRight, &pIn->pRight, ppLast);
36173  }else{
36174    *ppLast = pIn;
36175  }
36176  assert( (*ppLast)->pRight==0 );
36177}
36178
36179
36180/*
36181** Convert a sorted list of elements (connected by pRight) into a binary
36182** tree with depth of iDepth.  A depth of 1 means the tree contains a single
36183** node taken from the head of *ppList.  A depth of 2 means a tree with
36184** three nodes.  And so forth.
36185**
36186** Use as many entries from the input list as required and update the
36187** *ppList to point to the unused elements of the list.  If the input
36188** list contains too few elements, then construct an incomplete tree
36189** and leave *ppList set to NULL.
36190**
36191** Return a pointer to the root of the constructed binary tree.
36192*/
36193static struct RowSetEntry *rowSetNDeepTree(
36194  struct RowSetEntry **ppList,
36195  int iDepth
36196){
36197  struct RowSetEntry *p;         /* Root of the new tree */
36198  struct RowSetEntry *pLeft;     /* Left subtree */
36199  if( *ppList==0 ){
36200    return 0;
36201  }
36202  if( iDepth==1 ){
36203    p = *ppList;
36204    *ppList = p->pRight;
36205    p->pLeft = p->pRight = 0;
36206    return p;
36207  }
36208  pLeft = rowSetNDeepTree(ppList, iDepth-1);
36209  p = *ppList;
36210  if( p==0 ){
36211    return pLeft;
36212  }
36213  p->pLeft = pLeft;
36214  *ppList = p->pRight;
36215  p->pRight = rowSetNDeepTree(ppList, iDepth-1);
36216  return p;
36217}
36218
36219/*
36220** Convert a sorted list of elements into a binary tree. Make the tree
36221** as deep as it needs to be in order to contain the entire list.
36222*/
36223static struct RowSetEntry *rowSetListToTree(struct RowSetEntry *pList){
36224  int iDepth;           /* Depth of the tree so far */
36225  struct RowSetEntry *p;       /* Current tree root */
36226  struct RowSetEntry *pLeft;   /* Left subtree */
36227
36228  assert( pList!=0 );
36229  p = pList;
36230  pList = p->pRight;
36231  p->pLeft = p->pRight = 0;
36232  for(iDepth=1; pList; iDepth++){
36233    pLeft = p;
36234    p = pList;
36235    pList = p->pRight;
36236    p->pLeft = pLeft;
36237    p->pRight = rowSetNDeepTree(&pList, iDepth);
36238  }
36239  return p;
36240}
36241
36242/*
36243** Convert the list in p->pEntry into a sorted list if it is not
36244** sorted already.  If there is a binary tree on p->pTree, then
36245** convert it into a list too and merge it into the p->pEntry list.
36246*/
36247static void rowSetToList(RowSet *p){
36248  if( !p->isSorted ){
36249    rowSetSort(p);
36250  }
36251  if( p->pTree ){
36252    struct RowSetEntry *pHead, *pTail;
36253    rowSetTreeToList(p->pTree, &pHead, &pTail);
36254    p->pTree = 0;
36255    p->pEntry = rowSetMerge(p->pEntry, pHead);
36256  }
36257}
36258
36259/*
36260** Extract the smallest element from the RowSet.
36261** Write the element into *pRowid.  Return 1 on success.  Return
36262** 0 if the RowSet is already empty.
36263**
36264** After this routine has been called, the sqlite3RowSetInsert()
36265** routine may not be called again.
36266*/
36267SQLITE_PRIVATE int sqlite3RowSetNext(RowSet *p, i64 *pRowid){
36268  rowSetToList(p);
36269  if( p->pEntry ){
36270    *pRowid = p->pEntry->v;
36271    p->pEntry = p->pEntry->pRight;
36272    if( p->pEntry==0 ){
36273      sqlite3RowSetClear(p);
36274    }
36275    return 1;
36276  }else{
36277    return 0;
36278  }
36279}
36280
36281/*
36282** Check to see if element iRowid was inserted into the the rowset as
36283** part of any insert batch prior to iBatch.  Return 1 or 0.
36284*/
36285SQLITE_PRIVATE int sqlite3RowSetTest(RowSet *pRowSet, u8 iBatch, sqlite3_int64 iRowid){
36286  struct RowSetEntry *p;
36287  if( iBatch!=pRowSet->iBatch ){
36288    if( pRowSet->pEntry ){
36289      rowSetToList(pRowSet);
36290      pRowSet->pTree = rowSetListToTree(pRowSet->pEntry);
36291      pRowSet->pEntry = 0;
36292      pRowSet->pLast = 0;
36293    }
36294    pRowSet->iBatch = iBatch;
36295  }
36296  p = pRowSet->pTree;
36297  while( p ){
36298    if( p->v<iRowid ){
36299      p = p->pRight;
36300    }else if( p->v>iRowid ){
36301      p = p->pLeft;
36302    }else{
36303      return 1;
36304    }
36305  }
36306  return 0;
36307}
36308
36309/************** End of rowset.c **********************************************/
36310/************** Begin file pager.c *******************************************/
36311/*
36312** 2001 September 15
36313**
36314** The author disclaims copyright to this source code.  In place of
36315** a legal notice, here is a blessing:
36316**
36317**    May you do good and not evil.
36318**    May you find forgiveness for yourself and forgive others.
36319**    May you share freely, never taking more than you give.
36320**
36321*************************************************************************
36322** This is the implementation of the page cache subsystem or "pager".
36323**
36324** The pager is used to access a database disk file.  It implements
36325** atomic commit and rollback through the use of a journal file that
36326** is separate from the database file.  The pager also implements file
36327** locking to prevent two processes from writing the same database
36328** file simultaneously, or one process from reading the database while
36329** another is writing.
36330*/
36331#ifndef SQLITE_OMIT_DISKIO
36332/************** Include wal.h in the middle of pager.c ***********************/
36333/************** Begin file wal.h *********************************************/
36334/*
36335** 2010 February 1
36336**
36337** The author disclaims copyright to this source code.  In place of
36338** a legal notice, here is a blessing:
36339**
36340**    May you do good and not evil.
36341**    May you find forgiveness for yourself and forgive others.
36342**    May you share freely, never taking more than you give.
36343**
36344*************************************************************************
36345** This header file defines the interface to the write-ahead logging
36346** system. Refer to the comments below and the header comment attached to
36347** the implementation of each function in log.c for further details.
36348*/
36349
36350#ifndef _WAL_H_
36351#define _WAL_H_
36352
36353
36354#ifdef SQLITE_OMIT_WAL
36355# define sqlite3WalOpen(x,y,z)                   0
36356# define sqlite3WalClose(w,x,y,z)                0
36357# define sqlite3WalBeginReadTransaction(y,z)     0
36358# define sqlite3WalEndReadTransaction(z)
36359# define sqlite3WalRead(v,w,x,y,z)               0
36360# define sqlite3WalDbsize(y)                     0
36361# define sqlite3WalBeginWriteTransaction(y)      0
36362# define sqlite3WalEndWriteTransaction(x)        0
36363# define sqlite3WalUndo(x,y,z)                   0
36364# define sqlite3WalSavepoint(y,z)
36365# define sqlite3WalSavepointUndo(y,z)            0
36366# define sqlite3WalFrames(u,v,w,x,y,z)           0
36367# define sqlite3WalCheckpoint(r,s,t,u,v,w,x,y,z) 0
36368# define sqlite3WalCallback(z)                   0
36369# define sqlite3WalExclusiveMode(y,z)            0
36370# define sqlite3WalHeapMemory(z)                 0
36371#else
36372
36373#define WAL_SAVEPOINT_NDATA 4
36374
36375/* Connection to a write-ahead log (WAL) file.
36376** There is one object of this type for each pager.
36377*/
36378typedef struct Wal Wal;
36379
36380/* Open and close a connection to a write-ahead log. */
36381SQLITE_PRIVATE int sqlite3WalOpen(sqlite3_vfs*, sqlite3_file*, const char *zName, int, Wal**);
36382SQLITE_PRIVATE int sqlite3WalClose(Wal *pWal, int sync_flags, int, u8 *);
36383
36384/* Used by readers to open (lock) and close (unlock) a snapshot.  A
36385** snapshot is like a read-transaction.  It is the state of the database
36386** at an instant in time.  sqlite3WalOpenSnapshot gets a read lock and
36387** preserves the current state even if the other threads or processes
36388** write to or checkpoint the WAL.  sqlite3WalCloseSnapshot() closes the
36389** transaction and releases the lock.
36390*/
36391SQLITE_PRIVATE int sqlite3WalBeginReadTransaction(Wal *pWal, int *);
36392SQLITE_PRIVATE void sqlite3WalEndReadTransaction(Wal *pWal);
36393
36394/* Read a page from the write-ahead log, if it is present. */
36395SQLITE_PRIVATE int sqlite3WalRead(Wal *pWal, Pgno pgno, int *pInWal, int nOut, u8 *pOut);
36396
36397/* If the WAL is not empty, return the size of the database. */
36398SQLITE_PRIVATE Pgno sqlite3WalDbsize(Wal *pWal);
36399
36400/* Obtain or release the WRITER lock. */
36401SQLITE_PRIVATE int sqlite3WalBeginWriteTransaction(Wal *pWal);
36402SQLITE_PRIVATE int sqlite3WalEndWriteTransaction(Wal *pWal);
36403
36404/* Undo any frames written (but not committed) to the log */
36405SQLITE_PRIVATE int sqlite3WalUndo(Wal *pWal, int (*xUndo)(void *, Pgno), void *pUndoCtx);
36406
36407/* Return an integer that records the current (uncommitted) write
36408** position in the WAL */
36409SQLITE_PRIVATE void sqlite3WalSavepoint(Wal *pWal, u32 *aWalData);
36410
36411/* Move the write position of the WAL back to iFrame.  Called in
36412** response to a ROLLBACK TO command. */
36413SQLITE_PRIVATE int sqlite3WalSavepointUndo(Wal *pWal, u32 *aWalData);
36414
36415/* Write a frame or frames to the log. */
36416SQLITE_PRIVATE int sqlite3WalFrames(Wal *pWal, int, PgHdr *, Pgno, int, int);
36417
36418/* Copy pages from the log to the database file */
36419SQLITE_PRIVATE int sqlite3WalCheckpoint(
36420  Wal *pWal,                      /* Write-ahead log connection */
36421  int eMode,                      /* One of PASSIVE, FULL and RESTART */
36422  int (*xBusy)(void*),            /* Function to call when busy */
36423  void *pBusyArg,                 /* Context argument for xBusyHandler */
36424  int sync_flags,                 /* Flags to sync db file with (or 0) */
36425  int nBuf,                       /* Size of buffer nBuf */
36426  u8 *zBuf,                       /* Temporary buffer to use */
36427  int *pnLog,                     /* OUT: Number of frames in WAL */
36428  int *pnCkpt                     /* OUT: Number of backfilled frames in WAL */
36429);
36430
36431/* Return the value to pass to a sqlite3_wal_hook callback, the
36432** number of frames in the WAL at the point of the last commit since
36433** sqlite3WalCallback() was called.  If no commits have occurred since
36434** the last call, then return 0.
36435*/
36436SQLITE_PRIVATE int sqlite3WalCallback(Wal *pWal);
36437
36438/* Tell the wal layer that an EXCLUSIVE lock has been obtained (or released)
36439** by the pager layer on the database file.
36440*/
36441SQLITE_PRIVATE int sqlite3WalExclusiveMode(Wal *pWal, int op);
36442
36443/* Return true if the argument is non-NULL and the WAL module is using
36444** heap-memory for the wal-index. Otherwise, if the argument is NULL or the
36445** WAL module is using shared-memory, return false.
36446*/
36447SQLITE_PRIVATE int sqlite3WalHeapMemory(Wal *pWal);
36448
36449#endif /* ifndef SQLITE_OMIT_WAL */
36450#endif /* _WAL_H_ */
36451
36452/************** End of wal.h *************************************************/
36453/************** Continuing where we left off in pager.c **********************/
36454
36455
36456/******************* NOTES ON THE DESIGN OF THE PAGER ************************
36457**
36458** This comment block describes invariants that hold when using a rollback
36459** journal.  These invariants do not apply for journal_mode=WAL,
36460** journal_mode=MEMORY, or journal_mode=OFF.
36461**
36462** Within this comment block, a page is deemed to have been synced
36463** automatically as soon as it is written when PRAGMA synchronous=OFF.
36464** Otherwise, the page is not synced until the xSync method of the VFS
36465** is called successfully on the file containing the page.
36466**
36467** Definition:  A page of the database file is said to be "overwriteable" if
36468** one or more of the following are true about the page:
36469**
36470**     (a)  The original content of the page as it was at the beginning of
36471**          the transaction has been written into the rollback journal and
36472**          synced.
36473**
36474**     (b)  The page was a freelist leaf page at the start of the transaction.
36475**
36476**     (c)  The page number is greater than the largest page that existed in
36477**          the database file at the start of the transaction.
36478**
36479** (1) A page of the database file is never overwritten unless one of the
36480**     following are true:
36481**
36482**     (a) The page and all other pages on the same sector are overwriteable.
36483**
36484**     (b) The atomic page write optimization is enabled, and the entire
36485**         transaction other than the update of the transaction sequence
36486**         number consists of a single page change.
36487**
36488** (2) The content of a page written into the rollback journal exactly matches
36489**     both the content in the database when the rollback journal was written
36490**     and the content in the database at the beginning of the current
36491**     transaction.
36492**
36493** (3) Writes to the database file are an integer multiple of the page size
36494**     in length and are aligned on a page boundary.
36495**
36496** (4) Reads from the database file are either aligned on a page boundary and
36497**     an integer multiple of the page size in length or are taken from the
36498**     first 100 bytes of the database file.
36499**
36500** (5) All writes to the database file are synced prior to the rollback journal
36501**     being deleted, truncated, or zeroed.
36502**
36503** (6) If a master journal file is used, then all writes to the database file
36504**     are synced prior to the master journal being deleted.
36505**
36506** Definition: Two databases (or the same database at two points it time)
36507** are said to be "logically equivalent" if they give the same answer to
36508** all queries.  Note in particular the the content of freelist leaf
36509** pages can be changed arbitarily without effecting the logical equivalence
36510** of the database.
36511**
36512** (7) At any time, if any subset, including the empty set and the total set,
36513**     of the unsynced changes to a rollback journal are removed and the
36514**     journal is rolled back, the resulting database file will be logical
36515**     equivalent to the database file at the beginning of the transaction.
36516**
36517** (8) When a transaction is rolled back, the xTruncate method of the VFS
36518**     is called to restore the database file to the same size it was at
36519**     the beginning of the transaction.  (In some VFSes, the xTruncate
36520**     method is a no-op, but that does not change the fact the SQLite will
36521**     invoke it.)
36522**
36523** (9) Whenever the database file is modified, at least one bit in the range
36524**     of bytes from 24 through 39 inclusive will be changed prior to releasing
36525**     the EXCLUSIVE lock, thus signaling other connections on the same
36526**     database to flush their caches.
36527**
36528** (10) The pattern of bits in bytes 24 through 39 shall not repeat in less
36529**      than one billion transactions.
36530**
36531** (11) A database file is well-formed at the beginning and at the conclusion
36532**      of every transaction.
36533**
36534** (12) An EXCLUSIVE lock is held on the database file when writing to
36535**      the database file.
36536**
36537** (13) A SHARED lock is held on the database file while reading any
36538**      content out of the database file.
36539**
36540******************************************************************************/
36541
36542/*
36543** Macros for troubleshooting.  Normally turned off
36544*/
36545#if 0
36546int sqlite3PagerTrace=1;  /* True to enable tracing */
36547#define sqlite3DebugPrintf printf
36548#define PAGERTRACE(X)     if( sqlite3PagerTrace ){ sqlite3DebugPrintf X; }
36549#else
36550#define PAGERTRACE(X)
36551#endif
36552
36553/*
36554** The following two macros are used within the PAGERTRACE() macros above
36555** to print out file-descriptors.
36556**
36557** PAGERID() takes a pointer to a Pager struct as its argument. The
36558** associated file-descriptor is returned. FILEHANDLEID() takes an sqlite3_file
36559** struct as its argument.
36560*/
36561#define PAGERID(p) ((int)(p->fd))
36562#define FILEHANDLEID(fd) ((int)fd)
36563
36564/*
36565** The Pager.eState variable stores the current 'state' of a pager. A
36566** pager may be in any one of the seven states shown in the following
36567** state diagram.
36568**
36569**                            OPEN <------+------+
36570**                              |         |      |
36571**                              V         |      |
36572**               +---------> READER-------+      |
36573**               |              |                |
36574**               |              V                |
36575**               |<-------WRITER_LOCKED------> ERROR
36576**               |              |                ^
36577**               |              V                |
36578**               |<------WRITER_CACHEMOD-------->|
36579**               |              |                |
36580**               |              V                |
36581**               |<-------WRITER_DBMOD---------->|
36582**               |              |                |
36583**               |              V                |
36584**               +<------WRITER_FINISHED-------->+
36585**
36586**
36587** List of state transitions and the C [function] that performs each:
36588**
36589**   OPEN              -> READER              [sqlite3PagerSharedLock]
36590**   READER            -> OPEN                [pager_unlock]
36591**
36592**   READER            -> WRITER_LOCKED       [sqlite3PagerBegin]
36593**   WRITER_LOCKED     -> WRITER_CACHEMOD     [pager_open_journal]
36594**   WRITER_CACHEMOD   -> WRITER_DBMOD        [syncJournal]
36595**   WRITER_DBMOD      -> WRITER_FINISHED     [sqlite3PagerCommitPhaseOne]
36596**   WRITER_***        -> READER              [pager_end_transaction]
36597**
36598**   WRITER_***        -> ERROR               [pager_error]
36599**   ERROR             -> OPEN                [pager_unlock]
36600**
36601**
36602**  OPEN:
36603**
36604**    The pager starts up in this state. Nothing is guaranteed in this
36605**    state - the file may or may not be locked and the database size is
36606**    unknown. The database may not be read or written.
36607**
36608**    * No read or write transaction is active.
36609**    * Any lock, or no lock at all, may be held on the database file.
36610**    * The dbSize, dbOrigSize and dbFileSize variables may not be trusted.
36611**
36612**  READER:
36613**
36614**    In this state all the requirements for reading the database in
36615**    rollback (non-WAL) mode are met. Unless the pager is (or recently
36616**    was) in exclusive-locking mode, a user-level read transaction is
36617**    open. The database size is known in this state.
36618**
36619**    A connection running with locking_mode=normal enters this state when
36620**    it opens a read-transaction on the database and returns to state
36621**    OPEN after the read-transaction is completed. However a connection
36622**    running in locking_mode=exclusive (including temp databases) remains in
36623**    this state even after the read-transaction is closed. The only way
36624**    a locking_mode=exclusive connection can transition from READER to OPEN
36625**    is via the ERROR state (see below).
36626**
36627**    * A read transaction may be active (but a write-transaction cannot).
36628**    * A SHARED or greater lock is held on the database file.
36629**    * The dbSize variable may be trusted (even if a user-level read
36630**      transaction is not active). The dbOrigSize and dbFileSize variables
36631**      may not be trusted at this point.
36632**    * If the database is a WAL database, then the WAL connection is open.
36633**    * Even if a read-transaction is not open, it is guaranteed that
36634**      there is no hot-journal in the file-system.
36635**
36636**  WRITER_LOCKED:
36637**
36638**    The pager moves to this state from READER when a write-transaction
36639**    is first opened on the database. In WRITER_LOCKED state, all locks
36640**    required to start a write-transaction are held, but no actual
36641**    modifications to the cache or database have taken place.
36642**
36643**    In rollback mode, a RESERVED or (if the transaction was opened with
36644**    BEGIN EXCLUSIVE) EXCLUSIVE lock is obtained on the database file when
36645**    moving to this state, but the journal file is not written to or opened
36646**    to in this state. If the transaction is committed or rolled back while
36647**    in WRITER_LOCKED state, all that is required is to unlock the database
36648**    file.
36649**
36650**    IN WAL mode, WalBeginWriteTransaction() is called to lock the log file.
36651**    If the connection is running with locking_mode=exclusive, an attempt
36652**    is made to obtain an EXCLUSIVE lock on the database file.
36653**
36654**    * A write transaction is active.
36655**    * If the connection is open in rollback-mode, a RESERVED or greater
36656**      lock is held on the database file.
36657**    * If the connection is open in WAL-mode, a WAL write transaction
36658**      is open (i.e. sqlite3WalBeginWriteTransaction() has been successfully
36659**      called).
36660**    * The dbSize, dbOrigSize and dbFileSize variables are all valid.
36661**    * The contents of the pager cache have not been modified.
36662**    * The journal file may or may not be open.
36663**    * Nothing (not even the first header) has been written to the journal.
36664**
36665**  WRITER_CACHEMOD:
36666**
36667**    A pager moves from WRITER_LOCKED state to this state when a page is
36668**    first modified by the upper layer. In rollback mode the journal file
36669**    is opened (if it is not already open) and a header written to the
36670**    start of it. The database file on disk has not been modified.
36671**
36672**    * A write transaction is active.
36673**    * A RESERVED or greater lock is held on the database file.
36674**    * The journal file is open and the first header has been written
36675**      to it, but the header has not been synced to disk.
36676**    * The contents of the page cache have been modified.
36677**
36678**  WRITER_DBMOD:
36679**
36680**    The pager transitions from WRITER_CACHEMOD into WRITER_DBMOD state
36681**    when it modifies the contents of the database file. WAL connections
36682**    never enter this state (since they do not modify the database file,
36683**    just the log file).
36684**
36685**    * A write transaction is active.
36686**    * An EXCLUSIVE or greater lock is held on the database file.
36687**    * The journal file is open and the first header has been written
36688**      and synced to disk.
36689**    * The contents of the page cache have been modified (and possibly
36690**      written to disk).
36691**
36692**  WRITER_FINISHED:
36693**
36694**    It is not possible for a WAL connection to enter this state.
36695**
36696**    A rollback-mode pager changes to WRITER_FINISHED state from WRITER_DBMOD
36697**    state after the entire transaction has been successfully written into the
36698**    database file. In this state the transaction may be committed simply
36699**    by finalizing the journal file. Once in WRITER_FINISHED state, it is
36700**    not possible to modify the database further. At this point, the upper
36701**    layer must either commit or rollback the transaction.
36702**
36703**    * A write transaction is active.
36704**    * An EXCLUSIVE or greater lock is held on the database file.
36705**    * All writing and syncing of journal and database data has finished.
36706**      If no error occured, all that remains is to finalize the journal to
36707**      commit the transaction. If an error did occur, the caller will need
36708**      to rollback the transaction.
36709**
36710**  ERROR:
36711**
36712**    The ERROR state is entered when an IO or disk-full error (including
36713**    SQLITE_IOERR_NOMEM) occurs at a point in the code that makes it
36714**    difficult to be sure that the in-memory pager state (cache contents,
36715**    db size etc.) are consistent with the contents of the file-system.
36716**
36717**    Temporary pager files may enter the ERROR state, but in-memory pagers
36718**    cannot.
36719**
36720**    For example, if an IO error occurs while performing a rollback,
36721**    the contents of the page-cache may be left in an inconsistent state.
36722**    At this point it would be dangerous to change back to READER state
36723**    (as usually happens after a rollback). Any subsequent readers might
36724**    report database corruption (due to the inconsistent cache), and if
36725**    they upgrade to writers, they may inadvertently corrupt the database
36726**    file. To avoid this hazard, the pager switches into the ERROR state
36727**    instead of READER following such an error.
36728**
36729**    Once it has entered the ERROR state, any attempt to use the pager
36730**    to read or write data returns an error. Eventually, once all
36731**    outstanding transactions have been abandoned, the pager is able to
36732**    transition back to OPEN state, discarding the contents of the
36733**    page-cache and any other in-memory state at the same time. Everything
36734**    is reloaded from disk (and, if necessary, hot-journal rollback peformed)
36735**    when a read-transaction is next opened on the pager (transitioning
36736**    the pager into READER state). At that point the system has recovered
36737**    from the error.
36738**
36739**    Specifically, the pager jumps into the ERROR state if:
36740**
36741**      1. An error occurs while attempting a rollback. This happens in
36742**         function sqlite3PagerRollback().
36743**
36744**      2. An error occurs while attempting to finalize a journal file
36745**         following a commit in function sqlite3PagerCommitPhaseTwo().
36746**
36747**      3. An error occurs while attempting to write to the journal or
36748**         database file in function pagerStress() in order to free up
36749**         memory.
36750**
36751**    In other cases, the error is returned to the b-tree layer. The b-tree
36752**    layer then attempts a rollback operation. If the error condition
36753**    persists, the pager enters the ERROR state via condition (1) above.
36754**
36755**    Condition (3) is necessary because it can be triggered by a read-only
36756**    statement executed within a transaction. In this case, if the error
36757**    code were simply returned to the user, the b-tree layer would not
36758**    automatically attempt a rollback, as it assumes that an error in a
36759**    read-only statement cannot leave the pager in an internally inconsistent
36760**    state.
36761**
36762**    * The Pager.errCode variable is set to something other than SQLITE_OK.
36763**    * There are one or more outstanding references to pages (after the
36764**      last reference is dropped the pager should move back to OPEN state).
36765**    * The pager is not an in-memory pager.
36766**
36767**
36768** Notes:
36769**
36770**   * A pager is never in WRITER_DBMOD or WRITER_FINISHED state if the
36771**     connection is open in WAL mode. A WAL connection is always in one
36772**     of the first four states.
36773**
36774**   * Normally, a connection open in exclusive mode is never in PAGER_OPEN
36775**     state. There are two exceptions: immediately after exclusive-mode has
36776**     been turned on (and before any read or write transactions are
36777**     executed), and when the pager is leaving the "error state".
36778**
36779**   * See also: assert_pager_state().
36780*/
36781#define PAGER_OPEN                  0
36782#define PAGER_READER                1
36783#define PAGER_WRITER_LOCKED         2
36784#define PAGER_WRITER_CACHEMOD       3
36785#define PAGER_WRITER_DBMOD          4
36786#define PAGER_WRITER_FINISHED       5
36787#define PAGER_ERROR                 6
36788
36789/*
36790** The Pager.eLock variable is almost always set to one of the
36791** following locking-states, according to the lock currently held on
36792** the database file: NO_LOCK, SHARED_LOCK, RESERVED_LOCK or EXCLUSIVE_LOCK.
36793** This variable is kept up to date as locks are taken and released by
36794** the pagerLockDb() and pagerUnlockDb() wrappers.
36795**
36796** If the VFS xLock() or xUnlock() returns an error other than SQLITE_BUSY
36797** (i.e. one of the SQLITE_IOERR subtypes), it is not clear whether or not
36798** the operation was successful. In these circumstances pagerLockDb() and
36799** pagerUnlockDb() take a conservative approach - eLock is always updated
36800** when unlocking the file, and only updated when locking the file if the
36801** VFS call is successful. This way, the Pager.eLock variable may be set
36802** to a less exclusive (lower) value than the lock that is actually held
36803** at the system level, but it is never set to a more exclusive value.
36804**
36805** This is usually safe. If an xUnlock fails or appears to fail, there may
36806** be a few redundant xLock() calls or a lock may be held for longer than
36807** required, but nothing really goes wrong.
36808**
36809** The exception is when the database file is unlocked as the pager moves
36810** from ERROR to OPEN state. At this point there may be a hot-journal file
36811** in the file-system that needs to be rolled back (as part of a OPEN->SHARED
36812** transition, by the same pager or any other). If the call to xUnlock()
36813** fails at this point and the pager is left holding an EXCLUSIVE lock, this
36814** can confuse the call to xCheckReservedLock() call made later as part
36815** of hot-journal detection.
36816**
36817** xCheckReservedLock() is defined as returning true "if there is a RESERVED
36818** lock held by this process or any others". So xCheckReservedLock may
36819** return true because the caller itself is holding an EXCLUSIVE lock (but
36820** doesn't know it because of a previous error in xUnlock). If this happens
36821** a hot-journal may be mistaken for a journal being created by an active
36822** transaction in another process, causing SQLite to read from the database
36823** without rolling it back.
36824**
36825** To work around this, if a call to xUnlock() fails when unlocking the
36826** database in the ERROR state, Pager.eLock is set to UNKNOWN_LOCK. It
36827** is only changed back to a real locking state after a successful call
36828** to xLock(EXCLUSIVE). Also, the code to do the OPEN->SHARED state transition
36829** omits the check for a hot-journal if Pager.eLock is set to UNKNOWN_LOCK
36830** lock. Instead, it assumes a hot-journal exists and obtains an EXCLUSIVE
36831** lock on the database file before attempting to roll it back. See function
36832** PagerSharedLock() for more detail.
36833**
36834** Pager.eLock may only be set to UNKNOWN_LOCK when the pager is in
36835** PAGER_OPEN state.
36836*/
36837#define UNKNOWN_LOCK                (EXCLUSIVE_LOCK+1)
36838
36839/*
36840** A macro used for invoking the codec if there is one
36841*/
36842#ifdef SQLITE_HAS_CODEC
36843# define CODEC1(P,D,N,X,E) \
36844    if( P->xCodec && P->xCodec(P->pCodec,D,N,X)==0 ){ E; }
36845# define CODEC2(P,D,N,X,E,O) \
36846    if( P->xCodec==0 ){ O=(char*)D; }else \
36847    if( (O=(char*)(P->xCodec(P->pCodec,D,N,X)))==0 ){ E; }
36848#else
36849# define CODEC1(P,D,N,X,E)   /* NO-OP */
36850# define CODEC2(P,D,N,X,E,O) O=(char*)D
36851#endif
36852
36853/*
36854** The maximum allowed sector size. 64KiB. If the xSectorsize() method
36855** returns a value larger than this, then MAX_SECTOR_SIZE is used instead.
36856** This could conceivably cause corruption following a power failure on
36857** such a system. This is currently an undocumented limit.
36858*/
36859#define MAX_SECTOR_SIZE 0x10000
36860
36861/*
36862** An instance of the following structure is allocated for each active
36863** savepoint and statement transaction in the system. All such structures
36864** are stored in the Pager.aSavepoint[] array, which is allocated and
36865** resized using sqlite3Realloc().
36866**
36867** When a savepoint is created, the PagerSavepoint.iHdrOffset field is
36868** set to 0. If a journal-header is written into the main journal while
36869** the savepoint is active, then iHdrOffset is set to the byte offset
36870** immediately following the last journal record written into the main
36871** journal before the journal-header. This is required during savepoint
36872** rollback (see pagerPlaybackSavepoint()).
36873*/
36874typedef struct PagerSavepoint PagerSavepoint;
36875struct PagerSavepoint {
36876  i64 iOffset;                 /* Starting offset in main journal */
36877  i64 iHdrOffset;              /* See above */
36878  Bitvec *pInSavepoint;        /* Set of pages in this savepoint */
36879  Pgno nOrig;                  /* Original number of pages in file */
36880  Pgno iSubRec;                /* Index of first record in sub-journal */
36881#ifndef SQLITE_OMIT_WAL
36882  u32 aWalData[WAL_SAVEPOINT_NDATA];        /* WAL savepoint context */
36883#endif
36884};
36885
36886/*
36887** A open page cache is an instance of struct Pager. A description of
36888** some of the more important member variables follows:
36889**
36890** eState
36891**
36892**   The current 'state' of the pager object. See the comment and state
36893**   diagram above for a description of the pager state.
36894**
36895** eLock
36896**
36897**   For a real on-disk database, the current lock held on the database file -
36898**   NO_LOCK, SHARED_LOCK, RESERVED_LOCK or EXCLUSIVE_LOCK.
36899**
36900**   For a temporary or in-memory database (neither of which require any
36901**   locks), this variable is always set to EXCLUSIVE_LOCK. Since such
36902**   databases always have Pager.exclusiveMode==1, this tricks the pager
36903**   logic into thinking that it already has all the locks it will ever
36904**   need (and no reason to release them).
36905**
36906**   In some (obscure) circumstances, this variable may also be set to
36907**   UNKNOWN_LOCK. See the comment above the #define of UNKNOWN_LOCK for
36908**   details.
36909**
36910** changeCountDone
36911**
36912**   This boolean variable is used to make sure that the change-counter
36913**   (the 4-byte header field at byte offset 24 of the database file) is
36914**   not updated more often than necessary.
36915**
36916**   It is set to true when the change-counter field is updated, which
36917**   can only happen if an exclusive lock is held on the database file.
36918**   It is cleared (set to false) whenever an exclusive lock is
36919**   relinquished on the database file. Each time a transaction is committed,
36920**   The changeCountDone flag is inspected. If it is true, the work of
36921**   updating the change-counter is omitted for the current transaction.
36922**
36923**   This mechanism means that when running in exclusive mode, a connection
36924**   need only update the change-counter once, for the first transaction
36925**   committed.
36926**
36927** setMaster
36928**
36929**   When PagerCommitPhaseOne() is called to commit a transaction, it may
36930**   (or may not) specify a master-journal name to be written into the
36931**   journal file before it is synced to disk.
36932**
36933**   Whether or not a journal file contains a master-journal pointer affects
36934**   the way in which the journal file is finalized after the transaction is
36935**   committed or rolled back when running in "journal_mode=PERSIST" mode.
36936**   If a journal file does not contain a master-journal pointer, it is
36937**   finalized by overwriting the first journal header with zeroes. If
36938**   it does contain a master-journal pointer the journal file is finalized
36939**   by truncating it to zero bytes, just as if the connection were
36940**   running in "journal_mode=truncate" mode.
36941**
36942**   Journal files that contain master journal pointers cannot be finalized
36943**   simply by overwriting the first journal-header with zeroes, as the
36944**   master journal pointer could interfere with hot-journal rollback of any
36945**   subsequently interrupted transaction that reuses the journal file.
36946**
36947**   The flag is cleared as soon as the journal file is finalized (either
36948**   by PagerCommitPhaseTwo or PagerRollback). If an IO error prevents the
36949**   journal file from being successfully finalized, the setMaster flag
36950**   is cleared anyway (and the pager will move to ERROR state).
36951**
36952** doNotSpill, doNotSyncSpill
36953**
36954**   These two boolean variables control the behaviour of cache-spills
36955**   (calls made by the pcache module to the pagerStress() routine to
36956**   write cached data to the file-system in order to free up memory).
36957**
36958**   When doNotSpill is non-zero, writing to the database from pagerStress()
36959**   is disabled altogether. This is done in a very obscure case that
36960**   comes up during savepoint rollback that requires the pcache module
36961**   to allocate a new page to prevent the journal file from being written
36962**   while it is being traversed by code in pager_playback().
36963**
36964**   If doNotSyncSpill is non-zero, writing to the database from pagerStress()
36965**   is permitted, but syncing the journal file is not. This flag is set
36966**   by sqlite3PagerWrite() when the file-system sector-size is larger than
36967**   the database page-size in order to prevent a journal sync from happening
36968**   in between the journalling of two pages on the same sector.
36969**
36970** subjInMemory
36971**
36972**   This is a boolean variable. If true, then any required sub-journal
36973**   is opened as an in-memory journal file. If false, then in-memory
36974**   sub-journals are only used for in-memory pager files.
36975**
36976**   This variable is updated by the upper layer each time a new
36977**   write-transaction is opened.
36978**
36979** dbSize, dbOrigSize, dbFileSize
36980**
36981**   Variable dbSize is set to the number of pages in the database file.
36982**   It is valid in PAGER_READER and higher states (all states except for
36983**   OPEN and ERROR).
36984**
36985**   dbSize is set based on the size of the database file, which may be
36986**   larger than the size of the database (the value stored at offset
36987**   28 of the database header by the btree). If the size of the file
36988**   is not an integer multiple of the page-size, the value stored in
36989**   dbSize is rounded down (i.e. a 5KB file with 2K page-size has dbSize==2).
36990**   Except, any file that is greater than 0 bytes in size is considered
36991**   to have at least one page. (i.e. a 1KB file with 2K page-size leads
36992**   to dbSize==1).
36993**
36994**   During a write-transaction, if pages with page-numbers greater than
36995**   dbSize are modified in the cache, dbSize is updated accordingly.
36996**   Similarly, if the database is truncated using PagerTruncateImage(),
36997**   dbSize is updated.
36998**
36999**   Variables dbOrigSize and dbFileSize are valid in states
37000**   PAGER_WRITER_LOCKED and higher. dbOrigSize is a copy of the dbSize
37001**   variable at the start of the transaction. It is used during rollback,
37002**   and to determine whether or not pages need to be journalled before
37003**   being modified.
37004**
37005**   Throughout a write-transaction, dbFileSize contains the size of
37006**   the file on disk in pages. It is set to a copy of dbSize when the
37007**   write-transaction is first opened, and updated when VFS calls are made
37008**   to write or truncate the database file on disk.
37009**
37010**   The only reason the dbFileSize variable is required is to suppress
37011**   unnecessary calls to xTruncate() after committing a transaction. If,
37012**   when a transaction is committed, the dbFileSize variable indicates
37013**   that the database file is larger than the database image (Pager.dbSize),
37014**   pager_truncate() is called. The pager_truncate() call uses xFilesize()
37015**   to measure the database file on disk, and then truncates it if required.
37016**   dbFileSize is not used when rolling back a transaction. In this case
37017**   pager_truncate() is called unconditionally (which means there may be
37018**   a call to xFilesize() that is not strictly required). In either case,
37019**   pager_truncate() may cause the file to become smaller or larger.
37020**
37021** dbHintSize
37022**
37023**   The dbHintSize variable is used to limit the number of calls made to
37024**   the VFS xFileControl(FCNTL_SIZE_HINT) method.
37025**
37026**   dbHintSize is set to a copy of the dbSize variable when a
37027**   write-transaction is opened (at the same time as dbFileSize and
37028**   dbOrigSize). If the xFileControl(FCNTL_SIZE_HINT) method is called,
37029**   dbHintSize is increased to the number of pages that correspond to the
37030**   size-hint passed to the method call. See pager_write_pagelist() for
37031**   details.
37032**
37033** errCode
37034**
37035**   The Pager.errCode variable is only ever used in PAGER_ERROR state. It
37036**   is set to zero in all other states. In PAGER_ERROR state, Pager.errCode
37037**   is always set to SQLITE_FULL, SQLITE_IOERR or one of the SQLITE_IOERR_XXX
37038**   sub-codes.
37039*/
37040struct Pager {
37041  sqlite3_vfs *pVfs;          /* OS functions to use for IO */
37042  u8 exclusiveMode;           /* Boolean. True if locking_mode==EXCLUSIVE */
37043  u8 journalMode;             /* One of the PAGER_JOURNALMODE_* values */
37044  u8 useJournal;              /* Use a rollback journal on this file */
37045  u8 noReadlock;              /* Do not bother to obtain readlocks */
37046  u8 noSync;                  /* Do not sync the journal if true */
37047  u8 fullSync;                /* Do extra syncs of the journal for robustness */
37048  u8 ckptSyncFlags;           /* SYNC_NORMAL or SYNC_FULL for checkpoint */
37049  u8 syncFlags;               /* SYNC_NORMAL or SYNC_FULL otherwise */
37050  u8 tempFile;                /* zFilename is a temporary file */
37051  u8 readOnly;                /* True for a read-only database */
37052  u8 memDb;                   /* True to inhibit all file I/O */
37053
37054  /**************************************************************************
37055  ** The following block contains those class members that change during
37056  ** routine opertion.  Class members not in this block are either fixed
37057  ** when the pager is first created or else only change when there is a
37058  ** significant mode change (such as changing the page_size, locking_mode,
37059  ** or the journal_mode).  From another view, these class members describe
37060  ** the "state" of the pager, while other class members describe the
37061  ** "configuration" of the pager.
37062  */
37063  u8 eState;                  /* Pager state (OPEN, READER, WRITER_LOCKED..) */
37064  u8 eLock;                   /* Current lock held on database file */
37065  u8 changeCountDone;         /* Set after incrementing the change-counter */
37066  u8 setMaster;               /* True if a m-j name has been written to jrnl */
37067  u8 doNotSpill;              /* Do not spill the cache when non-zero */
37068  u8 doNotSyncSpill;          /* Do not do a spill that requires jrnl sync */
37069  u8 subjInMemory;            /* True to use in-memory sub-journals */
37070  Pgno dbSize;                /* Number of pages in the database */
37071  Pgno dbOrigSize;            /* dbSize before the current transaction */
37072  Pgno dbFileSize;            /* Number of pages in the database file */
37073  Pgno dbHintSize;            /* Value passed to FCNTL_SIZE_HINT call */
37074  int errCode;                /* One of several kinds of errors */
37075  int nRec;                   /* Pages journalled since last j-header written */
37076  u32 cksumInit;              /* Quasi-random value added to every checksum */
37077  u32 nSubRec;                /* Number of records written to sub-journal */
37078  Bitvec *pInJournal;         /* One bit for each page in the database file */
37079  sqlite3_file *fd;           /* File descriptor for database */
37080  sqlite3_file *jfd;          /* File descriptor for main journal */
37081  sqlite3_file *sjfd;         /* File descriptor for sub-journal */
37082  i64 journalOff;             /* Current write offset in the journal file */
37083  i64 journalHdr;             /* Byte offset to previous journal header */
37084  sqlite3_backup *pBackup;    /* Pointer to list of ongoing backup processes */
37085  PagerSavepoint *aSavepoint; /* Array of active savepoints */
37086  int nSavepoint;             /* Number of elements in aSavepoint[] */
37087  char dbFileVers[16];        /* Changes whenever database file changes */
37088  /*
37089  ** End of the routinely-changing class members
37090  ***************************************************************************/
37091
37092  u16 nExtra;                 /* Add this many bytes to each in-memory page */
37093  i16 nReserve;               /* Number of unused bytes at end of each page */
37094  u32 vfsFlags;               /* Flags for sqlite3_vfs.xOpen() */
37095  u32 sectorSize;             /* Assumed sector size during rollback */
37096  int pageSize;               /* Number of bytes in a page */
37097  Pgno mxPgno;                /* Maximum allowed size of the database */
37098  i64 journalSizeLimit;       /* Size limit for persistent journal files */
37099  char *zFilename;            /* Name of the database file */
37100  char *zJournal;             /* Name of the journal file */
37101  int (*xBusyHandler)(void*); /* Function to call when busy */
37102  void *pBusyHandlerArg;      /* Context argument for xBusyHandler */
37103#ifdef SQLITE_TEST
37104  int nHit, nMiss;            /* Cache hits and missing */
37105  int nRead, nWrite;          /* Database pages read/written */
37106#endif
37107  void (*xReiniter)(DbPage*); /* Call this routine when reloading pages */
37108#ifdef SQLITE_HAS_CODEC
37109  void *(*xCodec)(void*,void*,Pgno,int); /* Routine for en/decoding data */
37110  void (*xCodecSizeChng)(void*,int,int); /* Notify of page size changes */
37111  void (*xCodecFree)(void*);             /* Destructor for the codec */
37112  void *pCodec;               /* First argument to xCodec... methods */
37113#endif
37114  char *pTmpSpace;            /* Pager.pageSize bytes of space for tmp use */
37115  PCache *pPCache;            /* Pointer to page cache object */
37116#ifndef SQLITE_OMIT_WAL
37117  Wal *pWal;                  /* Write-ahead log used by "journal_mode=wal" */
37118  char *zWal;                 /* File name for write-ahead log */
37119#endif
37120};
37121
37122/*
37123** The following global variables hold counters used for
37124** testing purposes only.  These variables do not exist in
37125** a non-testing build.  These variables are not thread-safe.
37126*/
37127#ifdef SQLITE_TEST
37128SQLITE_API int sqlite3_pager_readdb_count = 0;    /* Number of full pages read from DB */
37129SQLITE_API int sqlite3_pager_writedb_count = 0;   /* Number of full pages written to DB */
37130SQLITE_API int sqlite3_pager_writej_count = 0;    /* Number of pages written to journal */
37131# define PAGER_INCR(v)  v++
37132#else
37133# define PAGER_INCR(v)
37134#endif
37135
37136
37137
37138/*
37139** Journal files begin with the following magic string.  The data
37140** was obtained from /dev/random.  It is used only as a sanity check.
37141**
37142** Since version 2.8.0, the journal format contains additional sanity
37143** checking information.  If the power fails while the journal is being
37144** written, semi-random garbage data might appear in the journal
37145** file after power is restored.  If an attempt is then made
37146** to roll the journal back, the database could be corrupted.  The additional
37147** sanity checking data is an attempt to discover the garbage in the
37148** journal and ignore it.
37149**
37150** The sanity checking information for the new journal format consists
37151** of a 32-bit checksum on each page of data.  The checksum covers both
37152** the page number and the pPager->pageSize bytes of data for the page.
37153** This cksum is initialized to a 32-bit random value that appears in the
37154** journal file right after the header.  The random initializer is important,
37155** because garbage data that appears at the end of a journal is likely
37156** data that was once in other files that have now been deleted.  If the
37157** garbage data came from an obsolete journal file, the checksums might
37158** be correct.  But by initializing the checksum to random value which
37159** is different for every journal, we minimize that risk.
37160*/
37161static const unsigned char aJournalMagic[] = {
37162  0xd9, 0xd5, 0x05, 0xf9, 0x20, 0xa1, 0x63, 0xd7,
37163};
37164
37165/*
37166** The size of the of each page record in the journal is given by
37167** the following macro.
37168*/
37169#define JOURNAL_PG_SZ(pPager)  ((pPager->pageSize) + 8)
37170
37171/*
37172** The journal header size for this pager. This is usually the same
37173** size as a single disk sector. See also setSectorSize().
37174*/
37175#define JOURNAL_HDR_SZ(pPager) (pPager->sectorSize)
37176
37177/*
37178** The macro MEMDB is true if we are dealing with an in-memory database.
37179** We do this as a macro so that if the SQLITE_OMIT_MEMORYDB macro is set,
37180** the value of MEMDB will be a constant and the compiler will optimize
37181** out code that would never execute.
37182*/
37183#ifdef SQLITE_OMIT_MEMORYDB
37184# define MEMDB 0
37185#else
37186# define MEMDB pPager->memDb
37187#endif
37188
37189/*
37190** The maximum legal page number is (2^31 - 1).
37191*/
37192#define PAGER_MAX_PGNO 2147483647
37193
37194/*
37195** The argument to this macro is a file descriptor (type sqlite3_file*).
37196** Return 0 if it is not open, or non-zero (but not 1) if it is.
37197**
37198** This is so that expressions can be written as:
37199**
37200**   if( isOpen(pPager->jfd) ){ ...
37201**
37202** instead of
37203**
37204**   if( pPager->jfd->pMethods ){ ...
37205*/
37206#define isOpen(pFd) ((pFd)->pMethods)
37207
37208/*
37209** Return true if this pager uses a write-ahead log instead of the usual
37210** rollback journal. Otherwise false.
37211*/
37212#ifndef SQLITE_OMIT_WAL
37213static int pagerUseWal(Pager *pPager){
37214  return (pPager->pWal!=0);
37215}
37216#else
37217# define pagerUseWal(x) 0
37218# define pagerRollbackWal(x) 0
37219# define pagerWalFrames(v,w,x,y,z) 0
37220# define pagerOpenWalIfPresent(z) SQLITE_OK
37221# define pagerBeginReadTransaction(z) SQLITE_OK
37222#endif
37223
37224#ifndef NDEBUG
37225/*
37226** Usage:
37227**
37228**   assert( assert_pager_state(pPager) );
37229**
37230** This function runs many asserts to try to find inconsistencies in
37231** the internal state of the Pager object.
37232*/
37233static int assert_pager_state(Pager *p){
37234  Pager *pPager = p;
37235
37236  /* State must be valid. */
37237  assert( p->eState==PAGER_OPEN
37238       || p->eState==PAGER_READER
37239       || p->eState==PAGER_WRITER_LOCKED
37240       || p->eState==PAGER_WRITER_CACHEMOD
37241       || p->eState==PAGER_WRITER_DBMOD
37242       || p->eState==PAGER_WRITER_FINISHED
37243       || p->eState==PAGER_ERROR
37244  );
37245
37246  /* Regardless of the current state, a temp-file connection always behaves
37247  ** as if it has an exclusive lock on the database file. It never updates
37248  ** the change-counter field, so the changeCountDone flag is always set.
37249  */
37250  assert( p->tempFile==0 || p->eLock==EXCLUSIVE_LOCK );
37251  assert( p->tempFile==0 || pPager->changeCountDone );
37252
37253  /* If the useJournal flag is clear, the journal-mode must be "OFF".
37254  ** And if the journal-mode is "OFF", the journal file must not be open.
37255  */
37256  assert( p->journalMode==PAGER_JOURNALMODE_OFF || p->useJournal );
37257  assert( p->journalMode!=PAGER_JOURNALMODE_OFF || !isOpen(p->jfd) );
37258
37259  /* Check that MEMDB implies noSync. And an in-memory journal. Since
37260  ** this means an in-memory pager performs no IO at all, it cannot encounter
37261  ** either SQLITE_IOERR or SQLITE_FULL during rollback or while finalizing
37262  ** a journal file. (although the in-memory journal implementation may
37263  ** return SQLITE_IOERR_NOMEM while the journal file is being written). It
37264  ** is therefore not possible for an in-memory pager to enter the ERROR
37265  ** state.
37266  */
37267  if( MEMDB ){
37268    assert( p->noSync );
37269    assert( p->journalMode==PAGER_JOURNALMODE_OFF
37270         || p->journalMode==PAGER_JOURNALMODE_MEMORY
37271    );
37272    assert( p->eState!=PAGER_ERROR && p->eState!=PAGER_OPEN );
37273    assert( pagerUseWal(p)==0 );
37274  }
37275
37276  /* If changeCountDone is set, a RESERVED lock or greater must be held
37277  ** on the file.
37278  */
37279  assert( pPager->changeCountDone==0 || pPager->eLock>=RESERVED_LOCK );
37280  assert( p->eLock!=PENDING_LOCK );
37281
37282  switch( p->eState ){
37283    case PAGER_OPEN:
37284      assert( !MEMDB );
37285      assert( pPager->errCode==SQLITE_OK );
37286      assert( sqlite3PcacheRefCount(pPager->pPCache)==0 || pPager->tempFile );
37287      break;
37288
37289    case PAGER_READER:
37290      assert( pPager->errCode==SQLITE_OK );
37291      assert( p->eLock!=UNKNOWN_LOCK );
37292      assert( p->eLock>=SHARED_LOCK || p->noReadlock );
37293      break;
37294
37295    case PAGER_WRITER_LOCKED:
37296      assert( p->eLock!=UNKNOWN_LOCK );
37297      assert( pPager->errCode==SQLITE_OK );
37298      if( !pagerUseWal(pPager) ){
37299        assert( p->eLock>=RESERVED_LOCK );
37300      }
37301      assert( pPager->dbSize==pPager->dbOrigSize );
37302      assert( pPager->dbOrigSize==pPager->dbFileSize );
37303      assert( pPager->dbOrigSize==pPager->dbHintSize );
37304      assert( pPager->setMaster==0 );
37305      break;
37306
37307    case PAGER_WRITER_CACHEMOD:
37308      assert( p->eLock!=UNKNOWN_LOCK );
37309      assert( pPager->errCode==SQLITE_OK );
37310      if( !pagerUseWal(pPager) ){
37311        /* It is possible that if journal_mode=wal here that neither the
37312        ** journal file nor the WAL file are open. This happens during
37313        ** a rollback transaction that switches from journal_mode=off
37314        ** to journal_mode=wal.
37315        */
37316        assert( p->eLock>=RESERVED_LOCK );
37317        assert( isOpen(p->jfd)
37318             || p->journalMode==PAGER_JOURNALMODE_OFF
37319             || p->journalMode==PAGER_JOURNALMODE_WAL
37320        );
37321      }
37322      assert( pPager->dbOrigSize==pPager->dbFileSize );
37323      assert( pPager->dbOrigSize==pPager->dbHintSize );
37324      break;
37325
37326    case PAGER_WRITER_DBMOD:
37327      assert( p->eLock==EXCLUSIVE_LOCK );
37328      assert( pPager->errCode==SQLITE_OK );
37329      assert( !pagerUseWal(pPager) );
37330      assert( p->eLock>=EXCLUSIVE_LOCK );
37331      assert( isOpen(p->jfd)
37332           || p->journalMode==PAGER_JOURNALMODE_OFF
37333           || p->journalMode==PAGER_JOURNALMODE_WAL
37334      );
37335      assert( pPager->dbOrigSize<=pPager->dbHintSize );
37336      break;
37337
37338    case PAGER_WRITER_FINISHED:
37339      assert( p->eLock==EXCLUSIVE_LOCK );
37340      assert( pPager->errCode==SQLITE_OK );
37341      assert( !pagerUseWal(pPager) );
37342      assert( isOpen(p->jfd)
37343           || p->journalMode==PAGER_JOURNALMODE_OFF
37344           || p->journalMode==PAGER_JOURNALMODE_WAL
37345      );
37346      break;
37347
37348    case PAGER_ERROR:
37349      /* There must be at least one outstanding reference to the pager if
37350      ** in ERROR state. Otherwise the pager should have already dropped
37351      ** back to OPEN state.
37352      */
37353      assert( pPager->errCode!=SQLITE_OK );
37354      assert( sqlite3PcacheRefCount(pPager->pPCache)>0 );
37355      break;
37356  }
37357
37358  return 1;
37359}
37360#endif /* ifndef NDEBUG */
37361
37362#ifdef SQLITE_DEBUG
37363/*
37364** Return a pointer to a human readable string in a static buffer
37365** containing the state of the Pager object passed as an argument. This
37366** is intended to be used within debuggers. For example, as an alternative
37367** to "print *pPager" in gdb:
37368**
37369** (gdb) printf "%s", print_pager_state(pPager)
37370*/
37371static char *print_pager_state(Pager *p){
37372  static char zRet[1024];
37373
37374  sqlite3_snprintf(1024, zRet,
37375      "Filename:      %s\n"
37376      "State:         %s errCode=%d\n"
37377      "Lock:          %s\n"
37378      "Locking mode:  locking_mode=%s\n"
37379      "Journal mode:  journal_mode=%s\n"
37380      "Backing store: tempFile=%d memDb=%d useJournal=%d\n"
37381      "Journal:       journalOff=%lld journalHdr=%lld\n"
37382      "Size:          dbsize=%d dbOrigSize=%d dbFileSize=%d\n"
37383      , p->zFilename
37384      , p->eState==PAGER_OPEN            ? "OPEN" :
37385        p->eState==PAGER_READER          ? "READER" :
37386        p->eState==PAGER_WRITER_LOCKED   ? "WRITER_LOCKED" :
37387        p->eState==PAGER_WRITER_CACHEMOD ? "WRITER_CACHEMOD" :
37388        p->eState==PAGER_WRITER_DBMOD    ? "WRITER_DBMOD" :
37389        p->eState==PAGER_WRITER_FINISHED ? "WRITER_FINISHED" :
37390        p->eState==PAGER_ERROR           ? "ERROR" : "?error?"
37391      , (int)p->errCode
37392      , p->eLock==NO_LOCK         ? "NO_LOCK" :
37393        p->eLock==RESERVED_LOCK   ? "RESERVED" :
37394        p->eLock==EXCLUSIVE_LOCK  ? "EXCLUSIVE" :
37395        p->eLock==SHARED_LOCK     ? "SHARED" :
37396        p->eLock==UNKNOWN_LOCK    ? "UNKNOWN" : "?error?"
37397      , p->exclusiveMode ? "exclusive" : "normal"
37398      , p->journalMode==PAGER_JOURNALMODE_MEMORY   ? "memory" :
37399        p->journalMode==PAGER_JOURNALMODE_OFF      ? "off" :
37400        p->journalMode==PAGER_JOURNALMODE_DELETE   ? "delete" :
37401        p->journalMode==PAGER_JOURNALMODE_PERSIST  ? "persist" :
37402        p->journalMode==PAGER_JOURNALMODE_TRUNCATE ? "truncate" :
37403        p->journalMode==PAGER_JOURNALMODE_WAL      ? "wal" : "?error?"
37404      , (int)p->tempFile, (int)p->memDb, (int)p->useJournal
37405      , p->journalOff, p->journalHdr
37406      , (int)p->dbSize, (int)p->dbOrigSize, (int)p->dbFileSize
37407  );
37408
37409  return zRet;
37410}
37411#endif
37412
37413/*
37414** Return true if it is necessary to write page *pPg into the sub-journal.
37415** A page needs to be written into the sub-journal if there exists one
37416** or more open savepoints for which:
37417**
37418**   * The page-number is less than or equal to PagerSavepoint.nOrig, and
37419**   * The bit corresponding to the page-number is not set in
37420**     PagerSavepoint.pInSavepoint.
37421*/
37422static int subjRequiresPage(PgHdr *pPg){
37423  Pgno pgno = pPg->pgno;
37424  Pager *pPager = pPg->pPager;
37425  int i;
37426  for(i=0; i<pPager->nSavepoint; i++){
37427    PagerSavepoint *p = &pPager->aSavepoint[i];
37428    if( p->nOrig>=pgno && 0==sqlite3BitvecTest(p->pInSavepoint, pgno) ){
37429      return 1;
37430    }
37431  }
37432  return 0;
37433}
37434
37435/*
37436** Return true if the page is already in the journal file.
37437*/
37438static int pageInJournal(PgHdr *pPg){
37439  return sqlite3BitvecTest(pPg->pPager->pInJournal, pPg->pgno);
37440}
37441
37442/*
37443** Read a 32-bit integer from the given file descriptor.  Store the integer
37444** that is read in *pRes.  Return SQLITE_OK if everything worked, or an
37445** error code is something goes wrong.
37446**
37447** All values are stored on disk as big-endian.
37448*/
37449static int read32bits(sqlite3_file *fd, i64 offset, u32 *pRes){
37450  unsigned char ac[4];
37451  int rc = sqlite3OsRead(fd, ac, sizeof(ac), offset);
37452  if( rc==SQLITE_OK ){
37453    *pRes = sqlite3Get4byte(ac);
37454  }
37455  return rc;
37456}
37457
37458/*
37459** Write a 32-bit integer into a string buffer in big-endian byte order.
37460*/
37461#define put32bits(A,B)  sqlite3Put4byte((u8*)A,B)
37462
37463
37464/*
37465** Write a 32-bit integer into the given file descriptor.  Return SQLITE_OK
37466** on success or an error code is something goes wrong.
37467*/
37468static int write32bits(sqlite3_file *fd, i64 offset, u32 val){
37469  char ac[4];
37470  put32bits(ac, val);
37471  return sqlite3OsWrite(fd, ac, 4, offset);
37472}
37473
37474/*
37475** Unlock the database file to level eLock, which must be either NO_LOCK
37476** or SHARED_LOCK. Regardless of whether or not the call to xUnlock()
37477** succeeds, set the Pager.eLock variable to match the (attempted) new lock.
37478**
37479** Except, if Pager.eLock is set to UNKNOWN_LOCK when this function is
37480** called, do not modify it. See the comment above the #define of
37481** UNKNOWN_LOCK for an explanation of this.
37482*/
37483static int pagerUnlockDb(Pager *pPager, int eLock){
37484  int rc = SQLITE_OK;
37485
37486  assert( !pPager->exclusiveMode || pPager->eLock==eLock );
37487  assert( eLock==NO_LOCK || eLock==SHARED_LOCK );
37488  assert( eLock!=NO_LOCK || pagerUseWal(pPager)==0 );
37489  if( isOpen(pPager->fd) ){
37490    assert( pPager->eLock>=eLock );
37491    rc = sqlite3OsUnlock(pPager->fd, eLock);
37492    if( pPager->eLock!=UNKNOWN_LOCK ){
37493      pPager->eLock = (u8)eLock;
37494    }
37495    IOTRACE(("UNLOCK %p %d\n", pPager, eLock))
37496  }
37497  return rc;
37498}
37499
37500/*
37501** Lock the database file to level eLock, which must be either SHARED_LOCK,
37502** RESERVED_LOCK or EXCLUSIVE_LOCK. If the caller is successful, set the
37503** Pager.eLock variable to the new locking state.
37504**
37505** Except, if Pager.eLock is set to UNKNOWN_LOCK when this function is
37506** called, do not modify it unless the new locking state is EXCLUSIVE_LOCK.
37507** See the comment above the #define of UNKNOWN_LOCK for an explanation
37508** of this.
37509*/
37510static int pagerLockDb(Pager *pPager, int eLock){
37511  int rc = SQLITE_OK;
37512
37513  assert( eLock==SHARED_LOCK || eLock==RESERVED_LOCK || eLock==EXCLUSIVE_LOCK );
37514  if( pPager->eLock<eLock || pPager->eLock==UNKNOWN_LOCK ){
37515    rc = sqlite3OsLock(pPager->fd, eLock);
37516    if( rc==SQLITE_OK && (pPager->eLock!=UNKNOWN_LOCK||eLock==EXCLUSIVE_LOCK) ){
37517      pPager->eLock = (u8)eLock;
37518      IOTRACE(("LOCK %p %d\n", pPager, eLock))
37519    }
37520  }
37521  return rc;
37522}
37523
37524/*
37525** This function determines whether or not the atomic-write optimization
37526** can be used with this pager. The optimization can be used if:
37527**
37528**  (a) the value returned by OsDeviceCharacteristics() indicates that
37529**      a database page may be written atomically, and
37530**  (b) the value returned by OsSectorSize() is less than or equal
37531**      to the page size.
37532**
37533** The optimization is also always enabled for temporary files. It is
37534** an error to call this function if pPager is opened on an in-memory
37535** database.
37536**
37537** If the optimization cannot be used, 0 is returned. If it can be used,
37538** then the value returned is the size of the journal file when it
37539** contains rollback data for exactly one page.
37540*/
37541#ifdef SQLITE_ENABLE_ATOMIC_WRITE
37542static int jrnlBufferSize(Pager *pPager){
37543  assert( !MEMDB );
37544  if( !pPager->tempFile ){
37545    int dc;                           /* Device characteristics */
37546    int nSector;                      /* Sector size */
37547    int szPage;                       /* Page size */
37548
37549    assert( isOpen(pPager->fd) );
37550    dc = sqlite3OsDeviceCharacteristics(pPager->fd);
37551    nSector = pPager->sectorSize;
37552    szPage = pPager->pageSize;
37553
37554    assert(SQLITE_IOCAP_ATOMIC512==(512>>8));
37555    assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8));
37556    if( 0==(dc&(SQLITE_IOCAP_ATOMIC|(szPage>>8)) || nSector>szPage) ){
37557      return 0;
37558    }
37559  }
37560
37561  return JOURNAL_HDR_SZ(pPager) + JOURNAL_PG_SZ(pPager);
37562}
37563#endif
37564
37565/*
37566** If SQLITE_CHECK_PAGES is defined then we do some sanity checking
37567** on the cache using a hash function.  This is used for testing
37568** and debugging only.
37569*/
37570#ifdef SQLITE_CHECK_PAGES
37571/*
37572** Return a 32-bit hash of the page data for pPage.
37573*/
37574static u32 pager_datahash(int nByte, unsigned char *pData){
37575  u32 hash = 0;
37576  int i;
37577  for(i=0; i<nByte; i++){
37578    hash = (hash*1039) + pData[i];
37579  }
37580  return hash;
37581}
37582static u32 pager_pagehash(PgHdr *pPage){
37583  return pager_datahash(pPage->pPager->pageSize, (unsigned char *)pPage->pData);
37584}
37585static void pager_set_pagehash(PgHdr *pPage){
37586  pPage->pageHash = pager_pagehash(pPage);
37587}
37588
37589/*
37590** The CHECK_PAGE macro takes a PgHdr* as an argument. If SQLITE_CHECK_PAGES
37591** is defined, and NDEBUG is not defined, an assert() statement checks
37592** that the page is either dirty or still matches the calculated page-hash.
37593*/
37594#define CHECK_PAGE(x) checkPage(x)
37595static void checkPage(PgHdr *pPg){
37596  Pager *pPager = pPg->pPager;
37597  assert( pPager->eState!=PAGER_ERROR );
37598  assert( (pPg->flags&PGHDR_DIRTY) || pPg->pageHash==pager_pagehash(pPg) );
37599}
37600
37601#else
37602#define pager_datahash(X,Y)  0
37603#define pager_pagehash(X)  0
37604#define pager_set_pagehash(X)
37605#define CHECK_PAGE(x)
37606#endif  /* SQLITE_CHECK_PAGES */
37607
37608/*
37609** When this is called the journal file for pager pPager must be open.
37610** This function attempts to read a master journal file name from the
37611** end of the file and, if successful, copies it into memory supplied
37612** by the caller. See comments above writeMasterJournal() for the format
37613** used to store a master journal file name at the end of a journal file.
37614**
37615** zMaster must point to a buffer of at least nMaster bytes allocated by
37616** the caller. This should be sqlite3_vfs.mxPathname+1 (to ensure there is
37617** enough space to write the master journal name). If the master journal
37618** name in the journal is longer than nMaster bytes (including a
37619** nul-terminator), then this is handled as if no master journal name
37620** were present in the journal.
37621**
37622** If a master journal file name is present at the end of the journal
37623** file, then it is copied into the buffer pointed to by zMaster. A
37624** nul-terminator byte is appended to the buffer following the master
37625** journal file name.
37626**
37627** If it is determined that no master journal file name is present
37628** zMaster[0] is set to 0 and SQLITE_OK returned.
37629**
37630** If an error occurs while reading from the journal file, an SQLite
37631** error code is returned.
37632*/
37633static int readMasterJournal(sqlite3_file *pJrnl, char *zMaster, u32 nMaster){
37634  int rc;                    /* Return code */
37635  u32 len;                   /* Length in bytes of master journal name */
37636  i64 szJ;                   /* Total size in bytes of journal file pJrnl */
37637  u32 cksum;                 /* MJ checksum value read from journal */
37638  u32 u;                     /* Unsigned loop counter */
37639  unsigned char aMagic[8];   /* A buffer to hold the magic header */
37640  zMaster[0] = '\0';
37641
37642  if( SQLITE_OK!=(rc = sqlite3OsFileSize(pJrnl, &szJ))
37643   || szJ<16
37644   || SQLITE_OK!=(rc = read32bits(pJrnl, szJ-16, &len))
37645   || len>=nMaster
37646   || SQLITE_OK!=(rc = read32bits(pJrnl, szJ-12, &cksum))
37647   || SQLITE_OK!=(rc = sqlite3OsRead(pJrnl, aMagic, 8, szJ-8))
37648   || memcmp(aMagic, aJournalMagic, 8)
37649   || SQLITE_OK!=(rc = sqlite3OsRead(pJrnl, zMaster, len, szJ-16-len))
37650  ){
37651    return rc;
37652  }
37653
37654  /* See if the checksum matches the master journal name */
37655  for(u=0; u<len; u++){
37656    cksum -= zMaster[u];
37657  }
37658  if( cksum ){
37659    /* If the checksum doesn't add up, then one or more of the disk sectors
37660    ** containing the master journal filename is corrupted. This means
37661    ** definitely roll back, so just return SQLITE_OK and report a (nul)
37662    ** master-journal filename.
37663    */
37664    len = 0;
37665  }
37666  zMaster[len] = '\0';
37667
37668  return SQLITE_OK;
37669}
37670
37671/*
37672** Return the offset of the sector boundary at or immediately
37673** following the value in pPager->journalOff, assuming a sector
37674** size of pPager->sectorSize bytes.
37675**
37676** i.e for a sector size of 512:
37677**
37678**   Pager.journalOff          Return value
37679**   ---------------------------------------
37680**   0                         0
37681**   512                       512
37682**   100                       512
37683**   2000                      2048
37684**
37685*/
37686static i64 journalHdrOffset(Pager *pPager){
37687  i64 offset = 0;
37688  i64 c = pPager->journalOff;
37689  if( c ){
37690    offset = ((c-1)/JOURNAL_HDR_SZ(pPager) + 1) * JOURNAL_HDR_SZ(pPager);
37691  }
37692  assert( offset%JOURNAL_HDR_SZ(pPager)==0 );
37693  assert( offset>=c );
37694  assert( (offset-c)<JOURNAL_HDR_SZ(pPager) );
37695  return offset;
37696}
37697
37698/*
37699** The journal file must be open when this function is called.
37700**
37701** This function is a no-op if the journal file has not been written to
37702** within the current transaction (i.e. if Pager.journalOff==0).
37703**
37704** If doTruncate is non-zero or the Pager.journalSizeLimit variable is
37705** set to 0, then truncate the journal file to zero bytes in size. Otherwise,
37706** zero the 28-byte header at the start of the journal file. In either case,
37707** if the pager is not in no-sync mode, sync the journal file immediately
37708** after writing or truncating it.
37709**
37710** If Pager.journalSizeLimit is set to a positive, non-zero value, and
37711** following the truncation or zeroing described above the size of the
37712** journal file in bytes is larger than this value, then truncate the
37713** journal file to Pager.journalSizeLimit bytes. The journal file does
37714** not need to be synced following this operation.
37715**
37716** If an IO error occurs, abandon processing and return the IO error code.
37717** Otherwise, return SQLITE_OK.
37718*/
37719static int zeroJournalHdr(Pager *pPager, int doTruncate){
37720  int rc = SQLITE_OK;                               /* Return code */
37721  assert( isOpen(pPager->jfd) );
37722  if( pPager->journalOff ){
37723    const i64 iLimit = pPager->journalSizeLimit;    /* Local cache of jsl */
37724
37725    IOTRACE(("JZEROHDR %p\n", pPager))
37726    if( doTruncate || iLimit==0 ){
37727      rc = sqlite3OsTruncate(pPager->jfd, 0);
37728    }else{
37729      static const char zeroHdr[28] = {0};
37730      rc = sqlite3OsWrite(pPager->jfd, zeroHdr, sizeof(zeroHdr), 0);
37731    }
37732    if( rc==SQLITE_OK && !pPager->noSync ){
37733      rc = sqlite3OsSync(pPager->jfd, SQLITE_SYNC_DATAONLY|pPager->syncFlags);
37734    }
37735
37736    /* At this point the transaction is committed but the write lock
37737    ** is still held on the file. If there is a size limit configured for
37738    ** the persistent journal and the journal file currently consumes more
37739    ** space than that limit allows for, truncate it now. There is no need
37740    ** to sync the file following this operation.
37741    */
37742    if( rc==SQLITE_OK && iLimit>0 ){
37743      i64 sz;
37744      rc = sqlite3OsFileSize(pPager->jfd, &sz);
37745      if( rc==SQLITE_OK && sz>iLimit ){
37746        rc = sqlite3OsTruncate(pPager->jfd, iLimit);
37747      }
37748    }
37749  }
37750  return rc;
37751}
37752
37753/*
37754** The journal file must be open when this routine is called. A journal
37755** header (JOURNAL_HDR_SZ bytes) is written into the journal file at the
37756** current location.
37757**
37758** The format for the journal header is as follows:
37759** - 8 bytes: Magic identifying journal format.
37760** - 4 bytes: Number of records in journal, or -1 no-sync mode is on.
37761** - 4 bytes: Random number used for page hash.
37762** - 4 bytes: Initial database page count.
37763** - 4 bytes: Sector size used by the process that wrote this journal.
37764** - 4 bytes: Database page size.
37765**
37766** Followed by (JOURNAL_HDR_SZ - 28) bytes of unused space.
37767*/
37768static int writeJournalHdr(Pager *pPager){
37769  int rc = SQLITE_OK;                 /* Return code */
37770  char *zHeader = pPager->pTmpSpace;  /* Temporary space used to build header */
37771  u32 nHeader = (u32)pPager->pageSize;/* Size of buffer pointed to by zHeader */
37772  u32 nWrite;                         /* Bytes of header sector written */
37773  int ii;                             /* Loop counter */
37774
37775  assert( isOpen(pPager->jfd) );      /* Journal file must be open. */
37776
37777  if( nHeader>JOURNAL_HDR_SZ(pPager) ){
37778    nHeader = JOURNAL_HDR_SZ(pPager);
37779  }
37780
37781  /* If there are active savepoints and any of them were created
37782  ** since the most recent journal header was written, update the
37783  ** PagerSavepoint.iHdrOffset fields now.
37784  */
37785  for(ii=0; ii<pPager->nSavepoint; ii++){
37786    if( pPager->aSavepoint[ii].iHdrOffset==0 ){
37787      pPager->aSavepoint[ii].iHdrOffset = pPager->journalOff;
37788    }
37789  }
37790
37791  pPager->journalHdr = pPager->journalOff = journalHdrOffset(pPager);
37792
37793  /*
37794  ** Write the nRec Field - the number of page records that follow this
37795  ** journal header. Normally, zero is written to this value at this time.
37796  ** After the records are added to the journal (and the journal synced,
37797  ** if in full-sync mode), the zero is overwritten with the true number
37798  ** of records (see syncJournal()).
37799  **
37800  ** A faster alternative is to write 0xFFFFFFFF to the nRec field. When
37801  ** reading the journal this value tells SQLite to assume that the
37802  ** rest of the journal file contains valid page records. This assumption
37803  ** is dangerous, as if a failure occurred whilst writing to the journal
37804  ** file it may contain some garbage data. There are two scenarios
37805  ** where this risk can be ignored:
37806  **
37807  **   * When the pager is in no-sync mode. Corruption can follow a
37808  **     power failure in this case anyway.
37809  **
37810  **   * When the SQLITE_IOCAP_SAFE_APPEND flag is set. This guarantees
37811  **     that garbage data is never appended to the journal file.
37812  */
37813  assert( isOpen(pPager->fd) || pPager->noSync );
37814  if( pPager->noSync || (pPager->journalMode==PAGER_JOURNALMODE_MEMORY)
37815   || (sqlite3OsDeviceCharacteristics(pPager->fd)&SQLITE_IOCAP_SAFE_APPEND)
37816  ){
37817    memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic));
37818    put32bits(&zHeader[sizeof(aJournalMagic)], 0xffffffff);
37819  }else{
37820    memset(zHeader, 0, sizeof(aJournalMagic)+4);
37821  }
37822
37823  /* The random check-hash initialiser */
37824  sqlite3_randomness(sizeof(pPager->cksumInit), &pPager->cksumInit);
37825  put32bits(&zHeader[sizeof(aJournalMagic)+4], pPager->cksumInit);
37826  /* The initial database size */
37827  put32bits(&zHeader[sizeof(aJournalMagic)+8], pPager->dbOrigSize);
37828  /* The assumed sector size for this process */
37829  put32bits(&zHeader[sizeof(aJournalMagic)+12], pPager->sectorSize);
37830
37831  /* The page size */
37832  put32bits(&zHeader[sizeof(aJournalMagic)+16], pPager->pageSize);
37833
37834  /* Initializing the tail of the buffer is not necessary.  Everything
37835  ** works find if the following memset() is omitted.  But initializing
37836  ** the memory prevents valgrind from complaining, so we are willing to
37837  ** take the performance hit.
37838  */
37839  memset(&zHeader[sizeof(aJournalMagic)+20], 0,
37840         nHeader-(sizeof(aJournalMagic)+20));
37841
37842  /* In theory, it is only necessary to write the 28 bytes that the
37843  ** journal header consumes to the journal file here. Then increment the
37844  ** Pager.journalOff variable by JOURNAL_HDR_SZ so that the next
37845  ** record is written to the following sector (leaving a gap in the file
37846  ** that will be implicitly filled in by the OS).
37847  **
37848  ** However it has been discovered that on some systems this pattern can
37849  ** be significantly slower than contiguously writing data to the file,
37850  ** even if that means explicitly writing data to the block of
37851  ** (JOURNAL_HDR_SZ - 28) bytes that will not be used. So that is what
37852  ** is done.
37853  **
37854  ** The loop is required here in case the sector-size is larger than the
37855  ** database page size. Since the zHeader buffer is only Pager.pageSize
37856  ** bytes in size, more than one call to sqlite3OsWrite() may be required
37857  ** to populate the entire journal header sector.
37858  */
37859  for(nWrite=0; rc==SQLITE_OK&&nWrite<JOURNAL_HDR_SZ(pPager); nWrite+=nHeader){
37860    IOTRACE(("JHDR %p %lld %d\n", pPager, pPager->journalHdr, nHeader))
37861    rc = sqlite3OsWrite(pPager->jfd, zHeader, nHeader, pPager->journalOff);
37862    assert( pPager->journalHdr <= pPager->journalOff );
37863    pPager->journalOff += nHeader;
37864  }
37865
37866  return rc;
37867}
37868
37869/*
37870** The journal file must be open when this is called. A journal header file
37871** (JOURNAL_HDR_SZ bytes) is read from the current location in the journal
37872** file. The current location in the journal file is given by
37873** pPager->journalOff. See comments above function writeJournalHdr() for
37874** a description of the journal header format.
37875**
37876** If the header is read successfully, *pNRec is set to the number of
37877** page records following this header and *pDbSize is set to the size of the
37878** database before the transaction began, in pages. Also, pPager->cksumInit
37879** is set to the value read from the journal header. SQLITE_OK is returned
37880** in this case.
37881**
37882** If the journal header file appears to be corrupted, SQLITE_DONE is
37883** returned and *pNRec and *PDbSize are undefined.  If JOURNAL_HDR_SZ bytes
37884** cannot be read from the journal file an error code is returned.
37885*/
37886static int readJournalHdr(
37887  Pager *pPager,               /* Pager object */
37888  int isHot,
37889  i64 journalSize,             /* Size of the open journal file in bytes */
37890  u32 *pNRec,                  /* OUT: Value read from the nRec field */
37891  u32 *pDbSize                 /* OUT: Value of original database size field */
37892){
37893  int rc;                      /* Return code */
37894  unsigned char aMagic[8];     /* A buffer to hold the magic header */
37895  i64 iHdrOff;                 /* Offset of journal header being read */
37896
37897  assert( isOpen(pPager->jfd) );      /* Journal file must be open. */
37898
37899  /* Advance Pager.journalOff to the start of the next sector. If the
37900  ** journal file is too small for there to be a header stored at this
37901  ** point, return SQLITE_DONE.
37902  */
37903  pPager->journalOff = journalHdrOffset(pPager);
37904  if( pPager->journalOff+JOURNAL_HDR_SZ(pPager) > journalSize ){
37905    return SQLITE_DONE;
37906  }
37907  iHdrOff = pPager->journalOff;
37908
37909  /* Read in the first 8 bytes of the journal header. If they do not match
37910  ** the  magic string found at the start of each journal header, return
37911  ** SQLITE_DONE. If an IO error occurs, return an error code. Otherwise,
37912  ** proceed.
37913  */
37914  if( isHot || iHdrOff!=pPager->journalHdr ){
37915    rc = sqlite3OsRead(pPager->jfd, aMagic, sizeof(aMagic), iHdrOff);
37916    if( rc ){
37917      return rc;
37918    }
37919    if( memcmp(aMagic, aJournalMagic, sizeof(aMagic))!=0 ){
37920      return SQLITE_DONE;
37921    }
37922  }
37923
37924  /* Read the first three 32-bit fields of the journal header: The nRec
37925  ** field, the checksum-initializer and the database size at the start
37926  ** of the transaction. Return an error code if anything goes wrong.
37927  */
37928  if( SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+8, pNRec))
37929   || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+12, &pPager->cksumInit))
37930   || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+16, pDbSize))
37931  ){
37932    return rc;
37933  }
37934
37935  if( pPager->journalOff==0 ){
37936    u32 iPageSize;               /* Page-size field of journal header */
37937    u32 iSectorSize;             /* Sector-size field of journal header */
37938
37939    /* Read the page-size and sector-size journal header fields. */
37940    if( SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+20, &iSectorSize))
37941     || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+24, &iPageSize))
37942    ){
37943      return rc;
37944    }
37945
37946    /* Versions of SQLite prior to 3.5.8 set the page-size field of the
37947    ** journal header to zero. In this case, assume that the Pager.pageSize
37948    ** variable is already set to the correct page size.
37949    */
37950    if( iPageSize==0 ){
37951      iPageSize = pPager->pageSize;
37952    }
37953
37954    /* Check that the values read from the page-size and sector-size fields
37955    ** are within range. To be 'in range', both values need to be a power
37956    ** of two greater than or equal to 512 or 32, and not greater than their
37957    ** respective compile time maximum limits.
37958    */
37959    if( iPageSize<512                  || iSectorSize<32
37960     || iPageSize>SQLITE_MAX_PAGE_SIZE || iSectorSize>MAX_SECTOR_SIZE
37961     || ((iPageSize-1)&iPageSize)!=0   || ((iSectorSize-1)&iSectorSize)!=0
37962    ){
37963      /* If the either the page-size or sector-size in the journal-header is
37964      ** invalid, then the process that wrote the journal-header must have
37965      ** crashed before the header was synced. In this case stop reading
37966      ** the journal file here.
37967      */
37968      return SQLITE_DONE;
37969    }
37970
37971    /* Update the page-size to match the value read from the journal.
37972    ** Use a testcase() macro to make sure that malloc failure within
37973    ** PagerSetPagesize() is tested.
37974    */
37975    rc = sqlite3PagerSetPagesize(pPager, &iPageSize, -1);
37976    testcase( rc!=SQLITE_OK );
37977
37978    /* Update the assumed sector-size to match the value used by
37979    ** the process that created this journal. If this journal was
37980    ** created by a process other than this one, then this routine
37981    ** is being called from within pager_playback(). The local value
37982    ** of Pager.sectorSize is restored at the end of that routine.
37983    */
37984    pPager->sectorSize = iSectorSize;
37985  }
37986
37987  pPager->journalOff += JOURNAL_HDR_SZ(pPager);
37988  return rc;
37989}
37990
37991
37992/*
37993** Write the supplied master journal name into the journal file for pager
37994** pPager at the current location. The master journal name must be the last
37995** thing written to a journal file. If the pager is in full-sync mode, the
37996** journal file descriptor is advanced to the next sector boundary before
37997** anything is written. The format is:
37998**
37999**   + 4 bytes: PAGER_MJ_PGNO.
38000**   + N bytes: Master journal filename in utf-8.
38001**   + 4 bytes: N (length of master journal name in bytes, no nul-terminator).
38002**   + 4 bytes: Master journal name checksum.
38003**   + 8 bytes: aJournalMagic[].
38004**
38005** The master journal page checksum is the sum of the bytes in the master
38006** journal name, where each byte is interpreted as a signed 8-bit integer.
38007**
38008** If zMaster is a NULL pointer (occurs for a single database transaction),
38009** this call is a no-op.
38010*/
38011static int writeMasterJournal(Pager *pPager, const char *zMaster){
38012  int rc;                          /* Return code */
38013  int nMaster;                     /* Length of string zMaster */
38014  i64 iHdrOff;                     /* Offset of header in journal file */
38015  i64 jrnlSize;                    /* Size of journal file on disk */
38016  u32 cksum = 0;                   /* Checksum of string zMaster */
38017
38018  assert( pPager->setMaster==0 );
38019  assert( !pagerUseWal(pPager) );
38020
38021  if( !zMaster
38022   || pPager->journalMode==PAGER_JOURNALMODE_MEMORY
38023   || pPager->journalMode==PAGER_JOURNALMODE_OFF
38024  ){
38025    return SQLITE_OK;
38026  }
38027  pPager->setMaster = 1;
38028  assert( isOpen(pPager->jfd) );
38029  assert( pPager->journalHdr <= pPager->journalOff );
38030
38031  /* Calculate the length in bytes and the checksum of zMaster */
38032  for(nMaster=0; zMaster[nMaster]; nMaster++){
38033    cksum += zMaster[nMaster];
38034  }
38035
38036  /* If in full-sync mode, advance to the next disk sector before writing
38037  ** the master journal name. This is in case the previous page written to
38038  ** the journal has already been synced.
38039  */
38040  if( pPager->fullSync ){
38041    pPager->journalOff = journalHdrOffset(pPager);
38042  }
38043  iHdrOff = pPager->journalOff;
38044
38045  /* Write the master journal data to the end of the journal file. If
38046  ** an error occurs, return the error code to the caller.
38047  */
38048  if( (0 != (rc = write32bits(pPager->jfd, iHdrOff, PAGER_MJ_PGNO(pPager))))
38049   || (0 != (rc = sqlite3OsWrite(pPager->jfd, zMaster, nMaster, iHdrOff+4)))
38050   || (0 != (rc = write32bits(pPager->jfd, iHdrOff+4+nMaster, nMaster)))
38051   || (0 != (rc = write32bits(pPager->jfd, iHdrOff+4+nMaster+4, cksum)))
38052   || (0 != (rc = sqlite3OsWrite(pPager->jfd, aJournalMagic, 8, iHdrOff+4+nMaster+8)))
38053  ){
38054    return rc;
38055  }
38056  pPager->journalOff += (nMaster+20);
38057
38058  /* If the pager is in peristent-journal mode, then the physical
38059  ** journal-file may extend past the end of the master-journal name
38060  ** and 8 bytes of magic data just written to the file. This is
38061  ** dangerous because the code to rollback a hot-journal file
38062  ** will not be able to find the master-journal name to determine
38063  ** whether or not the journal is hot.
38064  **
38065  ** Easiest thing to do in this scenario is to truncate the journal
38066  ** file to the required size.
38067  */
38068  if( SQLITE_OK==(rc = sqlite3OsFileSize(pPager->jfd, &jrnlSize))
38069   && jrnlSize>pPager->journalOff
38070  ){
38071    rc = sqlite3OsTruncate(pPager->jfd, pPager->journalOff);
38072  }
38073  return rc;
38074}
38075
38076/*
38077** Find a page in the hash table given its page number. Return
38078** a pointer to the page or NULL if the requested page is not
38079** already in memory.
38080*/
38081static PgHdr *pager_lookup(Pager *pPager, Pgno pgno){
38082  PgHdr *p;                         /* Return value */
38083
38084  /* It is not possible for a call to PcacheFetch() with createFlag==0 to
38085  ** fail, since no attempt to allocate dynamic memory will be made.
38086  */
38087  (void)sqlite3PcacheFetch(pPager->pPCache, pgno, 0, &p);
38088  return p;
38089}
38090
38091/*
38092** Discard the entire contents of the in-memory page-cache.
38093*/
38094static void pager_reset(Pager *pPager){
38095  sqlite3BackupRestart(pPager->pBackup);
38096  sqlite3PcacheClear(pPager->pPCache);
38097}
38098
38099/*
38100** Free all structures in the Pager.aSavepoint[] array and set both
38101** Pager.aSavepoint and Pager.nSavepoint to zero. Close the sub-journal
38102** if it is open and the pager is not in exclusive mode.
38103*/
38104static void releaseAllSavepoints(Pager *pPager){
38105  int ii;               /* Iterator for looping through Pager.aSavepoint */
38106  for(ii=0; ii<pPager->nSavepoint; ii++){
38107    sqlite3BitvecDestroy(pPager->aSavepoint[ii].pInSavepoint);
38108  }
38109  if( !pPager->exclusiveMode || sqlite3IsMemJournal(pPager->sjfd) ){
38110    sqlite3OsClose(pPager->sjfd);
38111  }
38112  sqlite3_free(pPager->aSavepoint);
38113  pPager->aSavepoint = 0;
38114  pPager->nSavepoint = 0;
38115  pPager->nSubRec = 0;
38116}
38117
38118/*
38119** Set the bit number pgno in the PagerSavepoint.pInSavepoint
38120** bitvecs of all open savepoints. Return SQLITE_OK if successful
38121** or SQLITE_NOMEM if a malloc failure occurs.
38122*/
38123static int addToSavepointBitvecs(Pager *pPager, Pgno pgno){
38124  int ii;                   /* Loop counter */
38125  int rc = SQLITE_OK;       /* Result code */
38126
38127  for(ii=0; ii<pPager->nSavepoint; ii++){
38128    PagerSavepoint *p = &pPager->aSavepoint[ii];
38129    if( pgno<=p->nOrig ){
38130      rc |= sqlite3BitvecSet(p->pInSavepoint, pgno);
38131      testcase( rc==SQLITE_NOMEM );
38132      assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
38133    }
38134  }
38135  return rc;
38136}
38137
38138/*
38139** This function is a no-op if the pager is in exclusive mode and not
38140** in the ERROR state. Otherwise, it switches the pager to PAGER_OPEN
38141** state.
38142**
38143** If the pager is not in exclusive-access mode, the database file is
38144** completely unlocked. If the file is unlocked and the file-system does
38145** not exhibit the UNDELETABLE_WHEN_OPEN property, the journal file is
38146** closed (if it is open).
38147**
38148** If the pager is in ERROR state when this function is called, the
38149** contents of the pager cache are discarded before switching back to
38150** the OPEN state. Regardless of whether the pager is in exclusive-mode
38151** or not, any journal file left in the file-system will be treated
38152** as a hot-journal and rolled back the next time a read-transaction
38153** is opened (by this or by any other connection).
38154*/
38155static void pager_unlock(Pager *pPager){
38156
38157  assert( pPager->eState==PAGER_READER
38158       || pPager->eState==PAGER_OPEN
38159       || pPager->eState==PAGER_ERROR
38160  );
38161
38162  sqlite3BitvecDestroy(pPager->pInJournal);
38163  pPager->pInJournal = 0;
38164  releaseAllSavepoints(pPager);
38165
38166  if( pagerUseWal(pPager) ){
38167    assert( !isOpen(pPager->jfd) );
38168    sqlite3WalEndReadTransaction(pPager->pWal);
38169    pPager->eState = PAGER_OPEN;
38170  }else if( !pPager->exclusiveMode ){
38171    int rc;                       /* Error code returned by pagerUnlockDb() */
38172    int iDc = isOpen(pPager->fd)?sqlite3OsDeviceCharacteristics(pPager->fd):0;
38173
38174    /* If the operating system support deletion of open files, then
38175    ** close the journal file when dropping the database lock.  Otherwise
38176    ** another connection with journal_mode=delete might delete the file
38177    ** out from under us.
38178    */
38179    assert( (PAGER_JOURNALMODE_MEMORY   & 5)!=1 );
38180    assert( (PAGER_JOURNALMODE_OFF      & 5)!=1 );
38181    assert( (PAGER_JOURNALMODE_WAL      & 5)!=1 );
38182    assert( (PAGER_JOURNALMODE_DELETE   & 5)!=1 );
38183    assert( (PAGER_JOURNALMODE_TRUNCATE & 5)==1 );
38184    assert( (PAGER_JOURNALMODE_PERSIST  & 5)==1 );
38185    if( 0==(iDc & SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN)
38186     || 1!=(pPager->journalMode & 5)
38187    ){
38188      sqlite3OsClose(pPager->jfd);
38189    }
38190
38191    /* If the pager is in the ERROR state and the call to unlock the database
38192    ** file fails, set the current lock to UNKNOWN_LOCK. See the comment
38193    ** above the #define for UNKNOWN_LOCK for an explanation of why this
38194    ** is necessary.
38195    */
38196    rc = pagerUnlockDb(pPager, NO_LOCK);
38197    if( rc!=SQLITE_OK && pPager->eState==PAGER_ERROR ){
38198      pPager->eLock = UNKNOWN_LOCK;
38199    }
38200
38201    /* The pager state may be changed from PAGER_ERROR to PAGER_OPEN here
38202    ** without clearing the error code. This is intentional - the error
38203    ** code is cleared and the cache reset in the block below.
38204    */
38205    assert( pPager->errCode || pPager->eState!=PAGER_ERROR );
38206    pPager->changeCountDone = 0;
38207    pPager->eState = PAGER_OPEN;
38208  }
38209
38210  /* If Pager.errCode is set, the contents of the pager cache cannot be
38211  ** trusted. Now that there are no outstanding references to the pager,
38212  ** it can safely move back to PAGER_OPEN state. This happens in both
38213  ** normal and exclusive-locking mode.
38214  */
38215  if( pPager->errCode ){
38216    assert( !MEMDB );
38217    pager_reset(pPager);
38218    pPager->changeCountDone = pPager->tempFile;
38219    pPager->eState = PAGER_OPEN;
38220    pPager->errCode = SQLITE_OK;
38221  }
38222
38223  pPager->journalOff = 0;
38224  pPager->journalHdr = 0;
38225  pPager->setMaster = 0;
38226}
38227
38228/*
38229** This function is called whenever an IOERR or FULL error that requires
38230** the pager to transition into the ERROR state may ahve occurred.
38231** The first argument is a pointer to the pager structure, the second
38232** the error-code about to be returned by a pager API function. The
38233** value returned is a copy of the second argument to this function.
38234**
38235** If the second argument is SQLITE_FULL, SQLITE_IOERR or one of the
38236** IOERR sub-codes, the pager enters the ERROR state and the error code
38237** is stored in Pager.errCode. While the pager remains in the ERROR state,
38238** all major API calls on the Pager will immediately return Pager.errCode.
38239**
38240** The ERROR state indicates that the contents of the pager-cache
38241** cannot be trusted. This state can be cleared by completely discarding
38242** the contents of the pager-cache. If a transaction was active when
38243** the persistent error occurred, then the rollback journal may need
38244** to be replayed to restore the contents of the database file (as if
38245** it were a hot-journal).
38246*/
38247static int pager_error(Pager *pPager, int rc){
38248  int rc2 = rc & 0xff;
38249  assert( rc==SQLITE_OK || !MEMDB );
38250  assert(
38251       pPager->errCode==SQLITE_FULL ||
38252       pPager->errCode==SQLITE_OK ||
38253       (pPager->errCode & 0xff)==SQLITE_IOERR
38254  );
38255  if( rc2==SQLITE_FULL || rc2==SQLITE_IOERR ){
38256    pPager->errCode = rc;
38257    pPager->eState = PAGER_ERROR;
38258  }
38259  return rc;
38260}
38261
38262/*
38263** This routine ends a transaction. A transaction is usually ended by
38264** either a COMMIT or a ROLLBACK operation. This routine may be called
38265** after rollback of a hot-journal, or if an error occurs while opening
38266** the journal file or writing the very first journal-header of a
38267** database transaction.
38268**
38269** This routine is never called in PAGER_ERROR state. If it is called
38270** in PAGER_NONE or PAGER_SHARED state and the lock held is less
38271** exclusive than a RESERVED lock, it is a no-op.
38272**
38273** Otherwise, any active savepoints are released.
38274**
38275** If the journal file is open, then it is "finalized". Once a journal
38276** file has been finalized it is not possible to use it to roll back a
38277** transaction. Nor will it be considered to be a hot-journal by this
38278** or any other database connection. Exactly how a journal is finalized
38279** depends on whether or not the pager is running in exclusive mode and
38280** the current journal-mode (Pager.journalMode value), as follows:
38281**
38282**   journalMode==MEMORY
38283**     Journal file descriptor is simply closed. This destroys an
38284**     in-memory journal.
38285**
38286**   journalMode==TRUNCATE
38287**     Journal file is truncated to zero bytes in size.
38288**
38289**   journalMode==PERSIST
38290**     The first 28 bytes of the journal file are zeroed. This invalidates
38291**     the first journal header in the file, and hence the entire journal
38292**     file. An invalid journal file cannot be rolled back.
38293**
38294**   journalMode==DELETE
38295**     The journal file is closed and deleted using sqlite3OsDelete().
38296**
38297**     If the pager is running in exclusive mode, this method of finalizing
38298**     the journal file is never used. Instead, if the journalMode is
38299**     DELETE and the pager is in exclusive mode, the method described under
38300**     journalMode==PERSIST is used instead.
38301**
38302** After the journal is finalized, the pager moves to PAGER_READER state.
38303** If running in non-exclusive rollback mode, the lock on the file is
38304** downgraded to a SHARED_LOCK.
38305**
38306** SQLITE_OK is returned if no error occurs. If an error occurs during
38307** any of the IO operations to finalize the journal file or unlock the
38308** database then the IO error code is returned to the user. If the
38309** operation to finalize the journal file fails, then the code still
38310** tries to unlock the database file if not in exclusive mode. If the
38311** unlock operation fails as well, then the first error code related
38312** to the first error encountered (the journal finalization one) is
38313** returned.
38314*/
38315static int pager_end_transaction(Pager *pPager, int hasMaster){
38316  int rc = SQLITE_OK;      /* Error code from journal finalization operation */
38317  int rc2 = SQLITE_OK;     /* Error code from db file unlock operation */
38318
38319  /* Do nothing if the pager does not have an open write transaction
38320  ** or at least a RESERVED lock. This function may be called when there
38321  ** is no write-transaction active but a RESERVED or greater lock is
38322  ** held under two circumstances:
38323  **
38324  **   1. After a successful hot-journal rollback, it is called with
38325  **      eState==PAGER_NONE and eLock==EXCLUSIVE_LOCK.
38326  **
38327  **   2. If a connection with locking_mode=exclusive holding an EXCLUSIVE
38328  **      lock switches back to locking_mode=normal and then executes a
38329  **      read-transaction, this function is called with eState==PAGER_READER
38330  **      and eLock==EXCLUSIVE_LOCK when the read-transaction is closed.
38331  */
38332  assert( assert_pager_state(pPager) );
38333  assert( pPager->eState!=PAGER_ERROR );
38334  if( pPager->eState<PAGER_WRITER_LOCKED && pPager->eLock<RESERVED_LOCK ){
38335    return SQLITE_OK;
38336  }
38337
38338  releaseAllSavepoints(pPager);
38339  assert( isOpen(pPager->jfd) || pPager->pInJournal==0 );
38340  if( isOpen(pPager->jfd) ){
38341    assert( !pagerUseWal(pPager) );
38342
38343    /* Finalize the journal file. */
38344    if( sqlite3IsMemJournal(pPager->jfd) ){
38345      assert( pPager->journalMode==PAGER_JOURNALMODE_MEMORY );
38346      sqlite3OsClose(pPager->jfd);
38347    }else if( pPager->journalMode==PAGER_JOURNALMODE_TRUNCATE ){
38348      if( pPager->journalOff==0 ){
38349        rc = SQLITE_OK;
38350      }else{
38351        rc = sqlite3OsTruncate(pPager->jfd, 0);
38352      }
38353      pPager->journalOff = 0;
38354    }else if( pPager->journalMode==PAGER_JOURNALMODE_PERSIST
38355      || (pPager->exclusiveMode && pPager->journalMode!=PAGER_JOURNALMODE_WAL)
38356    ){
38357      rc = zeroJournalHdr(pPager, hasMaster);
38358      pPager->journalOff = 0;
38359    }else{
38360      /* This branch may be executed with Pager.journalMode==MEMORY if
38361      ** a hot-journal was just rolled back. In this case the journal
38362      ** file should be closed and deleted. If this connection writes to
38363      ** the database file, it will do so using an in-memory journal.
38364      */
38365      assert( pPager->journalMode==PAGER_JOURNALMODE_DELETE
38366           || pPager->journalMode==PAGER_JOURNALMODE_MEMORY
38367           || pPager->journalMode==PAGER_JOURNALMODE_WAL
38368      );
38369      sqlite3OsClose(pPager->jfd);
38370      if( !pPager->tempFile ){
38371        rc = sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
38372      }
38373    }
38374  }
38375
38376#ifdef SQLITE_CHECK_PAGES
38377  sqlite3PcacheIterateDirty(pPager->pPCache, pager_set_pagehash);
38378  if( pPager->dbSize==0 && sqlite3PcacheRefCount(pPager->pPCache)>0 ){
38379    PgHdr *p = pager_lookup(pPager, 1);
38380    if( p ){
38381      p->pageHash = 0;
38382      sqlite3PagerUnref(p);
38383    }
38384  }
38385#endif
38386
38387  sqlite3BitvecDestroy(pPager->pInJournal);
38388  pPager->pInJournal = 0;
38389  pPager->nRec = 0;
38390  sqlite3PcacheCleanAll(pPager->pPCache);
38391  sqlite3PcacheTruncate(pPager->pPCache, pPager->dbSize);
38392
38393  if( pagerUseWal(pPager) ){
38394    /* Drop the WAL write-lock, if any. Also, if the connection was in
38395    ** locking_mode=exclusive mode but is no longer, drop the EXCLUSIVE
38396    ** lock held on the database file.
38397    */
38398    rc2 = sqlite3WalEndWriteTransaction(pPager->pWal);
38399    assert( rc2==SQLITE_OK );
38400  }
38401  if( !pPager->exclusiveMode
38402   && (!pagerUseWal(pPager) || sqlite3WalExclusiveMode(pPager->pWal, 0))
38403  ){
38404    rc2 = pagerUnlockDb(pPager, SHARED_LOCK);
38405    pPager->changeCountDone = 0;
38406  }
38407  pPager->eState = PAGER_READER;
38408  pPager->setMaster = 0;
38409
38410  return (rc==SQLITE_OK?rc2:rc);
38411}
38412
38413/*
38414** Execute a rollback if a transaction is active and unlock the
38415** database file.
38416**
38417** If the pager has already entered the ERROR state, do not attempt
38418** the rollback at this time. Instead, pager_unlock() is called. The
38419** call to pager_unlock() will discard all in-memory pages, unlock
38420** the database file and move the pager back to OPEN state. If this
38421** means that there is a hot-journal left in the file-system, the next
38422** connection to obtain a shared lock on the pager (which may be this one)
38423** will roll it back.
38424**
38425** If the pager has not already entered the ERROR state, but an IO or
38426** malloc error occurs during a rollback, then this will itself cause
38427** the pager to enter the ERROR state. Which will be cleared by the
38428** call to pager_unlock(), as described above.
38429*/
38430static void pagerUnlockAndRollback(Pager *pPager){
38431  if( pPager->eState!=PAGER_ERROR && pPager->eState!=PAGER_OPEN ){
38432    assert( assert_pager_state(pPager) );
38433    if( pPager->eState>=PAGER_WRITER_LOCKED ){
38434      sqlite3BeginBenignMalloc();
38435      sqlite3PagerRollback(pPager);
38436      sqlite3EndBenignMalloc();
38437    }else if( !pPager->exclusiveMode ){
38438      assert( pPager->eState==PAGER_READER );
38439      pager_end_transaction(pPager, 0);
38440    }
38441  }
38442  pager_unlock(pPager);
38443}
38444
38445/*
38446** Parameter aData must point to a buffer of pPager->pageSize bytes
38447** of data. Compute and return a checksum based ont the contents of the
38448** page of data and the current value of pPager->cksumInit.
38449**
38450** This is not a real checksum. It is really just the sum of the
38451** random initial value (pPager->cksumInit) and every 200th byte
38452** of the page data, starting with byte offset (pPager->pageSize%200).
38453** Each byte is interpreted as an 8-bit unsigned integer.
38454**
38455** Changing the formula used to compute this checksum results in an
38456** incompatible journal file format.
38457**
38458** If journal corruption occurs due to a power failure, the most likely
38459** scenario is that one end or the other of the record will be changed.
38460** It is much less likely that the two ends of the journal record will be
38461** correct and the middle be corrupt.  Thus, this "checksum" scheme,
38462** though fast and simple, catches the mostly likely kind of corruption.
38463*/
38464static u32 pager_cksum(Pager *pPager, const u8 *aData){
38465  u32 cksum = pPager->cksumInit;         /* Checksum value to return */
38466  int i = pPager->pageSize-200;          /* Loop counter */
38467  while( i>0 ){
38468    cksum += aData[i];
38469    i -= 200;
38470  }
38471  return cksum;
38472}
38473
38474/*
38475** Report the current page size and number of reserved bytes back
38476** to the codec.
38477*/
38478#ifdef SQLITE_HAS_CODEC
38479static void pagerReportSize(Pager *pPager){
38480  if( pPager->xCodecSizeChng ){
38481    pPager->xCodecSizeChng(pPager->pCodec, pPager->pageSize,
38482                           (int)pPager->nReserve);
38483  }
38484}
38485#else
38486# define pagerReportSize(X)     /* No-op if we do not support a codec */
38487#endif
38488
38489/*
38490** Read a single page from either the journal file (if isMainJrnl==1) or
38491** from the sub-journal (if isMainJrnl==0) and playback that page.
38492** The page begins at offset *pOffset into the file. The *pOffset
38493** value is increased to the start of the next page in the journal.
38494**
38495** The main rollback journal uses checksums - the statement journal does
38496** not.
38497**
38498** If the page number of the page record read from the (sub-)journal file
38499** is greater than the current value of Pager.dbSize, then playback is
38500** skipped and SQLITE_OK is returned.
38501**
38502** If pDone is not NULL, then it is a record of pages that have already
38503** been played back.  If the page at *pOffset has already been played back
38504** (if the corresponding pDone bit is set) then skip the playback.
38505** Make sure the pDone bit corresponding to the *pOffset page is set
38506** prior to returning.
38507**
38508** If the page record is successfully read from the (sub-)journal file
38509** and played back, then SQLITE_OK is returned. If an IO error occurs
38510** while reading the record from the (sub-)journal file or while writing
38511** to the database file, then the IO error code is returned. If data
38512** is successfully read from the (sub-)journal file but appears to be
38513** corrupted, SQLITE_DONE is returned. Data is considered corrupted in
38514** two circumstances:
38515**
38516**   * If the record page-number is illegal (0 or PAGER_MJ_PGNO), or
38517**   * If the record is being rolled back from the main journal file
38518**     and the checksum field does not match the record content.
38519**
38520** Neither of these two scenarios are possible during a savepoint rollback.
38521**
38522** If this is a savepoint rollback, then memory may have to be dynamically
38523** allocated by this function. If this is the case and an allocation fails,
38524** SQLITE_NOMEM is returned.
38525*/
38526static int pager_playback_one_page(
38527  Pager *pPager,                /* The pager being played back */
38528  i64 *pOffset,                 /* Offset of record to playback */
38529  Bitvec *pDone,                /* Bitvec of pages already played back */
38530  int isMainJrnl,               /* 1 -> main journal. 0 -> sub-journal. */
38531  int isSavepnt                 /* True for a savepoint rollback */
38532){
38533  int rc;
38534  PgHdr *pPg;                   /* An existing page in the cache */
38535  Pgno pgno;                    /* The page number of a page in journal */
38536  u32 cksum;                    /* Checksum used for sanity checking */
38537  char *aData;                  /* Temporary storage for the page */
38538  sqlite3_file *jfd;            /* The file descriptor for the journal file */
38539  int isSynced;                 /* True if journal page is synced */
38540
38541  assert( (isMainJrnl&~1)==0 );      /* isMainJrnl is 0 or 1 */
38542  assert( (isSavepnt&~1)==0 );       /* isSavepnt is 0 or 1 */
38543  assert( isMainJrnl || pDone );     /* pDone always used on sub-journals */
38544  assert( isSavepnt || pDone==0 );   /* pDone never used on non-savepoint */
38545
38546  aData = pPager->pTmpSpace;
38547  assert( aData );         /* Temp storage must have already been allocated */
38548  assert( pagerUseWal(pPager)==0 || (!isMainJrnl && isSavepnt) );
38549
38550  /* Either the state is greater than PAGER_WRITER_CACHEMOD (a transaction
38551  ** or savepoint rollback done at the request of the caller) or this is
38552  ** a hot-journal rollback. If it is a hot-journal rollback, the pager
38553  ** is in state OPEN and holds an EXCLUSIVE lock. Hot-journal rollback
38554  ** only reads from the main journal, not the sub-journal.
38555  */
38556  assert( pPager->eState>=PAGER_WRITER_CACHEMOD
38557       || (pPager->eState==PAGER_OPEN && pPager->eLock==EXCLUSIVE_LOCK)
38558  );
38559  assert( pPager->eState>=PAGER_WRITER_CACHEMOD || isMainJrnl );
38560
38561  /* Read the page number and page data from the journal or sub-journal
38562  ** file. Return an error code to the caller if an IO error occurs.
38563  */
38564  jfd = isMainJrnl ? pPager->jfd : pPager->sjfd;
38565  rc = read32bits(jfd, *pOffset, &pgno);
38566  if( rc!=SQLITE_OK ) return rc;
38567  rc = sqlite3OsRead(jfd, (u8*)aData, pPager->pageSize, (*pOffset)+4);
38568  if( rc!=SQLITE_OK ) return rc;
38569  *pOffset += pPager->pageSize + 4 + isMainJrnl*4;
38570
38571  /* Sanity checking on the page.  This is more important that I originally
38572  ** thought.  If a power failure occurs while the journal is being written,
38573  ** it could cause invalid data to be written into the journal.  We need to
38574  ** detect this invalid data (with high probability) and ignore it.
38575  */
38576  if( pgno==0 || pgno==PAGER_MJ_PGNO(pPager) ){
38577    assert( !isSavepnt );
38578    return SQLITE_DONE;
38579  }
38580  if( pgno>(Pgno)pPager->dbSize || sqlite3BitvecTest(pDone, pgno) ){
38581    return SQLITE_OK;
38582  }
38583  if( isMainJrnl ){
38584    rc = read32bits(jfd, (*pOffset)-4, &cksum);
38585    if( rc ) return rc;
38586    if( !isSavepnt && pager_cksum(pPager, (u8*)aData)!=cksum ){
38587      return SQLITE_DONE;
38588    }
38589  }
38590
38591  /* If this page has already been played by before during the current
38592  ** rollback, then don't bother to play it back again.
38593  */
38594  if( pDone && (rc = sqlite3BitvecSet(pDone, pgno))!=SQLITE_OK ){
38595    return rc;
38596  }
38597
38598  /* When playing back page 1, restore the nReserve setting
38599  */
38600  if( pgno==1 && pPager->nReserve!=((u8*)aData)[20] ){
38601    pPager->nReserve = ((u8*)aData)[20];
38602    pagerReportSize(pPager);
38603  }
38604
38605  /* If the pager is in CACHEMOD state, then there must be a copy of this
38606  ** page in the pager cache. In this case just update the pager cache,
38607  ** not the database file. The page is left marked dirty in this case.
38608  **
38609  ** An exception to the above rule: If the database is in no-sync mode
38610  ** and a page is moved during an incremental vacuum then the page may
38611  ** not be in the pager cache. Later: if a malloc() or IO error occurs
38612  ** during a Movepage() call, then the page may not be in the cache
38613  ** either. So the condition described in the above paragraph is not
38614  ** assert()able.
38615  **
38616  ** If in WRITER_DBMOD, WRITER_FINISHED or OPEN state, then we update the
38617  ** pager cache if it exists and the main file. The page is then marked
38618  ** not dirty. Since this code is only executed in PAGER_OPEN state for
38619  ** a hot-journal rollback, it is guaranteed that the page-cache is empty
38620  ** if the pager is in OPEN state.
38621  **
38622  ** Ticket #1171:  The statement journal might contain page content that is
38623  ** different from the page content at the start of the transaction.
38624  ** This occurs when a page is changed prior to the start of a statement
38625  ** then changed again within the statement.  When rolling back such a
38626  ** statement we must not write to the original database unless we know
38627  ** for certain that original page contents are synced into the main rollback
38628  ** journal.  Otherwise, a power loss might leave modified data in the
38629  ** database file without an entry in the rollback journal that can
38630  ** restore the database to its original form.  Two conditions must be
38631  ** met before writing to the database files. (1) the database must be
38632  ** locked.  (2) we know that the original page content is fully synced
38633  ** in the main journal either because the page is not in cache or else
38634  ** the page is marked as needSync==0.
38635  **
38636  ** 2008-04-14:  When attempting to vacuum a corrupt database file, it
38637  ** is possible to fail a statement on a database that does not yet exist.
38638  ** Do not attempt to write if database file has never been opened.
38639  */
38640  if( pagerUseWal(pPager) ){
38641    pPg = 0;
38642  }else{
38643    pPg = pager_lookup(pPager, pgno);
38644  }
38645  assert( pPg || !MEMDB );
38646  assert( pPager->eState!=PAGER_OPEN || pPg==0 );
38647  PAGERTRACE(("PLAYBACK %d page %d hash(%08x) %s\n",
38648           PAGERID(pPager), pgno, pager_datahash(pPager->pageSize, (u8*)aData),
38649           (isMainJrnl?"main-journal":"sub-journal")
38650  ));
38651  if( isMainJrnl ){
38652    isSynced = pPager->noSync || (*pOffset <= pPager->journalHdr);
38653  }else{
38654    isSynced = (pPg==0 || 0==(pPg->flags & PGHDR_NEED_SYNC));
38655  }
38656  if( isOpen(pPager->fd)
38657   && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
38658   && isSynced
38659  ){
38660    i64 ofst = (pgno-1)*(i64)pPager->pageSize;
38661    testcase( !isSavepnt && pPg!=0 && (pPg->flags&PGHDR_NEED_SYNC)!=0 );
38662    assert( !pagerUseWal(pPager) );
38663    rc = sqlite3OsWrite(pPager->fd, (u8*)aData, pPager->pageSize, ofst);
38664    if( pgno>pPager->dbFileSize ){
38665      pPager->dbFileSize = pgno;
38666    }
38667    if( pPager->pBackup ){
38668      CODEC1(pPager, aData, pgno, 3, rc=SQLITE_NOMEM);
38669      sqlite3BackupUpdate(pPager->pBackup, pgno, (u8*)aData);
38670      CODEC2(pPager, aData, pgno, 7, rc=SQLITE_NOMEM, aData);
38671    }
38672  }else if( !isMainJrnl && pPg==0 ){
38673    /* If this is a rollback of a savepoint and data was not written to
38674    ** the database and the page is not in-memory, there is a potential
38675    ** problem. When the page is next fetched by the b-tree layer, it
38676    ** will be read from the database file, which may or may not be
38677    ** current.
38678    **
38679    ** There are a couple of different ways this can happen. All are quite
38680    ** obscure. When running in synchronous mode, this can only happen
38681    ** if the page is on the free-list at the start of the transaction, then
38682    ** populated, then moved using sqlite3PagerMovepage().
38683    **
38684    ** The solution is to add an in-memory page to the cache containing
38685    ** the data just read from the sub-journal. Mark the page as dirty
38686    ** and if the pager requires a journal-sync, then mark the page as
38687    ** requiring a journal-sync before it is written.
38688    */
38689    assert( isSavepnt );
38690    assert( pPager->doNotSpill==0 );
38691    pPager->doNotSpill++;
38692    rc = sqlite3PagerAcquire(pPager, pgno, &pPg, 1);
38693    assert( pPager->doNotSpill==1 );
38694    pPager->doNotSpill--;
38695    if( rc!=SQLITE_OK ) return rc;
38696    pPg->flags &= ~PGHDR_NEED_READ;
38697    sqlite3PcacheMakeDirty(pPg);
38698  }
38699  if( pPg ){
38700    /* No page should ever be explicitly rolled back that is in use, except
38701    ** for page 1 which is held in use in order to keep the lock on the
38702    ** database active. However such a page may be rolled back as a result
38703    ** of an internal error resulting in an automatic call to
38704    ** sqlite3PagerRollback().
38705    */
38706    void *pData;
38707    pData = pPg->pData;
38708    memcpy(pData, (u8*)aData, pPager->pageSize);
38709    pPager->xReiniter(pPg);
38710    if( isMainJrnl && (!isSavepnt || *pOffset<=pPager->journalHdr) ){
38711      /* If the contents of this page were just restored from the main
38712      ** journal file, then its content must be as they were when the
38713      ** transaction was first opened. In this case we can mark the page
38714      ** as clean, since there will be no need to write it out to the
38715      ** database.
38716      **
38717      ** There is one exception to this rule. If the page is being rolled
38718      ** back as part of a savepoint (or statement) rollback from an
38719      ** unsynced portion of the main journal file, then it is not safe
38720      ** to mark the page as clean. This is because marking the page as
38721      ** clean will clear the PGHDR_NEED_SYNC flag. Since the page is
38722      ** already in the journal file (recorded in Pager.pInJournal) and
38723      ** the PGHDR_NEED_SYNC flag is cleared, if the page is written to
38724      ** again within this transaction, it will be marked as dirty but
38725      ** the PGHDR_NEED_SYNC flag will not be set. It could then potentially
38726      ** be written out into the database file before its journal file
38727      ** segment is synced. If a crash occurs during or following this,
38728      ** database corruption may ensue.
38729      */
38730      assert( !pagerUseWal(pPager) );
38731      sqlite3PcacheMakeClean(pPg);
38732    }
38733    pager_set_pagehash(pPg);
38734
38735    /* If this was page 1, then restore the value of Pager.dbFileVers.
38736    ** Do this before any decoding. */
38737    if( pgno==1 ){
38738      memcpy(&pPager->dbFileVers, &((u8*)pData)[24],sizeof(pPager->dbFileVers));
38739    }
38740
38741    /* Decode the page just read from disk */
38742    CODEC1(pPager, pData, pPg->pgno, 3, rc=SQLITE_NOMEM);
38743    sqlite3PcacheRelease(pPg);
38744  }
38745  return rc;
38746}
38747
38748/*
38749** Parameter zMaster is the name of a master journal file. A single journal
38750** file that referred to the master journal file has just been rolled back.
38751** This routine checks if it is possible to delete the master journal file,
38752** and does so if it is.
38753**
38754** Argument zMaster may point to Pager.pTmpSpace. So that buffer is not
38755** available for use within this function.
38756**
38757** When a master journal file is created, it is populated with the names
38758** of all of its child journals, one after another, formatted as utf-8
38759** encoded text. The end of each child journal file is marked with a
38760** nul-terminator byte (0x00). i.e. the entire contents of a master journal
38761** file for a transaction involving two databases might be:
38762**
38763**   "/home/bill/a.db-journal\x00/home/bill/b.db-journal\x00"
38764**
38765** A master journal file may only be deleted once all of its child
38766** journals have been rolled back.
38767**
38768** This function reads the contents of the master-journal file into
38769** memory and loops through each of the child journal names. For
38770** each child journal, it checks if:
38771**
38772**   * if the child journal exists, and if so
38773**   * if the child journal contains a reference to master journal
38774**     file zMaster
38775**
38776** If a child journal can be found that matches both of the criteria
38777** above, this function returns without doing anything. Otherwise, if
38778** no such child journal can be found, file zMaster is deleted from
38779** the file-system using sqlite3OsDelete().
38780**
38781** If an IO error within this function, an error code is returned. This
38782** function allocates memory by calling sqlite3Malloc(). If an allocation
38783** fails, SQLITE_NOMEM is returned. Otherwise, if no IO or malloc errors
38784** occur, SQLITE_OK is returned.
38785**
38786** TODO: This function allocates a single block of memory to load
38787** the entire contents of the master journal file. This could be
38788** a couple of kilobytes or so - potentially larger than the page
38789** size.
38790*/
38791static int pager_delmaster(Pager *pPager, const char *zMaster){
38792  sqlite3_vfs *pVfs = pPager->pVfs;
38793  int rc;                   /* Return code */
38794  sqlite3_file *pMaster;    /* Malloc'd master-journal file descriptor */
38795  sqlite3_file *pJournal;   /* Malloc'd child-journal file descriptor */
38796  char *zMasterJournal = 0; /* Contents of master journal file */
38797  i64 nMasterJournal;       /* Size of master journal file */
38798  char *zJournal;           /* Pointer to one journal within MJ file */
38799  char *zMasterPtr;         /* Space to hold MJ filename from a journal file */
38800  int nMasterPtr;           /* Amount of space allocated to zMasterPtr[] */
38801
38802  /* Allocate space for both the pJournal and pMaster file descriptors.
38803  ** If successful, open the master journal file for reading.
38804  */
38805  pMaster = (sqlite3_file *)sqlite3MallocZero(pVfs->szOsFile * 2);
38806  pJournal = (sqlite3_file *)(((u8 *)pMaster) + pVfs->szOsFile);
38807  if( !pMaster ){
38808    rc = SQLITE_NOMEM;
38809  }else{
38810    const int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_MASTER_JOURNAL);
38811    rc = sqlite3OsOpen(pVfs, zMaster, pMaster, flags, 0);
38812  }
38813  if( rc!=SQLITE_OK ) goto delmaster_out;
38814
38815  /* Load the entire master journal file into space obtained from
38816  ** sqlite3_malloc() and pointed to by zMasterJournal.   Also obtain
38817  ** sufficient space (in zMasterPtr) to hold the names of master
38818  ** journal files extracted from regular rollback-journals.
38819  */
38820  rc = sqlite3OsFileSize(pMaster, &nMasterJournal);
38821  if( rc!=SQLITE_OK ) goto delmaster_out;
38822  nMasterPtr = pVfs->mxPathname+1;
38823  zMasterJournal = sqlite3Malloc((int)nMasterJournal + nMasterPtr + 1);
38824  if( !zMasterJournal ){
38825    rc = SQLITE_NOMEM;
38826    goto delmaster_out;
38827  }
38828  zMasterPtr = &zMasterJournal[nMasterJournal+1];
38829  rc = sqlite3OsRead(pMaster, zMasterJournal, (int)nMasterJournal, 0);
38830  if( rc!=SQLITE_OK ) goto delmaster_out;
38831  zMasterJournal[nMasterJournal] = 0;
38832
38833  zJournal = zMasterJournal;
38834  while( (zJournal-zMasterJournal)<nMasterJournal ){
38835    int exists;
38836    rc = sqlite3OsAccess(pVfs, zJournal, SQLITE_ACCESS_EXISTS, &exists);
38837    if( rc!=SQLITE_OK ){
38838      goto delmaster_out;
38839    }
38840    if( exists ){
38841      /* One of the journals pointed to by the master journal exists.
38842      ** Open it and check if it points at the master journal. If
38843      ** so, return without deleting the master journal file.
38844      */
38845      int c;
38846      int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_MAIN_JOURNAL);
38847      rc = sqlite3OsOpen(pVfs, zJournal, pJournal, flags, 0);
38848      if( rc!=SQLITE_OK ){
38849        goto delmaster_out;
38850      }
38851
38852      rc = readMasterJournal(pJournal, zMasterPtr, nMasterPtr);
38853      sqlite3OsClose(pJournal);
38854      if( rc!=SQLITE_OK ){
38855        goto delmaster_out;
38856      }
38857
38858      c = zMasterPtr[0]!=0 && strcmp(zMasterPtr, zMaster)==0;
38859      if( c ){
38860        /* We have a match. Do not delete the master journal file. */
38861        goto delmaster_out;
38862      }
38863    }
38864    zJournal += (sqlite3Strlen30(zJournal)+1);
38865  }
38866
38867  sqlite3OsClose(pMaster);
38868  rc = sqlite3OsDelete(pVfs, zMaster, 0);
38869
38870delmaster_out:
38871  sqlite3_free(zMasterJournal);
38872  if( pMaster ){
38873    sqlite3OsClose(pMaster);
38874    assert( !isOpen(pJournal) );
38875    sqlite3_free(pMaster);
38876  }
38877  return rc;
38878}
38879
38880
38881/*
38882** This function is used to change the actual size of the database
38883** file in the file-system. This only happens when committing a transaction,
38884** or rolling back a transaction (including rolling back a hot-journal).
38885**
38886** If the main database file is not open, or the pager is not in either
38887** DBMOD or OPEN state, this function is a no-op. Otherwise, the size
38888** of the file is changed to nPage pages (nPage*pPager->pageSize bytes).
38889** If the file on disk is currently larger than nPage pages, then use the VFS
38890** xTruncate() method to truncate it.
38891**
38892** Or, it might might be the case that the file on disk is smaller than
38893** nPage pages. Some operating system implementations can get confused if
38894** you try to truncate a file to some size that is larger than it
38895** currently is, so detect this case and write a single zero byte to
38896** the end of the new file instead.
38897**
38898** If successful, return SQLITE_OK. If an IO error occurs while modifying
38899** the database file, return the error code to the caller.
38900*/
38901static int pager_truncate(Pager *pPager, Pgno nPage){
38902  int rc = SQLITE_OK;
38903  assert( pPager->eState!=PAGER_ERROR );
38904  assert( pPager->eState!=PAGER_READER );
38905
38906  if( isOpen(pPager->fd)
38907   && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
38908  ){
38909    i64 currentSize, newSize;
38910    int szPage = pPager->pageSize;
38911    assert( pPager->eLock==EXCLUSIVE_LOCK );
38912    /* TODO: Is it safe to use Pager.dbFileSize here? */
38913    rc = sqlite3OsFileSize(pPager->fd, &currentSize);
38914    newSize = szPage*(i64)nPage;
38915    if( rc==SQLITE_OK && currentSize!=newSize ){
38916      if( currentSize>newSize ){
38917        rc = sqlite3OsTruncate(pPager->fd, newSize);
38918      }else{
38919        char *pTmp = pPager->pTmpSpace;
38920        memset(pTmp, 0, szPage);
38921        testcase( (newSize-szPage) <  currentSize );
38922        testcase( (newSize-szPage) == currentSize );
38923        testcase( (newSize-szPage) >  currentSize );
38924        rc = sqlite3OsWrite(pPager->fd, pTmp, szPage, newSize-szPage);
38925      }
38926      if( rc==SQLITE_OK ){
38927        pPager->dbFileSize = nPage;
38928      }
38929    }
38930  }
38931  return rc;
38932}
38933
38934/*
38935** Set the value of the Pager.sectorSize variable for the given
38936** pager based on the value returned by the xSectorSize method
38937** of the open database file. The sector size will be used used
38938** to determine the size and alignment of journal header and
38939** master journal pointers within created journal files.
38940**
38941** For temporary files the effective sector size is always 512 bytes.
38942**
38943** Otherwise, for non-temporary files, the effective sector size is
38944** the value returned by the xSectorSize() method rounded up to 32 if
38945** it is less than 32, or rounded down to MAX_SECTOR_SIZE if it
38946** is greater than MAX_SECTOR_SIZE.
38947*/
38948static void setSectorSize(Pager *pPager){
38949  assert( isOpen(pPager->fd) || pPager->tempFile );
38950
38951  if( !pPager->tempFile ){
38952    /* Sector size doesn't matter for temporary files. Also, the file
38953    ** may not have been opened yet, in which case the OsSectorSize()
38954    ** call will segfault.
38955    */
38956    pPager->sectorSize = sqlite3OsSectorSize(pPager->fd);
38957  }
38958  if( pPager->sectorSize<32 ){
38959    pPager->sectorSize = 512;
38960  }
38961  if( pPager->sectorSize>MAX_SECTOR_SIZE ){
38962    assert( MAX_SECTOR_SIZE>=512 );
38963    pPager->sectorSize = MAX_SECTOR_SIZE;
38964  }
38965}
38966
38967/*
38968** Playback the journal and thus restore the database file to
38969** the state it was in before we started making changes.
38970**
38971** The journal file format is as follows:
38972**
38973**  (1)  8 byte prefix.  A copy of aJournalMagic[].
38974**  (2)  4 byte big-endian integer which is the number of valid page records
38975**       in the journal.  If this value is 0xffffffff, then compute the
38976**       number of page records from the journal size.
38977**  (3)  4 byte big-endian integer which is the initial value for the
38978**       sanity checksum.
38979**  (4)  4 byte integer which is the number of pages to truncate the
38980**       database to during a rollback.
38981**  (5)  4 byte big-endian integer which is the sector size.  The header
38982**       is this many bytes in size.
38983**  (6)  4 byte big-endian integer which is the page size.
38984**  (7)  zero padding out to the next sector size.
38985**  (8)  Zero or more pages instances, each as follows:
38986**        +  4 byte page number.
38987**        +  pPager->pageSize bytes of data.
38988**        +  4 byte checksum
38989**
38990** When we speak of the journal header, we mean the first 7 items above.
38991** Each entry in the journal is an instance of the 8th item.
38992**
38993** Call the value from the second bullet "nRec".  nRec is the number of
38994** valid page entries in the journal.  In most cases, you can compute the
38995** value of nRec from the size of the journal file.  But if a power
38996** failure occurred while the journal was being written, it could be the
38997** case that the size of the journal file had already been increased but
38998** the extra entries had not yet made it safely to disk.  In such a case,
38999** the value of nRec computed from the file size would be too large.  For
39000** that reason, we always use the nRec value in the header.
39001**
39002** If the nRec value is 0xffffffff it means that nRec should be computed
39003** from the file size.  This value is used when the user selects the
39004** no-sync option for the journal.  A power failure could lead to corruption
39005** in this case.  But for things like temporary table (which will be
39006** deleted when the power is restored) we don't care.
39007**
39008** If the file opened as the journal file is not a well-formed
39009** journal file then all pages up to the first corrupted page are rolled
39010** back (or no pages if the journal header is corrupted). The journal file
39011** is then deleted and SQLITE_OK returned, just as if no corruption had
39012** been encountered.
39013**
39014** If an I/O or malloc() error occurs, the journal-file is not deleted
39015** and an error code is returned.
39016**
39017** The isHot parameter indicates that we are trying to rollback a journal
39018** that might be a hot journal.  Or, it could be that the journal is
39019** preserved because of JOURNALMODE_PERSIST or JOURNALMODE_TRUNCATE.
39020** If the journal really is hot, reset the pager cache prior rolling
39021** back any content.  If the journal is merely persistent, no reset is
39022** needed.
39023*/
39024static int pager_playback(Pager *pPager, int isHot){
39025  sqlite3_vfs *pVfs = pPager->pVfs;
39026  i64 szJ;                 /* Size of the journal file in bytes */
39027  u32 nRec;                /* Number of Records in the journal */
39028  u32 u;                   /* Unsigned loop counter */
39029  Pgno mxPg = 0;           /* Size of the original file in pages */
39030  int rc;                  /* Result code of a subroutine */
39031  int res = 1;             /* Value returned by sqlite3OsAccess() */
39032  char *zMaster = 0;       /* Name of master journal file if any */
39033  int needPagerReset;      /* True to reset page prior to first page rollback */
39034
39035  /* Figure out how many records are in the journal.  Abort early if
39036  ** the journal is empty.
39037  */
39038  assert( isOpen(pPager->jfd) );
39039  rc = sqlite3OsFileSize(pPager->jfd, &szJ);
39040  if( rc!=SQLITE_OK ){
39041    goto end_playback;
39042  }
39043
39044  /* Read the master journal name from the journal, if it is present.
39045  ** If a master journal file name is specified, but the file is not
39046  ** present on disk, then the journal is not hot and does not need to be
39047  ** played back.
39048  **
39049  ** TODO: Technically the following is an error because it assumes that
39050  ** buffer Pager.pTmpSpace is (mxPathname+1) bytes or larger. i.e. that
39051  ** (pPager->pageSize >= pPager->pVfs->mxPathname+1). Using os_unix.c,
39052  **  mxPathname is 512, which is the same as the minimum allowable value
39053  ** for pageSize.
39054  */
39055  zMaster = pPager->pTmpSpace;
39056  rc = readMasterJournal(pPager->jfd, zMaster, pPager->pVfs->mxPathname+1);
39057  if( rc==SQLITE_OK && zMaster[0] ){
39058    rc = sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS, &res);
39059  }
39060  zMaster = 0;
39061  if( rc!=SQLITE_OK || !res ){
39062    goto end_playback;
39063  }
39064  pPager->journalOff = 0;
39065  needPagerReset = isHot;
39066
39067  /* This loop terminates either when a readJournalHdr() or
39068  ** pager_playback_one_page() call returns SQLITE_DONE or an IO error
39069  ** occurs.
39070  */
39071  while( 1 ){
39072    /* Read the next journal header from the journal file.  If there are
39073    ** not enough bytes left in the journal file for a complete header, or
39074    ** it is corrupted, then a process must have failed while writing it.
39075    ** This indicates nothing more needs to be rolled back.
39076    */
39077    rc = readJournalHdr(pPager, isHot, szJ, &nRec, &mxPg);
39078    if( rc!=SQLITE_OK ){
39079      if( rc==SQLITE_DONE ){
39080        rc = SQLITE_OK;
39081      }
39082      goto end_playback;
39083    }
39084
39085    /* If nRec is 0xffffffff, then this journal was created by a process
39086    ** working in no-sync mode. This means that the rest of the journal
39087    ** file consists of pages, there are no more journal headers. Compute
39088    ** the value of nRec based on this assumption.
39089    */
39090    if( nRec==0xffffffff ){
39091      assert( pPager->journalOff==JOURNAL_HDR_SZ(pPager) );
39092      nRec = (int)((szJ - JOURNAL_HDR_SZ(pPager))/JOURNAL_PG_SZ(pPager));
39093    }
39094
39095    /* If nRec is 0 and this rollback is of a transaction created by this
39096    ** process and if this is the final header in the journal, then it means
39097    ** that this part of the journal was being filled but has not yet been
39098    ** synced to disk.  Compute the number of pages based on the remaining
39099    ** size of the file.
39100    **
39101    ** The third term of the test was added to fix ticket #2565.
39102    ** When rolling back a hot journal, nRec==0 always means that the next
39103    ** chunk of the journal contains zero pages to be rolled back.  But
39104    ** when doing a ROLLBACK and the nRec==0 chunk is the last chunk in
39105    ** the journal, it means that the journal might contain additional
39106    ** pages that need to be rolled back and that the number of pages
39107    ** should be computed based on the journal file size.
39108    */
39109    if( nRec==0 && !isHot &&
39110        pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff ){
39111      nRec = (int)((szJ - pPager->journalOff) / JOURNAL_PG_SZ(pPager));
39112    }
39113
39114    /* If this is the first header read from the journal, truncate the
39115    ** database file back to its original size.
39116    */
39117    if( pPager->journalOff==JOURNAL_HDR_SZ(pPager) ){
39118      rc = pager_truncate(pPager, mxPg);
39119      if( rc!=SQLITE_OK ){
39120        goto end_playback;
39121      }
39122      pPager->dbSize = mxPg;
39123    }
39124
39125    /* Copy original pages out of the journal and back into the
39126    ** database file and/or page cache.
39127    */
39128    for(u=0; u<nRec; u++){
39129      if( needPagerReset ){
39130        pager_reset(pPager);
39131        needPagerReset = 0;
39132      }
39133      rc = pager_playback_one_page(pPager,&pPager->journalOff,0,1,0);
39134      if( rc!=SQLITE_OK ){
39135        if( rc==SQLITE_DONE ){
39136          rc = SQLITE_OK;
39137          pPager->journalOff = szJ;
39138          break;
39139        }else if( rc==SQLITE_IOERR_SHORT_READ ){
39140          /* If the journal has been truncated, simply stop reading and
39141          ** processing the journal. This might happen if the journal was
39142          ** not completely written and synced prior to a crash.  In that
39143          ** case, the database should have never been written in the
39144          ** first place so it is OK to simply abandon the rollback. */
39145          rc = SQLITE_OK;
39146          goto end_playback;
39147        }else{
39148          /* If we are unable to rollback, quit and return the error
39149          ** code.  This will cause the pager to enter the error state
39150          ** so that no further harm will be done.  Perhaps the next
39151          ** process to come along will be able to rollback the database.
39152          */
39153          goto end_playback;
39154        }
39155      }
39156    }
39157  }
39158  /*NOTREACHED*/
39159  assert( 0 );
39160
39161end_playback:
39162  /* Following a rollback, the database file should be back in its original
39163  ** state prior to the start of the transaction, so invoke the
39164  ** SQLITE_FCNTL_DB_UNCHANGED file-control method to disable the
39165  ** assertion that the transaction counter was modified.
39166  */
39167  assert(
39168    pPager->fd->pMethods==0 ||
39169    sqlite3OsFileControl(pPager->fd,SQLITE_FCNTL_DB_UNCHANGED,0)>=SQLITE_OK
39170  );
39171
39172  /* If this playback is happening automatically as a result of an IO or
39173  ** malloc error that occurred after the change-counter was updated but
39174  ** before the transaction was committed, then the change-counter
39175  ** modification may just have been reverted. If this happens in exclusive
39176  ** mode, then subsequent transactions performed by the connection will not
39177  ** update the change-counter at all. This may lead to cache inconsistency
39178  ** problems for other processes at some point in the future. So, just
39179  ** in case this has happened, clear the changeCountDone flag now.
39180  */
39181  pPager->changeCountDone = pPager->tempFile;
39182
39183  if( rc==SQLITE_OK ){
39184    zMaster = pPager->pTmpSpace;
39185    rc = readMasterJournal(pPager->jfd, zMaster, pPager->pVfs->mxPathname+1);
39186    testcase( rc!=SQLITE_OK );
39187  }
39188  if( rc==SQLITE_OK
39189   && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
39190  ){
39191    rc = sqlite3PagerSync(pPager);
39192  }
39193  if( rc==SQLITE_OK ){
39194    rc = pager_end_transaction(pPager, zMaster[0]!='\0');
39195    testcase( rc!=SQLITE_OK );
39196  }
39197  if( rc==SQLITE_OK && zMaster[0] && res ){
39198    /* If there was a master journal and this routine will return success,
39199    ** see if it is possible to delete the master journal.
39200    */
39201    rc = pager_delmaster(pPager, zMaster);
39202    testcase( rc!=SQLITE_OK );
39203  }
39204
39205  /* The Pager.sectorSize variable may have been updated while rolling
39206  ** back a journal created by a process with a different sector size
39207  ** value. Reset it to the correct value for this process.
39208  */
39209  setSectorSize(pPager);
39210  return rc;
39211}
39212
39213
39214/*
39215** Read the content for page pPg out of the database file and into
39216** pPg->pData. A shared lock or greater must be held on the database
39217** file before this function is called.
39218**
39219** If page 1 is read, then the value of Pager.dbFileVers[] is set to
39220** the value read from the database file.
39221**
39222** If an IO error occurs, then the IO error is returned to the caller.
39223** Otherwise, SQLITE_OK is returned.
39224*/
39225static int readDbPage(PgHdr *pPg){
39226  Pager *pPager = pPg->pPager; /* Pager object associated with page pPg */
39227  Pgno pgno = pPg->pgno;       /* Page number to read */
39228  int rc = SQLITE_OK;          /* Return code */
39229  int isInWal = 0;             /* True if page is in log file */
39230  int pgsz = pPager->pageSize; /* Number of bytes to read */
39231
39232  assert( pPager->eState>=PAGER_READER && !MEMDB );
39233  assert( isOpen(pPager->fd) );
39234
39235  if( NEVER(!isOpen(pPager->fd)) ){
39236    assert( pPager->tempFile );
39237    memset(pPg->pData, 0, pPager->pageSize);
39238    return SQLITE_OK;
39239  }
39240
39241  if( pagerUseWal(pPager) ){
39242    /* Try to pull the page from the write-ahead log. */
39243    rc = sqlite3WalRead(pPager->pWal, pgno, &isInWal, pgsz, pPg->pData);
39244  }
39245  if( rc==SQLITE_OK && !isInWal ){
39246    i64 iOffset = (pgno-1)*(i64)pPager->pageSize;
39247    rc = sqlite3OsRead(pPager->fd, pPg->pData, pgsz, iOffset);
39248    if( rc==SQLITE_IOERR_SHORT_READ ){
39249      rc = SQLITE_OK;
39250    }
39251  }
39252
39253  if( pgno==1 ){
39254    if( rc ){
39255      /* If the read is unsuccessful, set the dbFileVers[] to something
39256      ** that will never be a valid file version.  dbFileVers[] is a copy
39257      ** of bytes 24..39 of the database.  Bytes 28..31 should always be
39258      ** zero or the size of the database in page. Bytes 32..35 and 35..39
39259      ** should be page numbers which are never 0xffffffff.  So filling
39260      ** pPager->dbFileVers[] with all 0xff bytes should suffice.
39261      **
39262      ** For an encrypted database, the situation is more complex:  bytes
39263      ** 24..39 of the database are white noise.  But the probability of
39264      ** white noising equaling 16 bytes of 0xff is vanishingly small so
39265      ** we should still be ok.
39266      */
39267      memset(pPager->dbFileVers, 0xff, sizeof(pPager->dbFileVers));
39268    }else{
39269      u8 *dbFileVers = &((u8*)pPg->pData)[24];
39270      memcpy(&pPager->dbFileVers, dbFileVers, sizeof(pPager->dbFileVers));
39271    }
39272  }
39273  CODEC1(pPager, pPg->pData, pgno, 3, rc = SQLITE_NOMEM);
39274
39275  PAGER_INCR(sqlite3_pager_readdb_count);
39276  PAGER_INCR(pPager->nRead);
39277  IOTRACE(("PGIN %p %d\n", pPager, pgno));
39278  PAGERTRACE(("FETCH %d page %d hash(%08x)\n",
39279               PAGERID(pPager), pgno, pager_pagehash(pPg)));
39280
39281  return rc;
39282}
39283
39284/*
39285** Update the value of the change-counter at offsets 24 and 92 in
39286** the header and the sqlite version number at offset 96.
39287**
39288** This is an unconditional update.  See also the pager_incr_changecounter()
39289** routine which only updates the change-counter if the update is actually
39290** needed, as determined by the pPager->changeCountDone state variable.
39291*/
39292static void pager_write_changecounter(PgHdr *pPg){
39293  u32 change_counter;
39294
39295  /* Increment the value just read and write it back to byte 24. */
39296  change_counter = sqlite3Get4byte((u8*)pPg->pPager->dbFileVers)+1;
39297  put32bits(((char*)pPg->pData)+24, change_counter);
39298
39299  /* Also store the SQLite version number in bytes 96..99 and in
39300  ** bytes 92..95 store the change counter for which the version number
39301  ** is valid. */
39302  put32bits(((char*)pPg->pData)+92, change_counter);
39303  put32bits(((char*)pPg->pData)+96, SQLITE_VERSION_NUMBER);
39304}
39305
39306#ifndef SQLITE_OMIT_WAL
39307/*
39308** This function is invoked once for each page that has already been
39309** written into the log file when a WAL transaction is rolled back.
39310** Parameter iPg is the page number of said page. The pCtx argument
39311** is actually a pointer to the Pager structure.
39312**
39313** If page iPg is present in the cache, and has no outstanding references,
39314** it is discarded. Otherwise, if there are one or more outstanding
39315** references, the page content is reloaded from the database. If the
39316** attempt to reload content from the database is required and fails,
39317** return an SQLite error code. Otherwise, SQLITE_OK.
39318*/
39319static int pagerUndoCallback(void *pCtx, Pgno iPg){
39320  int rc = SQLITE_OK;
39321  Pager *pPager = (Pager *)pCtx;
39322  PgHdr *pPg;
39323
39324  pPg = sqlite3PagerLookup(pPager, iPg);
39325  if( pPg ){
39326    if( sqlite3PcachePageRefcount(pPg)==1 ){
39327      sqlite3PcacheDrop(pPg);
39328    }else{
39329      rc = readDbPage(pPg);
39330      if( rc==SQLITE_OK ){
39331        pPager->xReiniter(pPg);
39332      }
39333      sqlite3PagerUnref(pPg);
39334    }
39335  }
39336
39337  /* Normally, if a transaction is rolled back, any backup processes are
39338  ** updated as data is copied out of the rollback journal and into the
39339  ** database. This is not generally possible with a WAL database, as
39340  ** rollback involves simply truncating the log file. Therefore, if one
39341  ** or more frames have already been written to the log (and therefore
39342  ** also copied into the backup databases) as part of this transaction,
39343  ** the backups must be restarted.
39344  */
39345  sqlite3BackupRestart(pPager->pBackup);
39346
39347  return rc;
39348}
39349
39350/*
39351** This function is called to rollback a transaction on a WAL database.
39352*/
39353static int pagerRollbackWal(Pager *pPager){
39354  int rc;                         /* Return Code */
39355  PgHdr *pList;                   /* List of dirty pages to revert */
39356
39357  /* For all pages in the cache that are currently dirty or have already
39358  ** been written (but not committed) to the log file, do one of the
39359  ** following:
39360  **
39361  **   + Discard the cached page (if refcount==0), or
39362  **   + Reload page content from the database (if refcount>0).
39363  */
39364  pPager->dbSize = pPager->dbOrigSize;
39365  rc = sqlite3WalUndo(pPager->pWal, pagerUndoCallback, (void *)pPager);
39366  pList = sqlite3PcacheDirtyList(pPager->pPCache);
39367  while( pList && rc==SQLITE_OK ){
39368    PgHdr *pNext = pList->pDirty;
39369    rc = pagerUndoCallback((void *)pPager, pList->pgno);
39370    pList = pNext;
39371  }
39372
39373  return rc;
39374}
39375
39376/*
39377** This function is a wrapper around sqlite3WalFrames(). As well as logging
39378** the contents of the list of pages headed by pList (connected by pDirty),
39379** this function notifies any active backup processes that the pages have
39380** changed.
39381**
39382** The list of pages passed into this routine is always sorted by page number.
39383** Hence, if page 1 appears anywhere on the list, it will be the first page.
39384*/
39385static int pagerWalFrames(
39386  Pager *pPager,                  /* Pager object */
39387  PgHdr *pList,                   /* List of frames to log */
39388  Pgno nTruncate,                 /* Database size after this commit */
39389  int isCommit,                   /* True if this is a commit */
39390  int syncFlags                   /* Flags to pass to OsSync() (or 0) */
39391){
39392  int rc;                         /* Return code */
39393#if defined(SQLITE_DEBUG) || defined(SQLITE_CHECK_PAGES)
39394  PgHdr *p;                       /* For looping over pages */
39395#endif
39396
39397  assert( pPager->pWal );
39398#ifdef SQLITE_DEBUG
39399  /* Verify that the page list is in accending order */
39400  for(p=pList; p && p->pDirty; p=p->pDirty){
39401    assert( p->pgno < p->pDirty->pgno );
39402  }
39403#endif
39404
39405  if( isCommit ){
39406    /* If a WAL transaction is being committed, there is no point in writing
39407    ** any pages with page numbers greater than nTruncate into the WAL file.
39408    ** They will never be read by any client. So remove them from the pDirty
39409    ** list here. */
39410    PgHdr *p;
39411    PgHdr **ppNext = &pList;
39412    for(p=pList; (*ppNext = p); p=p->pDirty){
39413      if( p->pgno<=nTruncate ) ppNext = &p->pDirty;
39414    }
39415    assert( pList );
39416  }
39417
39418  if( pList->pgno==1 ) pager_write_changecounter(pList);
39419  rc = sqlite3WalFrames(pPager->pWal,
39420      pPager->pageSize, pList, nTruncate, isCommit, syncFlags
39421  );
39422  if( rc==SQLITE_OK && pPager->pBackup ){
39423    PgHdr *p;
39424    for(p=pList; p; p=p->pDirty){
39425      sqlite3BackupUpdate(pPager->pBackup, p->pgno, (u8 *)p->pData);
39426    }
39427  }
39428
39429#ifdef SQLITE_CHECK_PAGES
39430  pList = sqlite3PcacheDirtyList(pPager->pPCache);
39431  for(p=pList; p; p=p->pDirty){
39432    pager_set_pagehash(p);
39433  }
39434#endif
39435
39436  return rc;
39437}
39438
39439/*
39440** Begin a read transaction on the WAL.
39441**
39442** This routine used to be called "pagerOpenSnapshot()" because it essentially
39443** makes a snapshot of the database at the current point in time and preserves
39444** that snapshot for use by the reader in spite of concurrently changes by
39445** other writers or checkpointers.
39446*/
39447static int pagerBeginReadTransaction(Pager *pPager){
39448  int rc;                         /* Return code */
39449  int changed = 0;                /* True if cache must be reset */
39450
39451  assert( pagerUseWal(pPager) );
39452  assert( pPager->eState==PAGER_OPEN || pPager->eState==PAGER_READER );
39453
39454  /* sqlite3WalEndReadTransaction() was not called for the previous
39455  ** transaction in locking_mode=EXCLUSIVE.  So call it now.  If we
39456  ** are in locking_mode=NORMAL and EndRead() was previously called,
39457  ** the duplicate call is harmless.
39458  */
39459  sqlite3WalEndReadTransaction(pPager->pWal);
39460
39461  rc = sqlite3WalBeginReadTransaction(pPager->pWal, &changed);
39462  if( rc!=SQLITE_OK || changed ){
39463    pager_reset(pPager);
39464  }
39465
39466  return rc;
39467}
39468#endif
39469
39470/*
39471** This function is called as part of the transition from PAGER_OPEN
39472** to PAGER_READER state to determine the size of the database file
39473** in pages (assuming the page size currently stored in Pager.pageSize).
39474**
39475** If no error occurs, SQLITE_OK is returned and the size of the database
39476** in pages is stored in *pnPage. Otherwise, an error code (perhaps
39477** SQLITE_IOERR_FSTAT) is returned and *pnPage is left unmodified.
39478*/
39479static int pagerPagecount(Pager *pPager, Pgno *pnPage){
39480  Pgno nPage;                     /* Value to return via *pnPage */
39481
39482  /* Query the WAL sub-system for the database size. The WalDbsize()
39483  ** function returns zero if the WAL is not open (i.e. Pager.pWal==0), or
39484  ** if the database size is not available. The database size is not
39485  ** available from the WAL sub-system if the log file is empty or
39486  ** contains no valid committed transactions.
39487  */
39488  assert( pPager->eState==PAGER_OPEN );
39489  assert( pPager->eLock>=SHARED_LOCK || pPager->noReadlock );
39490  nPage = sqlite3WalDbsize(pPager->pWal);
39491
39492  /* If the database size was not available from the WAL sub-system,
39493  ** determine it based on the size of the database file. If the size
39494  ** of the database file is not an integer multiple of the page-size,
39495  ** round down to the nearest page. Except, any file larger than 0
39496  ** bytes in size is considered to contain at least one page.
39497  */
39498  if( nPage==0 ){
39499    i64 n = 0;                    /* Size of db file in bytes */
39500    assert( isOpen(pPager->fd) || pPager->tempFile );
39501    if( isOpen(pPager->fd) ){
39502      int rc = sqlite3OsFileSize(pPager->fd, &n);
39503      if( rc!=SQLITE_OK ){
39504        return rc;
39505      }
39506    }
39507    nPage = (Pgno)(n / pPager->pageSize);
39508    if( nPage==0 && n>0 ){
39509      nPage = 1;
39510    }
39511  }
39512
39513  /* If the current number of pages in the file is greater than the
39514  ** configured maximum pager number, increase the allowed limit so
39515  ** that the file can be read.
39516  */
39517  if( nPage>pPager->mxPgno ){
39518    pPager->mxPgno = (Pgno)nPage;
39519  }
39520
39521  *pnPage = nPage;
39522  return SQLITE_OK;
39523}
39524
39525#ifndef SQLITE_OMIT_WAL
39526/*
39527** Check if the *-wal file that corresponds to the database opened by pPager
39528** exists if the database is not empy, or verify that the *-wal file does
39529** not exist (by deleting it) if the database file is empty.
39530**
39531** If the database is not empty and the *-wal file exists, open the pager
39532** in WAL mode.  If the database is empty or if no *-wal file exists and
39533** if no error occurs, make sure Pager.journalMode is not set to
39534** PAGER_JOURNALMODE_WAL.
39535**
39536** Return SQLITE_OK or an error code.
39537**
39538** The caller must hold a SHARED lock on the database file to call this
39539** function. Because an EXCLUSIVE lock on the db file is required to delete
39540** a WAL on a none-empty database, this ensures there is no race condition
39541** between the xAccess() below and an xDelete() being executed by some
39542** other connection.
39543*/
39544static int pagerOpenWalIfPresent(Pager *pPager){
39545  int rc = SQLITE_OK;
39546  assert( pPager->eState==PAGER_OPEN );
39547  assert( pPager->eLock>=SHARED_LOCK || pPager->noReadlock );
39548
39549  if( !pPager->tempFile ){
39550    int isWal;                    /* True if WAL file exists */
39551    Pgno nPage;                   /* Size of the database file */
39552
39553    rc = pagerPagecount(pPager, &nPage);
39554    if( rc ) return rc;
39555    if( nPage==0 ){
39556      rc = sqlite3OsDelete(pPager->pVfs, pPager->zWal, 0);
39557      isWal = 0;
39558    }else{
39559      rc = sqlite3OsAccess(
39560          pPager->pVfs, pPager->zWal, SQLITE_ACCESS_EXISTS, &isWal
39561      );
39562    }
39563    if( rc==SQLITE_OK ){
39564      if( isWal ){
39565        testcase( sqlite3PcachePagecount(pPager->pPCache)==0 );
39566        rc = sqlite3PagerOpenWal(pPager, 0);
39567      }else if( pPager->journalMode==PAGER_JOURNALMODE_WAL ){
39568        pPager->journalMode = PAGER_JOURNALMODE_DELETE;
39569      }
39570    }
39571  }
39572  return rc;
39573}
39574#endif
39575
39576/*
39577** Playback savepoint pSavepoint. Or, if pSavepoint==NULL, then playback
39578** the entire master journal file. The case pSavepoint==NULL occurs when
39579** a ROLLBACK TO command is invoked on a SAVEPOINT that is a transaction
39580** savepoint.
39581**
39582** When pSavepoint is not NULL (meaning a non-transaction savepoint is
39583** being rolled back), then the rollback consists of up to three stages,
39584** performed in the order specified:
39585**
39586**   * Pages are played back from the main journal starting at byte
39587**     offset PagerSavepoint.iOffset and continuing to
39588**     PagerSavepoint.iHdrOffset, or to the end of the main journal
39589**     file if PagerSavepoint.iHdrOffset is zero.
39590**
39591**   * If PagerSavepoint.iHdrOffset is not zero, then pages are played
39592**     back starting from the journal header immediately following
39593**     PagerSavepoint.iHdrOffset to the end of the main journal file.
39594**
39595**   * Pages are then played back from the sub-journal file, starting
39596**     with the PagerSavepoint.iSubRec and continuing to the end of
39597**     the journal file.
39598**
39599** Throughout the rollback process, each time a page is rolled back, the
39600** corresponding bit is set in a bitvec structure (variable pDone in the
39601** implementation below). This is used to ensure that a page is only
39602** rolled back the first time it is encountered in either journal.
39603**
39604** If pSavepoint is NULL, then pages are only played back from the main
39605** journal file. There is no need for a bitvec in this case.
39606**
39607** In either case, before playback commences the Pager.dbSize variable
39608** is reset to the value that it held at the start of the savepoint
39609** (or transaction). No page with a page-number greater than this value
39610** is played back. If one is encountered it is simply skipped.
39611*/
39612static int pagerPlaybackSavepoint(Pager *pPager, PagerSavepoint *pSavepoint){
39613  i64 szJ;                 /* Effective size of the main journal */
39614  i64 iHdrOff;             /* End of first segment of main-journal records */
39615  int rc = SQLITE_OK;      /* Return code */
39616  Bitvec *pDone = 0;       /* Bitvec to ensure pages played back only once */
39617
39618  assert( pPager->eState!=PAGER_ERROR );
39619  assert( pPager->eState>=PAGER_WRITER_LOCKED );
39620
39621  /* Allocate a bitvec to use to store the set of pages rolled back */
39622  if( pSavepoint ){
39623    pDone = sqlite3BitvecCreate(pSavepoint->nOrig);
39624    if( !pDone ){
39625      return SQLITE_NOMEM;
39626    }
39627  }
39628
39629  /* Set the database size back to the value it was before the savepoint
39630  ** being reverted was opened.
39631  */
39632  pPager->dbSize = pSavepoint ? pSavepoint->nOrig : pPager->dbOrigSize;
39633  pPager->changeCountDone = pPager->tempFile;
39634
39635  if( !pSavepoint && pagerUseWal(pPager) ){
39636    return pagerRollbackWal(pPager);
39637  }
39638
39639  /* Use pPager->journalOff as the effective size of the main rollback
39640  ** journal.  The actual file might be larger than this in
39641  ** PAGER_JOURNALMODE_TRUNCATE or PAGER_JOURNALMODE_PERSIST.  But anything
39642  ** past pPager->journalOff is off-limits to us.
39643  */
39644  szJ = pPager->journalOff;
39645  assert( pagerUseWal(pPager)==0 || szJ==0 );
39646
39647  /* Begin by rolling back records from the main journal starting at
39648  ** PagerSavepoint.iOffset and continuing to the next journal header.
39649  ** There might be records in the main journal that have a page number
39650  ** greater than the current database size (pPager->dbSize) but those
39651  ** will be skipped automatically.  Pages are added to pDone as they
39652  ** are played back.
39653  */
39654  if( pSavepoint && !pagerUseWal(pPager) ){
39655    iHdrOff = pSavepoint->iHdrOffset ? pSavepoint->iHdrOffset : szJ;
39656    pPager->journalOff = pSavepoint->iOffset;
39657    while( rc==SQLITE_OK && pPager->journalOff<iHdrOff ){
39658      rc = pager_playback_one_page(pPager, &pPager->journalOff, pDone, 1, 1);
39659    }
39660    assert( rc!=SQLITE_DONE );
39661  }else{
39662    pPager->journalOff = 0;
39663  }
39664
39665  /* Continue rolling back records out of the main journal starting at
39666  ** the first journal header seen and continuing until the effective end
39667  ** of the main journal file.  Continue to skip out-of-range pages and
39668  ** continue adding pages rolled back to pDone.
39669  */
39670  while( rc==SQLITE_OK && pPager->journalOff<szJ ){
39671    u32 ii;            /* Loop counter */
39672    u32 nJRec = 0;     /* Number of Journal Records */
39673    u32 dummy;
39674    rc = readJournalHdr(pPager, 0, szJ, &nJRec, &dummy);
39675    assert( rc!=SQLITE_DONE );
39676
39677    /*
39678    ** The "pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff"
39679    ** test is related to ticket #2565.  See the discussion in the
39680    ** pager_playback() function for additional information.
39681    */
39682    if( nJRec==0
39683     && pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff
39684    ){
39685      nJRec = (u32)((szJ - pPager->journalOff)/JOURNAL_PG_SZ(pPager));
39686    }
39687    for(ii=0; rc==SQLITE_OK && ii<nJRec && pPager->journalOff<szJ; ii++){
39688      rc = pager_playback_one_page(pPager, &pPager->journalOff, pDone, 1, 1);
39689    }
39690    assert( rc!=SQLITE_DONE );
39691  }
39692  assert( rc!=SQLITE_OK || pPager->journalOff>=szJ );
39693
39694  /* Finally,  rollback pages from the sub-journal.  Page that were
39695  ** previously rolled back out of the main journal (and are hence in pDone)
39696  ** will be skipped.  Out-of-range pages are also skipped.
39697  */
39698  if( pSavepoint ){
39699    u32 ii;            /* Loop counter */
39700    i64 offset = pSavepoint->iSubRec*(4+pPager->pageSize);
39701
39702    if( pagerUseWal(pPager) ){
39703      rc = sqlite3WalSavepointUndo(pPager->pWal, pSavepoint->aWalData);
39704    }
39705    for(ii=pSavepoint->iSubRec; rc==SQLITE_OK && ii<pPager->nSubRec; ii++){
39706      assert( offset==ii*(4+pPager->pageSize) );
39707      rc = pager_playback_one_page(pPager, &offset, pDone, 0, 1);
39708    }
39709    assert( rc!=SQLITE_DONE );
39710  }
39711
39712  sqlite3BitvecDestroy(pDone);
39713  if( rc==SQLITE_OK ){
39714    pPager->journalOff = szJ;
39715  }
39716
39717  return rc;
39718}
39719
39720/*
39721** Change the maximum number of in-memory pages that are allowed.
39722*/
39723SQLITE_PRIVATE void sqlite3PagerSetCachesize(Pager *pPager, int mxPage){
39724  sqlite3PcacheSetCachesize(pPager->pPCache, mxPage);
39725}
39726
39727/*
39728** Adjust the robustness of the database to damage due to OS crashes
39729** or power failures by changing the number of syncs()s when writing
39730** the rollback journal.  There are three levels:
39731**
39732**    OFF       sqlite3OsSync() is never called.  This is the default
39733**              for temporary and transient files.
39734**
39735**    NORMAL    The journal is synced once before writes begin on the
39736**              database.  This is normally adequate protection, but
39737**              it is theoretically possible, though very unlikely,
39738**              that an inopertune power failure could leave the journal
39739**              in a state which would cause damage to the database
39740**              when it is rolled back.
39741**
39742**    FULL      The journal is synced twice before writes begin on the
39743**              database (with some additional information - the nRec field
39744**              of the journal header - being written in between the two
39745**              syncs).  If we assume that writing a
39746**              single disk sector is atomic, then this mode provides
39747**              assurance that the journal will not be corrupted to the
39748**              point of causing damage to the database during rollback.
39749**
39750** The above is for a rollback-journal mode.  For WAL mode, OFF continues
39751** to mean that no syncs ever occur.  NORMAL means that the WAL is synced
39752** prior to the start of checkpoint and that the database file is synced
39753** at the conclusion of the checkpoint if the entire content of the WAL
39754** was written back into the database.  But no sync operations occur for
39755** an ordinary commit in NORMAL mode with WAL.  FULL means that the WAL
39756** file is synced following each commit operation, in addition to the
39757** syncs associated with NORMAL.
39758**
39759** Do not confuse synchronous=FULL with SQLITE_SYNC_FULL.  The
39760** SQLITE_SYNC_FULL macro means to use the MacOSX-style full-fsync
39761** using fcntl(F_FULLFSYNC).  SQLITE_SYNC_NORMAL means to do an
39762** ordinary fsync() call.  There is no difference between SQLITE_SYNC_FULL
39763** and SQLITE_SYNC_NORMAL on platforms other than MacOSX.  But the
39764** synchronous=FULL versus synchronous=NORMAL setting determines when
39765** the xSync primitive is called and is relevant to all platforms.
39766**
39767** Numeric values associated with these states are OFF==1, NORMAL=2,
39768** and FULL=3.
39769*/
39770#ifndef SQLITE_OMIT_PAGER_PRAGMAS
39771SQLITE_PRIVATE void sqlite3PagerSetSafetyLevel(
39772  Pager *pPager,        /* The pager to set safety level for */
39773  int level,            /* PRAGMA synchronous.  1=OFF, 2=NORMAL, 3=FULL */
39774  int bFullFsync,       /* PRAGMA fullfsync */
39775  int bCkptFullFsync    /* PRAGMA checkpoint_fullfsync */
39776){
39777  assert( level>=1 && level<=3 );
39778  pPager->noSync =  (level==1 || pPager->tempFile) ?1:0;
39779  pPager->fullSync = (level==3 && !pPager->tempFile) ?1:0;
39780  if( pPager->noSync ){
39781    pPager->syncFlags = 0;
39782    pPager->ckptSyncFlags = 0;
39783  }else if( bFullFsync ){
39784    pPager->syncFlags = SQLITE_SYNC_FULL;
39785    pPager->ckptSyncFlags = SQLITE_SYNC_FULL;
39786  }else if( bCkptFullFsync ){
39787    pPager->syncFlags = SQLITE_SYNC_NORMAL;
39788    pPager->ckptSyncFlags = SQLITE_SYNC_FULL;
39789  }else{
39790    pPager->syncFlags = SQLITE_SYNC_NORMAL;
39791    pPager->ckptSyncFlags = SQLITE_SYNC_NORMAL;
39792  }
39793}
39794#endif
39795
39796/*
39797** The following global variable is incremented whenever the library
39798** attempts to open a temporary file.  This information is used for
39799** testing and analysis only.
39800*/
39801#ifdef SQLITE_TEST
39802SQLITE_API int sqlite3_opentemp_count = 0;
39803#endif
39804
39805/*
39806** Open a temporary file.
39807**
39808** Write the file descriptor into *pFile. Return SQLITE_OK on success
39809** or some other error code if we fail. The OS will automatically
39810** delete the temporary file when it is closed.
39811**
39812** The flags passed to the VFS layer xOpen() call are those specified
39813** by parameter vfsFlags ORed with the following:
39814**
39815**     SQLITE_OPEN_READWRITE
39816**     SQLITE_OPEN_CREATE
39817**     SQLITE_OPEN_EXCLUSIVE
39818**     SQLITE_OPEN_DELETEONCLOSE
39819*/
39820static int pagerOpentemp(
39821  Pager *pPager,        /* The pager object */
39822  sqlite3_file *pFile,  /* Write the file descriptor here */
39823  int vfsFlags          /* Flags passed through to the VFS */
39824){
39825  int rc;               /* Return code */
39826
39827#ifdef SQLITE_TEST
39828  sqlite3_opentemp_count++;  /* Used for testing and analysis only */
39829#endif
39830
39831  vfsFlags |=  SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE |
39832            SQLITE_OPEN_EXCLUSIVE | SQLITE_OPEN_DELETEONCLOSE;
39833  rc = sqlite3OsOpen(pPager->pVfs, 0, pFile, vfsFlags, 0);
39834  assert( rc!=SQLITE_OK || isOpen(pFile) );
39835  return rc;
39836}
39837
39838/*
39839** Set the busy handler function.
39840**
39841** The pager invokes the busy-handler if sqlite3OsLock() returns
39842** SQLITE_BUSY when trying to upgrade from no-lock to a SHARED lock,
39843** or when trying to upgrade from a RESERVED lock to an EXCLUSIVE
39844** lock. It does *not* invoke the busy handler when upgrading from
39845** SHARED to RESERVED, or when upgrading from SHARED to EXCLUSIVE
39846** (which occurs during hot-journal rollback). Summary:
39847**
39848**   Transition                        | Invokes xBusyHandler
39849**   --------------------------------------------------------
39850**   NO_LOCK       -> SHARED_LOCK      | Yes
39851**   SHARED_LOCK   -> RESERVED_LOCK    | No
39852**   SHARED_LOCK   -> EXCLUSIVE_LOCK   | No
39853**   RESERVED_LOCK -> EXCLUSIVE_LOCK   | Yes
39854**
39855** If the busy-handler callback returns non-zero, the lock is
39856** retried. If it returns zero, then the SQLITE_BUSY error is
39857** returned to the caller of the pager API function.
39858*/
39859SQLITE_PRIVATE void sqlite3PagerSetBusyhandler(
39860  Pager *pPager,                       /* Pager object */
39861  int (*xBusyHandler)(void *),         /* Pointer to busy-handler function */
39862  void *pBusyHandlerArg                /* Argument to pass to xBusyHandler */
39863){
39864  pPager->xBusyHandler = xBusyHandler;
39865  pPager->pBusyHandlerArg = pBusyHandlerArg;
39866}
39867
39868/*
39869** Change the page size used by the Pager object. The new page size
39870** is passed in *pPageSize.
39871**
39872** If the pager is in the error state when this function is called, it
39873** is a no-op. The value returned is the error state error code (i.e.
39874** one of SQLITE_IOERR, an SQLITE_IOERR_xxx sub-code or SQLITE_FULL).
39875**
39876** Otherwise, if all of the following are true:
39877**
39878**   * the new page size (value of *pPageSize) is valid (a power
39879**     of two between 512 and SQLITE_MAX_PAGE_SIZE, inclusive), and
39880**
39881**   * there are no outstanding page references, and
39882**
39883**   * the database is either not an in-memory database or it is
39884**     an in-memory database that currently consists of zero pages.
39885**
39886** then the pager object page size is set to *pPageSize.
39887**
39888** If the page size is changed, then this function uses sqlite3PagerMalloc()
39889** to obtain a new Pager.pTmpSpace buffer. If this allocation attempt
39890** fails, SQLITE_NOMEM is returned and the page size remains unchanged.
39891** In all other cases, SQLITE_OK is returned.
39892**
39893** If the page size is not changed, either because one of the enumerated
39894** conditions above is not true, the pager was in error state when this
39895** function was called, or because the memory allocation attempt failed,
39896** then *pPageSize is set to the old, retained page size before returning.
39897*/
39898SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager *pPager, u32 *pPageSize, int nReserve){
39899  int rc = SQLITE_OK;
39900
39901  /* It is not possible to do a full assert_pager_state() here, as this
39902  ** function may be called from within PagerOpen(), before the state
39903  ** of the Pager object is internally consistent.
39904  **
39905  ** At one point this function returned an error if the pager was in
39906  ** PAGER_ERROR state. But since PAGER_ERROR state guarantees that
39907  ** there is at least one outstanding page reference, this function
39908  ** is a no-op for that case anyhow.
39909  */
39910
39911  u32 pageSize = *pPageSize;
39912  assert( pageSize==0 || (pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE) );
39913  if( (pPager->memDb==0 || pPager->dbSize==0)
39914   && sqlite3PcacheRefCount(pPager->pPCache)==0
39915   && pageSize && pageSize!=(u32)pPager->pageSize
39916  ){
39917    char *pNew = NULL;             /* New temp space */
39918    i64 nByte = 0;
39919
39920    if( pPager->eState>PAGER_OPEN && isOpen(pPager->fd) ){
39921      rc = sqlite3OsFileSize(pPager->fd, &nByte);
39922    }
39923    if( rc==SQLITE_OK ){
39924      pNew = (char *)sqlite3PageMalloc(pageSize);
39925      if( !pNew ) rc = SQLITE_NOMEM;
39926    }
39927
39928    if( rc==SQLITE_OK ){
39929      pager_reset(pPager);
39930      pPager->dbSize = (Pgno)(nByte/pageSize);
39931      pPager->pageSize = pageSize;
39932      sqlite3PageFree(pPager->pTmpSpace);
39933      pPager->pTmpSpace = pNew;
39934      sqlite3PcacheSetPageSize(pPager->pPCache, pageSize);
39935    }
39936  }
39937
39938  *pPageSize = pPager->pageSize;
39939  if( rc==SQLITE_OK ){
39940    if( nReserve<0 ) nReserve = pPager->nReserve;
39941    assert( nReserve>=0 && nReserve<1000 );
39942    pPager->nReserve = (i16)nReserve;
39943    pagerReportSize(pPager);
39944  }
39945  return rc;
39946}
39947
39948/*
39949** Return a pointer to the "temporary page" buffer held internally
39950** by the pager.  This is a buffer that is big enough to hold the
39951** entire content of a database page.  This buffer is used internally
39952** during rollback and will be overwritten whenever a rollback
39953** occurs.  But other modules are free to use it too, as long as
39954** no rollbacks are happening.
39955*/
39956SQLITE_PRIVATE void *sqlite3PagerTempSpace(Pager *pPager){
39957  return pPager->pTmpSpace;
39958}
39959
39960/*
39961** Attempt to set the maximum database page count if mxPage is positive.
39962** Make no changes if mxPage is zero or negative.  And never reduce the
39963** maximum page count below the current size of the database.
39964**
39965** Regardless of mxPage, return the current maximum page count.
39966*/
39967SQLITE_PRIVATE int sqlite3PagerMaxPageCount(Pager *pPager, int mxPage){
39968  if( mxPage>0 ){
39969    pPager->mxPgno = mxPage;
39970  }
39971  assert( pPager->eState!=PAGER_OPEN );      /* Called only by OP_MaxPgcnt */
39972  assert( pPager->mxPgno>=pPager->dbSize );  /* OP_MaxPgcnt enforces this */
39973  return pPager->mxPgno;
39974}
39975
39976/*
39977** The following set of routines are used to disable the simulated
39978** I/O error mechanism.  These routines are used to avoid simulated
39979** errors in places where we do not care about errors.
39980**
39981** Unless -DSQLITE_TEST=1 is used, these routines are all no-ops
39982** and generate no code.
39983*/
39984#ifdef SQLITE_TEST
39985SQLITE_API extern int sqlite3_io_error_pending;
39986SQLITE_API extern int sqlite3_io_error_hit;
39987static int saved_cnt;
39988void disable_simulated_io_errors(void){
39989  saved_cnt = sqlite3_io_error_pending;
39990  sqlite3_io_error_pending = -1;
39991}
39992void enable_simulated_io_errors(void){
39993  sqlite3_io_error_pending = saved_cnt;
39994}
39995#else
39996# define disable_simulated_io_errors()
39997# define enable_simulated_io_errors()
39998#endif
39999
40000/*
40001** Read the first N bytes from the beginning of the file into memory
40002** that pDest points to.
40003**
40004** If the pager was opened on a transient file (zFilename==""), or
40005** opened on a file less than N bytes in size, the output buffer is
40006** zeroed and SQLITE_OK returned. The rationale for this is that this
40007** function is used to read database headers, and a new transient or
40008** zero sized database has a header than consists entirely of zeroes.
40009**
40010** If any IO error apart from SQLITE_IOERR_SHORT_READ is encountered,
40011** the error code is returned to the caller and the contents of the
40012** output buffer undefined.
40013*/
40014SQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager *pPager, int N, unsigned char *pDest){
40015  int rc = SQLITE_OK;
40016  memset(pDest, 0, N);
40017  assert( isOpen(pPager->fd) || pPager->tempFile );
40018
40019  /* This routine is only called by btree immediately after creating
40020  ** the Pager object.  There has not been an opportunity to transition
40021  ** to WAL mode yet.
40022  */
40023  assert( !pagerUseWal(pPager) );
40024
40025  if( isOpen(pPager->fd) ){
40026    IOTRACE(("DBHDR %p 0 %d\n", pPager, N))
40027    rc = sqlite3OsRead(pPager->fd, pDest, N, 0);
40028    if( rc==SQLITE_IOERR_SHORT_READ ){
40029      rc = SQLITE_OK;
40030    }
40031  }
40032  return rc;
40033}
40034
40035/*
40036** This function may only be called when a read-transaction is open on
40037** the pager. It returns the total number of pages in the database.
40038**
40039** However, if the file is between 1 and <page-size> bytes in size, then
40040** this is considered a 1 page file.
40041*/
40042SQLITE_PRIVATE void sqlite3PagerPagecount(Pager *pPager, int *pnPage){
40043  assert( pPager->eState>=PAGER_READER );
40044  assert( pPager->eState!=PAGER_WRITER_FINISHED );
40045  *pnPage = (int)pPager->dbSize;
40046}
40047
40048
40049/*
40050** Try to obtain a lock of type locktype on the database file. If
40051** a similar or greater lock is already held, this function is a no-op
40052** (returning SQLITE_OK immediately).
40053**
40054** Otherwise, attempt to obtain the lock using sqlite3OsLock(). Invoke
40055** the busy callback if the lock is currently not available. Repeat
40056** until the busy callback returns false or until the attempt to
40057** obtain the lock succeeds.
40058**
40059** Return SQLITE_OK on success and an error code if we cannot obtain
40060** the lock. If the lock is obtained successfully, set the Pager.state
40061** variable to locktype before returning.
40062*/
40063static int pager_wait_on_lock(Pager *pPager, int locktype){
40064  int rc;                              /* Return code */
40065
40066  /* Check that this is either a no-op (because the requested lock is
40067  ** already held, or one of the transistions that the busy-handler
40068  ** may be invoked during, according to the comment above
40069  ** sqlite3PagerSetBusyhandler().
40070  */
40071  assert( (pPager->eLock>=locktype)
40072       || (pPager->eLock==NO_LOCK && locktype==SHARED_LOCK)
40073       || (pPager->eLock==RESERVED_LOCK && locktype==EXCLUSIVE_LOCK)
40074  );
40075
40076  do {
40077    rc = pagerLockDb(pPager, locktype);
40078  }while( rc==SQLITE_BUSY && pPager->xBusyHandler(pPager->pBusyHandlerArg) );
40079  return rc;
40080}
40081
40082/*
40083** Function assertTruncateConstraint(pPager) checks that one of the
40084** following is true for all dirty pages currently in the page-cache:
40085**
40086**   a) The page number is less than or equal to the size of the
40087**      current database image, in pages, OR
40088**
40089**   b) if the page content were written at this time, it would not
40090**      be necessary to write the current content out to the sub-journal
40091**      (as determined by function subjRequiresPage()).
40092**
40093** If the condition asserted by this function were not true, and the
40094** dirty page were to be discarded from the cache via the pagerStress()
40095** routine, pagerStress() would not write the current page content to
40096** the database file. If a savepoint transaction were rolled back after
40097** this happened, the correct behaviour would be to restore the current
40098** content of the page. However, since this content is not present in either
40099** the database file or the portion of the rollback journal and
40100** sub-journal rolled back the content could not be restored and the
40101** database image would become corrupt. It is therefore fortunate that
40102** this circumstance cannot arise.
40103*/
40104#if defined(SQLITE_DEBUG)
40105static void assertTruncateConstraintCb(PgHdr *pPg){
40106  assert( pPg->flags&PGHDR_DIRTY );
40107  assert( !subjRequiresPage(pPg) || pPg->pgno<=pPg->pPager->dbSize );
40108}
40109static void assertTruncateConstraint(Pager *pPager){
40110  sqlite3PcacheIterateDirty(pPager->pPCache, assertTruncateConstraintCb);
40111}
40112#else
40113# define assertTruncateConstraint(pPager)
40114#endif
40115
40116/*
40117** Truncate the in-memory database file image to nPage pages. This
40118** function does not actually modify the database file on disk. It
40119** just sets the internal state of the pager object so that the
40120** truncation will be done when the current transaction is committed.
40121*/
40122SQLITE_PRIVATE void sqlite3PagerTruncateImage(Pager *pPager, Pgno nPage){
40123  assert( pPager->dbSize>=nPage );
40124  assert( pPager->eState>=PAGER_WRITER_CACHEMOD );
40125  pPager->dbSize = nPage;
40126  assertTruncateConstraint(pPager);
40127}
40128
40129
40130/*
40131** This function is called before attempting a hot-journal rollback. It
40132** syncs the journal file to disk, then sets pPager->journalHdr to the
40133** size of the journal file so that the pager_playback() routine knows
40134** that the entire journal file has been synced.
40135**
40136** Syncing a hot-journal to disk before attempting to roll it back ensures
40137** that if a power-failure occurs during the rollback, the process that
40138** attempts rollback following system recovery sees the same journal
40139** content as this process.
40140**
40141** If everything goes as planned, SQLITE_OK is returned. Otherwise,
40142** an SQLite error code.
40143*/
40144static int pagerSyncHotJournal(Pager *pPager){
40145  int rc = SQLITE_OK;
40146  if( !pPager->noSync ){
40147    rc = sqlite3OsSync(pPager->jfd, SQLITE_SYNC_NORMAL);
40148  }
40149  if( rc==SQLITE_OK ){
40150    rc = sqlite3OsFileSize(pPager->jfd, &pPager->journalHdr);
40151  }
40152  return rc;
40153}
40154
40155/*
40156** Shutdown the page cache.  Free all memory and close all files.
40157**
40158** If a transaction was in progress when this routine is called, that
40159** transaction is rolled back.  All outstanding pages are invalidated
40160** and their memory is freed.  Any attempt to use a page associated
40161** with this page cache after this function returns will likely
40162** result in a coredump.
40163**
40164** This function always succeeds. If a transaction is active an attempt
40165** is made to roll it back. If an error occurs during the rollback
40166** a hot journal may be left in the filesystem but no error is returned
40167** to the caller.
40168*/
40169SQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager){
40170  u8 *pTmp = (u8 *)pPager->pTmpSpace;
40171
40172  disable_simulated_io_errors();
40173  sqlite3BeginBenignMalloc();
40174  /* pPager->errCode = 0; */
40175  pPager->exclusiveMode = 0;
40176#ifndef SQLITE_OMIT_WAL
40177  sqlite3WalClose(pPager->pWal, pPager->ckptSyncFlags, pPager->pageSize, pTmp);
40178  pPager->pWal = 0;
40179#endif
40180  pager_reset(pPager);
40181  if( MEMDB ){
40182    pager_unlock(pPager);
40183  }else{
40184    /* If it is open, sync the journal file before calling UnlockAndRollback.
40185    ** If this is not done, then an unsynced portion of the open journal
40186    ** file may be played back into the database. If a power failure occurs
40187    ** while this is happening, the database could become corrupt.
40188    **
40189    ** If an error occurs while trying to sync the journal, shift the pager
40190    ** into the ERROR state. This causes UnlockAndRollback to unlock the
40191    ** database and close the journal file without attempting to roll it
40192    ** back or finalize it. The next database user will have to do hot-journal
40193    ** rollback before accessing the database file.
40194    */
40195    if( isOpen(pPager->jfd) ){
40196      pager_error(pPager, pagerSyncHotJournal(pPager));
40197    }
40198    pagerUnlockAndRollback(pPager);
40199  }
40200  sqlite3EndBenignMalloc();
40201  enable_simulated_io_errors();
40202  PAGERTRACE(("CLOSE %d\n", PAGERID(pPager)));
40203  IOTRACE(("CLOSE %p\n", pPager))
40204  sqlite3OsClose(pPager->jfd);
40205  sqlite3OsClose(pPager->fd);
40206  sqlite3PageFree(pTmp);
40207  sqlite3PcacheClose(pPager->pPCache);
40208
40209#ifdef SQLITE_HAS_CODEC
40210  if( pPager->xCodecFree ) pPager->xCodecFree(pPager->pCodec);
40211#endif
40212
40213  assert( !pPager->aSavepoint && !pPager->pInJournal );
40214  assert( !isOpen(pPager->jfd) && !isOpen(pPager->sjfd) );
40215
40216  sqlite3_free(pPager);
40217  return SQLITE_OK;
40218}
40219
40220#if !defined(NDEBUG) || defined(SQLITE_TEST)
40221/*
40222** Return the page number for page pPg.
40223*/
40224SQLITE_PRIVATE Pgno sqlite3PagerPagenumber(DbPage *pPg){
40225  return pPg->pgno;
40226}
40227#endif
40228
40229/*
40230** Increment the reference count for page pPg.
40231*/
40232SQLITE_PRIVATE void sqlite3PagerRef(DbPage *pPg){
40233  sqlite3PcacheRef(pPg);
40234}
40235
40236/*
40237** Sync the journal. In other words, make sure all the pages that have
40238** been written to the journal have actually reached the surface of the
40239** disk and can be restored in the event of a hot-journal rollback.
40240**
40241** If the Pager.noSync flag is set, then this function is a no-op.
40242** Otherwise, the actions required depend on the journal-mode and the
40243** device characteristics of the the file-system, as follows:
40244**
40245**   * If the journal file is an in-memory journal file, no action need
40246**     be taken.
40247**
40248**   * Otherwise, if the device does not support the SAFE_APPEND property,
40249**     then the nRec field of the most recently written journal header
40250**     is updated to contain the number of journal records that have
40251**     been written following it. If the pager is operating in full-sync
40252**     mode, then the journal file is synced before this field is updated.
40253**
40254**   * If the device does not support the SEQUENTIAL property, then
40255**     journal file is synced.
40256**
40257** Or, in pseudo-code:
40258**
40259**   if( NOT <in-memory journal> ){
40260**     if( NOT SAFE_APPEND ){
40261**       if( <full-sync mode> ) xSync(<journal file>);
40262**       <update nRec field>
40263**     }
40264**     if( NOT SEQUENTIAL ) xSync(<journal file>);
40265**   }
40266**
40267** If successful, this routine clears the PGHDR_NEED_SYNC flag of every
40268** page currently held in memory before returning SQLITE_OK. If an IO
40269** error is encountered, then the IO error code is returned to the caller.
40270*/
40271static int syncJournal(Pager *pPager, int newHdr){
40272  int rc;                         /* Return code */
40273
40274  assert( pPager->eState==PAGER_WRITER_CACHEMOD
40275       || pPager->eState==PAGER_WRITER_DBMOD
40276  );
40277  assert( assert_pager_state(pPager) );
40278  assert( !pagerUseWal(pPager) );
40279
40280  rc = sqlite3PagerExclusiveLock(pPager);
40281  if( rc!=SQLITE_OK ) return rc;
40282
40283  if( !pPager->noSync ){
40284    assert( !pPager->tempFile );
40285    if( isOpen(pPager->jfd) && pPager->journalMode!=PAGER_JOURNALMODE_MEMORY ){
40286      const int iDc = sqlite3OsDeviceCharacteristics(pPager->fd);
40287      assert( isOpen(pPager->jfd) );
40288
40289      if( 0==(iDc&SQLITE_IOCAP_SAFE_APPEND) ){
40290        /* This block deals with an obscure problem. If the last connection
40291        ** that wrote to this database was operating in persistent-journal
40292        ** mode, then the journal file may at this point actually be larger
40293        ** than Pager.journalOff bytes. If the next thing in the journal
40294        ** file happens to be a journal-header (written as part of the
40295        ** previous connection's transaction), and a crash or power-failure
40296        ** occurs after nRec is updated but before this connection writes
40297        ** anything else to the journal file (or commits/rolls back its
40298        ** transaction), then SQLite may become confused when doing the
40299        ** hot-journal rollback following recovery. It may roll back all
40300        ** of this connections data, then proceed to rolling back the old,
40301        ** out-of-date data that follows it. Database corruption.
40302        **
40303        ** To work around this, if the journal file does appear to contain
40304        ** a valid header following Pager.journalOff, then write a 0x00
40305        ** byte to the start of it to prevent it from being recognized.
40306        **
40307        ** Variable iNextHdrOffset is set to the offset at which this
40308        ** problematic header will occur, if it exists. aMagic is used
40309        ** as a temporary buffer to inspect the first couple of bytes of
40310        ** the potential journal header.
40311        */
40312        i64 iNextHdrOffset;
40313        u8 aMagic[8];
40314        u8 zHeader[sizeof(aJournalMagic)+4];
40315
40316        memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic));
40317        put32bits(&zHeader[sizeof(aJournalMagic)], pPager->nRec);
40318
40319        iNextHdrOffset = journalHdrOffset(pPager);
40320        rc = sqlite3OsRead(pPager->jfd, aMagic, 8, iNextHdrOffset);
40321        if( rc==SQLITE_OK && 0==memcmp(aMagic, aJournalMagic, 8) ){
40322          static const u8 zerobyte = 0;
40323          rc = sqlite3OsWrite(pPager->jfd, &zerobyte, 1, iNextHdrOffset);
40324        }
40325        if( rc!=SQLITE_OK && rc!=SQLITE_IOERR_SHORT_READ ){
40326          return rc;
40327        }
40328
40329        /* Write the nRec value into the journal file header. If in
40330        ** full-synchronous mode, sync the journal first. This ensures that
40331        ** all data has really hit the disk before nRec is updated to mark
40332        ** it as a candidate for rollback.
40333        **
40334        ** This is not required if the persistent media supports the
40335        ** SAFE_APPEND property. Because in this case it is not possible
40336        ** for garbage data to be appended to the file, the nRec field
40337        ** is populated with 0xFFFFFFFF when the journal header is written
40338        ** and never needs to be updated.
40339        */
40340        if( pPager->fullSync && 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){
40341          PAGERTRACE(("SYNC journal of %d\n", PAGERID(pPager)));
40342          IOTRACE(("JSYNC %p\n", pPager))
40343          rc = sqlite3OsSync(pPager->jfd, pPager->syncFlags);
40344          if( rc!=SQLITE_OK ) return rc;
40345        }
40346        IOTRACE(("JHDR %p %lld\n", pPager, pPager->journalHdr));
40347        rc = sqlite3OsWrite(
40348            pPager->jfd, zHeader, sizeof(zHeader), pPager->journalHdr
40349        );
40350        if( rc!=SQLITE_OK ) return rc;
40351      }
40352      if( 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){
40353        PAGERTRACE(("SYNC journal of %d\n", PAGERID(pPager)));
40354        IOTRACE(("JSYNC %p\n", pPager))
40355        rc = sqlite3OsSync(pPager->jfd, pPager->syncFlags|
40356          (pPager->syncFlags==SQLITE_SYNC_FULL?SQLITE_SYNC_DATAONLY:0)
40357        );
40358        if( rc!=SQLITE_OK ) return rc;
40359      }
40360
40361      pPager->journalHdr = pPager->journalOff;
40362      if( newHdr && 0==(iDc&SQLITE_IOCAP_SAFE_APPEND) ){
40363        pPager->nRec = 0;
40364        rc = writeJournalHdr(pPager);
40365        if( rc!=SQLITE_OK ) return rc;
40366      }
40367    }else{
40368      pPager->journalHdr = pPager->journalOff;
40369    }
40370  }
40371
40372  /* Unless the pager is in noSync mode, the journal file was just
40373  ** successfully synced. Either way, clear the PGHDR_NEED_SYNC flag on
40374  ** all pages.
40375  */
40376  sqlite3PcacheClearSyncFlags(pPager->pPCache);
40377  pPager->eState = PAGER_WRITER_DBMOD;
40378  assert( assert_pager_state(pPager) );
40379  return SQLITE_OK;
40380}
40381
40382/*
40383** The argument is the first in a linked list of dirty pages connected
40384** by the PgHdr.pDirty pointer. This function writes each one of the
40385** in-memory pages in the list to the database file. The argument may
40386** be NULL, representing an empty list. In this case this function is
40387** a no-op.
40388**
40389** The pager must hold at least a RESERVED lock when this function
40390** is called. Before writing anything to the database file, this lock
40391** is upgraded to an EXCLUSIVE lock. If the lock cannot be obtained,
40392** SQLITE_BUSY is returned and no data is written to the database file.
40393**
40394** If the pager is a temp-file pager and the actual file-system file
40395** is not yet open, it is created and opened before any data is
40396** written out.
40397**
40398** Once the lock has been upgraded and, if necessary, the file opened,
40399** the pages are written out to the database file in list order. Writing
40400** a page is skipped if it meets either of the following criteria:
40401**
40402**   * The page number is greater than Pager.dbSize, or
40403**   * The PGHDR_DONT_WRITE flag is set on the page.
40404**
40405** If writing out a page causes the database file to grow, Pager.dbFileSize
40406** is updated accordingly. If page 1 is written out, then the value cached
40407** in Pager.dbFileVers[] is updated to match the new value stored in
40408** the database file.
40409**
40410** If everything is successful, SQLITE_OK is returned. If an IO error
40411** occurs, an IO error code is returned. Or, if the EXCLUSIVE lock cannot
40412** be obtained, SQLITE_BUSY is returned.
40413*/
40414static int pager_write_pagelist(Pager *pPager, PgHdr *pList){
40415  int rc = SQLITE_OK;                  /* Return code */
40416
40417  /* This function is only called for rollback pagers in WRITER_DBMOD state. */
40418  assert( !pagerUseWal(pPager) );
40419  assert( pPager->eState==PAGER_WRITER_DBMOD );
40420  assert( pPager->eLock==EXCLUSIVE_LOCK );
40421
40422  /* If the file is a temp-file has not yet been opened, open it now. It
40423  ** is not possible for rc to be other than SQLITE_OK if this branch
40424  ** is taken, as pager_wait_on_lock() is a no-op for temp-files.
40425  */
40426  if( !isOpen(pPager->fd) ){
40427    assert( pPager->tempFile && rc==SQLITE_OK );
40428    rc = pagerOpentemp(pPager, pPager->fd, pPager->vfsFlags);
40429  }
40430
40431  /* Before the first write, give the VFS a hint of what the final
40432  ** file size will be.
40433  */
40434  assert( rc!=SQLITE_OK || isOpen(pPager->fd) );
40435  if( rc==SQLITE_OK && pPager->dbSize>pPager->dbHintSize ){
40436    sqlite3_int64 szFile = pPager->pageSize * (sqlite3_int64)pPager->dbSize;
40437    sqlite3OsFileControl(pPager->fd, SQLITE_FCNTL_SIZE_HINT, &szFile);
40438    pPager->dbHintSize = pPager->dbSize;
40439  }
40440
40441  while( rc==SQLITE_OK && pList ){
40442    Pgno pgno = pList->pgno;
40443
40444    /* If there are dirty pages in the page cache with page numbers greater
40445    ** than Pager.dbSize, this means sqlite3PagerTruncateImage() was called to
40446    ** make the file smaller (presumably by auto-vacuum code). Do not write
40447    ** any such pages to the file.
40448    **
40449    ** Also, do not write out any page that has the PGHDR_DONT_WRITE flag
40450    ** set (set by sqlite3PagerDontWrite()).
40451    */
40452    if( pgno<=pPager->dbSize && 0==(pList->flags&PGHDR_DONT_WRITE) ){
40453      i64 offset = (pgno-1)*(i64)pPager->pageSize;   /* Offset to write */
40454      char *pData;                                   /* Data to write */
40455
40456      assert( (pList->flags&PGHDR_NEED_SYNC)==0 );
40457      if( pList->pgno==1 ) pager_write_changecounter(pList);
40458
40459      /* Encode the database */
40460      CODEC2(pPager, pList->pData, pgno, 6, return SQLITE_NOMEM, pData);
40461
40462      /* Write out the page data. */
40463      rc = sqlite3OsWrite(pPager->fd, pData, pPager->pageSize, offset);
40464
40465      /* If page 1 was just written, update Pager.dbFileVers to match
40466      ** the value now stored in the database file. If writing this
40467      ** page caused the database file to grow, update dbFileSize.
40468      */
40469      if( pgno==1 ){
40470        memcpy(&pPager->dbFileVers, &pData[24], sizeof(pPager->dbFileVers));
40471      }
40472      if( pgno>pPager->dbFileSize ){
40473        pPager->dbFileSize = pgno;
40474      }
40475
40476      /* Update any backup objects copying the contents of this pager. */
40477      sqlite3BackupUpdate(pPager->pBackup, pgno, (u8*)pList->pData);
40478
40479      PAGERTRACE(("STORE %d page %d hash(%08x)\n",
40480                   PAGERID(pPager), pgno, pager_pagehash(pList)));
40481      IOTRACE(("PGOUT %p %d\n", pPager, pgno));
40482      PAGER_INCR(sqlite3_pager_writedb_count);
40483      PAGER_INCR(pPager->nWrite);
40484    }else{
40485      PAGERTRACE(("NOSTORE %d page %d\n", PAGERID(pPager), pgno));
40486    }
40487    pager_set_pagehash(pList);
40488    pList = pList->pDirty;
40489  }
40490
40491  return rc;
40492}
40493
40494/*
40495** Ensure that the sub-journal file is open. If it is already open, this
40496** function is a no-op.
40497**
40498** SQLITE_OK is returned if everything goes according to plan. An
40499** SQLITE_IOERR_XXX error code is returned if a call to sqlite3OsOpen()
40500** fails.
40501*/
40502static int openSubJournal(Pager *pPager){
40503  int rc = SQLITE_OK;
40504  if( !isOpen(pPager->sjfd) ){
40505    if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY || pPager->subjInMemory ){
40506      sqlite3MemJournalOpen(pPager->sjfd);
40507    }else{
40508      rc = pagerOpentemp(pPager, pPager->sjfd, SQLITE_OPEN_SUBJOURNAL);
40509    }
40510  }
40511  return rc;
40512}
40513
40514/*
40515** Append a record of the current state of page pPg to the sub-journal.
40516** It is the callers responsibility to use subjRequiresPage() to check
40517** that it is really required before calling this function.
40518**
40519** If successful, set the bit corresponding to pPg->pgno in the bitvecs
40520** for all open savepoints before returning.
40521**
40522** This function returns SQLITE_OK if everything is successful, an IO
40523** error code if the attempt to write to the sub-journal fails, or
40524** SQLITE_NOMEM if a malloc fails while setting a bit in a savepoint
40525** bitvec.
40526*/
40527static int subjournalPage(PgHdr *pPg){
40528  int rc = SQLITE_OK;
40529  Pager *pPager = pPg->pPager;
40530  if( pPager->journalMode!=PAGER_JOURNALMODE_OFF ){
40531
40532    /* Open the sub-journal, if it has not already been opened */
40533    assert( pPager->useJournal );
40534    assert( isOpen(pPager->jfd) || pagerUseWal(pPager) );
40535    assert( isOpen(pPager->sjfd) || pPager->nSubRec==0 );
40536    assert( pagerUseWal(pPager)
40537         || pageInJournal(pPg)
40538         || pPg->pgno>pPager->dbOrigSize
40539    );
40540    rc = openSubJournal(pPager);
40541
40542    /* If the sub-journal was opened successfully (or was already open),
40543    ** write the journal record into the file.  */
40544    if( rc==SQLITE_OK ){
40545      void *pData = pPg->pData;
40546      i64 offset = pPager->nSubRec*(4+pPager->pageSize);
40547      char *pData2;
40548
40549      CODEC2(pPager, pData, pPg->pgno, 7, return SQLITE_NOMEM, pData2);
40550      PAGERTRACE(("STMT-JOURNAL %d page %d\n", PAGERID(pPager), pPg->pgno));
40551      rc = write32bits(pPager->sjfd, offset, pPg->pgno);
40552      if( rc==SQLITE_OK ){
40553        rc = sqlite3OsWrite(pPager->sjfd, pData2, pPager->pageSize, offset+4);
40554      }
40555    }
40556  }
40557  if( rc==SQLITE_OK ){
40558    pPager->nSubRec++;
40559    assert( pPager->nSavepoint>0 );
40560    rc = addToSavepointBitvecs(pPager, pPg->pgno);
40561  }
40562  return rc;
40563}
40564
40565/*
40566** This function is called by the pcache layer when it has reached some
40567** soft memory limit. The first argument is a pointer to a Pager object
40568** (cast as a void*). The pager is always 'purgeable' (not an in-memory
40569** database). The second argument is a reference to a page that is
40570** currently dirty but has no outstanding references. The page
40571** is always associated with the Pager object passed as the first
40572** argument.
40573**
40574** The job of this function is to make pPg clean by writing its contents
40575** out to the database file, if possible. This may involve syncing the
40576** journal file.
40577**
40578** If successful, sqlite3PcacheMakeClean() is called on the page and
40579** SQLITE_OK returned. If an IO error occurs while trying to make the
40580** page clean, the IO error code is returned. If the page cannot be
40581** made clean for some other reason, but no error occurs, then SQLITE_OK
40582** is returned by sqlite3PcacheMakeClean() is not called.
40583*/
40584static int pagerStress(void *p, PgHdr *pPg){
40585  Pager *pPager = (Pager *)p;
40586  int rc = SQLITE_OK;
40587
40588  assert( pPg->pPager==pPager );
40589  assert( pPg->flags&PGHDR_DIRTY );
40590
40591  /* The doNotSyncSpill flag is set during times when doing a sync of
40592  ** journal (and adding a new header) is not allowed.  This occurs
40593  ** during calls to sqlite3PagerWrite() while trying to journal multiple
40594  ** pages belonging to the same sector.
40595  **
40596  ** The doNotSpill flag inhibits all cache spilling regardless of whether
40597  ** or not a sync is required.  This is set during a rollback.
40598  **
40599  ** Spilling is also prohibited when in an error state since that could
40600  ** lead to database corruption.   In the current implementaton it
40601  ** is impossible for sqlite3PCacheFetch() to be called with createFlag==1
40602  ** while in the error state, hence it is impossible for this routine to
40603  ** be called in the error state.  Nevertheless, we include a NEVER()
40604  ** test for the error state as a safeguard against future changes.
40605  */
40606  if( NEVER(pPager->errCode) ) return SQLITE_OK;
40607  if( pPager->doNotSpill ) return SQLITE_OK;
40608  if( pPager->doNotSyncSpill && (pPg->flags & PGHDR_NEED_SYNC)!=0 ){
40609    return SQLITE_OK;
40610  }
40611
40612  pPg->pDirty = 0;
40613  if( pagerUseWal(pPager) ){
40614    /* Write a single frame for this page to the log. */
40615    if( subjRequiresPage(pPg) ){
40616      rc = subjournalPage(pPg);
40617    }
40618    if( rc==SQLITE_OK ){
40619      rc = pagerWalFrames(pPager, pPg, 0, 0, 0);
40620    }
40621  }else{
40622
40623    /* Sync the journal file if required. */
40624    if( pPg->flags&PGHDR_NEED_SYNC
40625     || pPager->eState==PAGER_WRITER_CACHEMOD
40626    ){
40627      rc = syncJournal(pPager, 1);
40628    }
40629
40630    /* If the page number of this page is larger than the current size of
40631    ** the database image, it may need to be written to the sub-journal.
40632    ** This is because the call to pager_write_pagelist() below will not
40633    ** actually write data to the file in this case.
40634    **
40635    ** Consider the following sequence of events:
40636    **
40637    **   BEGIN;
40638    **     <journal page X>
40639    **     <modify page X>
40640    **     SAVEPOINT sp;
40641    **       <shrink database file to Y pages>
40642    **       pagerStress(page X)
40643    **     ROLLBACK TO sp;
40644    **
40645    ** If (X>Y), then when pagerStress is called page X will not be written
40646    ** out to the database file, but will be dropped from the cache. Then,
40647    ** following the "ROLLBACK TO sp" statement, reading page X will read
40648    ** data from the database file. This will be the copy of page X as it
40649    ** was when the transaction started, not as it was when "SAVEPOINT sp"
40650    ** was executed.
40651    **
40652    ** The solution is to write the current data for page X into the
40653    ** sub-journal file now (if it is not already there), so that it will
40654    ** be restored to its current value when the "ROLLBACK TO sp" is
40655    ** executed.
40656    */
40657    if( NEVER(
40658        rc==SQLITE_OK && pPg->pgno>pPager->dbSize && subjRequiresPage(pPg)
40659    ) ){
40660      rc = subjournalPage(pPg);
40661    }
40662
40663    /* Write the contents of the page out to the database file. */
40664    if( rc==SQLITE_OK ){
40665      assert( (pPg->flags&PGHDR_NEED_SYNC)==0 );
40666      rc = pager_write_pagelist(pPager, pPg);
40667    }
40668  }
40669
40670  /* Mark the page as clean. */
40671  if( rc==SQLITE_OK ){
40672    PAGERTRACE(("STRESS %d page %d\n", PAGERID(pPager), pPg->pgno));
40673    sqlite3PcacheMakeClean(pPg);
40674  }
40675
40676  return pager_error(pPager, rc);
40677}
40678
40679
40680/*
40681** Allocate and initialize a new Pager object and put a pointer to it
40682** in *ppPager. The pager should eventually be freed by passing it
40683** to sqlite3PagerClose().
40684**
40685** The zFilename argument is the path to the database file to open.
40686** If zFilename is NULL then a randomly-named temporary file is created
40687** and used as the file to be cached. Temporary files are be deleted
40688** automatically when they are closed. If zFilename is ":memory:" then
40689** all information is held in cache. It is never written to disk.
40690** This can be used to implement an in-memory database.
40691**
40692** The nExtra parameter specifies the number of bytes of space allocated
40693** along with each page reference. This space is available to the user
40694** via the sqlite3PagerGetExtra() API.
40695**
40696** The flags argument is used to specify properties that affect the
40697** operation of the pager. It should be passed some bitwise combination
40698** of the PAGER_OMIT_JOURNAL and PAGER_NO_READLOCK flags.
40699**
40700** The vfsFlags parameter is a bitmask to pass to the flags parameter
40701** of the xOpen() method of the supplied VFS when opening files.
40702**
40703** If the pager object is allocated and the specified file opened
40704** successfully, SQLITE_OK is returned and *ppPager set to point to
40705** the new pager object. If an error occurs, *ppPager is set to NULL
40706** and error code returned. This function may return SQLITE_NOMEM
40707** (sqlite3Malloc() is used to allocate memory), SQLITE_CANTOPEN or
40708** various SQLITE_IO_XXX errors.
40709*/
40710SQLITE_PRIVATE int sqlite3PagerOpen(
40711  sqlite3_vfs *pVfs,       /* The virtual file system to use */
40712  Pager **ppPager,         /* OUT: Return the Pager structure here */
40713  const char *zFilename,   /* Name of the database file to open */
40714  int nExtra,              /* Extra bytes append to each in-memory page */
40715  int flags,               /* flags controlling this file */
40716  int vfsFlags,            /* flags passed through to sqlite3_vfs.xOpen() */
40717  void (*xReinit)(DbPage*) /* Function to reinitialize pages */
40718){
40719  u8 *pPtr;
40720  Pager *pPager = 0;       /* Pager object to allocate and return */
40721  int rc = SQLITE_OK;      /* Return code */
40722  int tempFile = 0;        /* True for temp files (incl. in-memory files) */
40723  int memDb = 0;           /* True if this is an in-memory file */
40724  int readOnly = 0;        /* True if this is a read-only file */
40725  int journalFileSize;     /* Bytes to allocate for each journal fd */
40726  char *zPathname = 0;     /* Full path to database file */
40727  int nPathname = 0;       /* Number of bytes in zPathname */
40728  int useJournal = (flags & PAGER_OMIT_JOURNAL)==0; /* False to omit journal */
40729  int noReadlock = (flags & PAGER_NO_READLOCK)!=0;  /* True to omit read-lock */
40730  int pcacheSize = sqlite3PcacheSize();       /* Bytes to allocate for PCache */
40731  u32 szPageDflt = SQLITE_DEFAULT_PAGE_SIZE;  /* Default page size */
40732
40733  /* Figure out how much space is required for each journal file-handle
40734  ** (there are two of them, the main journal and the sub-journal). This
40735  ** is the maximum space required for an in-memory journal file handle
40736  ** and a regular journal file-handle. Note that a "regular journal-handle"
40737  ** may be a wrapper capable of caching the first portion of the journal
40738  ** file in memory to implement the atomic-write optimization (see
40739  ** source file journal.c).
40740  */
40741  if( sqlite3JournalSize(pVfs)>sqlite3MemJournalSize() ){
40742    journalFileSize = ROUND8(sqlite3JournalSize(pVfs));
40743  }else{
40744    journalFileSize = ROUND8(sqlite3MemJournalSize());
40745  }
40746
40747  /* Set the output variable to NULL in case an error occurs. */
40748  *ppPager = 0;
40749
40750#ifndef SQLITE_OMIT_MEMORYDB
40751  if( flags & PAGER_MEMORY ){
40752    memDb = 1;
40753    zFilename = 0;
40754  }
40755#endif
40756
40757  /* Compute and store the full pathname in an allocated buffer pointed
40758  ** to by zPathname, length nPathname. Or, if this is a temporary file,
40759  ** leave both nPathname and zPathname set to 0.
40760  */
40761  if( zFilename && zFilename[0] ){
40762    nPathname = pVfs->mxPathname+1;
40763    zPathname = sqlite3Malloc(nPathname*2);
40764    if( zPathname==0 ){
40765      return SQLITE_NOMEM;
40766    }
40767    zPathname[0] = 0; /* Make sure initialized even if FullPathname() fails */
40768    rc = sqlite3OsFullPathname(pVfs, zFilename, nPathname, zPathname);
40769    nPathname = sqlite3Strlen30(zPathname);
40770    if( rc==SQLITE_OK && nPathname+8>pVfs->mxPathname ){
40771      /* This branch is taken when the journal path required by
40772      ** the database being opened will be more than pVfs->mxPathname
40773      ** bytes in length. This means the database cannot be opened,
40774      ** as it will not be possible to open the journal file or even
40775      ** check for a hot-journal before reading.
40776      */
40777      rc = SQLITE_CANTOPEN_BKPT;
40778    }
40779    if( rc!=SQLITE_OK ){
40780      sqlite3_free(zPathname);
40781      return rc;
40782    }
40783  }
40784
40785  /* Allocate memory for the Pager structure, PCache object, the
40786  ** three file descriptors, the database file name and the journal
40787  ** file name. The layout in memory is as follows:
40788  **
40789  **     Pager object                    (sizeof(Pager) bytes)
40790  **     PCache object                   (sqlite3PcacheSize() bytes)
40791  **     Database file handle            (pVfs->szOsFile bytes)
40792  **     Sub-journal file handle         (journalFileSize bytes)
40793  **     Main journal file handle        (journalFileSize bytes)
40794  **     Database file name              (nPathname+1 bytes)
40795  **     Journal file name               (nPathname+8+1 bytes)
40796  */
40797  pPtr = (u8 *)sqlite3MallocZero(
40798    ROUND8(sizeof(*pPager)) +      /* Pager structure */
40799    ROUND8(pcacheSize) +           /* PCache object */
40800    ROUND8(pVfs->szOsFile) +       /* The main db file */
40801    journalFileSize * 2 +          /* The two journal files */
40802    nPathname + 1 +                /* zFilename */
40803    nPathname + 8 + 1              /* zJournal */
40804#ifndef SQLITE_OMIT_WAL
40805    + nPathname + 4 + 1              /* zWal */
40806#endif
40807  );
40808  assert( EIGHT_BYTE_ALIGNMENT(SQLITE_INT_TO_PTR(journalFileSize)) );
40809  if( !pPtr ){
40810    sqlite3_free(zPathname);
40811    return SQLITE_NOMEM;
40812  }
40813  pPager =              (Pager*)(pPtr);
40814  pPager->pPCache =    (PCache*)(pPtr += ROUND8(sizeof(*pPager)));
40815  pPager->fd =   (sqlite3_file*)(pPtr += ROUND8(pcacheSize));
40816  pPager->sjfd = (sqlite3_file*)(pPtr += ROUND8(pVfs->szOsFile));
40817  pPager->jfd =  (sqlite3_file*)(pPtr += journalFileSize);
40818  pPager->zFilename =    (char*)(pPtr += journalFileSize);
40819  assert( EIGHT_BYTE_ALIGNMENT(pPager->jfd) );
40820
40821  /* Fill in the Pager.zFilename and Pager.zJournal buffers, if required. */
40822  if( zPathname ){
40823    assert( nPathname>0 );
40824    pPager->zJournal =   (char*)(pPtr += nPathname + 1);
40825    memcpy(pPager->zFilename, zPathname, nPathname);
40826    memcpy(pPager->zJournal, zPathname, nPathname);
40827    memcpy(&pPager->zJournal[nPathname], "-journal", 8);
40828#ifndef SQLITE_OMIT_WAL
40829    pPager->zWal = &pPager->zJournal[nPathname+8+1];
40830    memcpy(pPager->zWal, zPathname, nPathname);
40831    memcpy(&pPager->zWal[nPathname], "-wal", 4);
40832#endif
40833    sqlite3_free(zPathname);
40834  }
40835  pPager->pVfs = pVfs;
40836  pPager->vfsFlags = vfsFlags;
40837
40838  /* Open the pager file.
40839  */
40840  if( zFilename && zFilename[0] ){
40841    int fout = 0;                    /* VFS flags returned by xOpen() */
40842    rc = sqlite3OsOpen(pVfs, pPager->zFilename, pPager->fd, vfsFlags, &fout);
40843    assert( !memDb );
40844    readOnly = (fout&SQLITE_OPEN_READONLY);
40845
40846    /* If the file was successfully opened for read/write access,
40847    ** choose a default page size in case we have to create the
40848    ** database file. The default page size is the maximum of:
40849    **
40850    **    + SQLITE_DEFAULT_PAGE_SIZE,
40851    **    + The value returned by sqlite3OsSectorSize()
40852    **    + The largest page size that can be written atomically.
40853    */
40854    if( rc==SQLITE_OK && !readOnly ){
40855      setSectorSize(pPager);
40856      assert(SQLITE_DEFAULT_PAGE_SIZE<=SQLITE_MAX_DEFAULT_PAGE_SIZE);
40857      if( szPageDflt<pPager->sectorSize ){
40858        if( pPager->sectorSize>SQLITE_MAX_DEFAULT_PAGE_SIZE ){
40859          szPageDflt = SQLITE_MAX_DEFAULT_PAGE_SIZE;
40860        }else{
40861          szPageDflt = (u32)pPager->sectorSize;
40862        }
40863      }
40864#ifdef SQLITE_ENABLE_ATOMIC_WRITE
40865      {
40866        int iDc = sqlite3OsDeviceCharacteristics(pPager->fd);
40867        int ii;
40868        assert(SQLITE_IOCAP_ATOMIC512==(512>>8));
40869        assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8));
40870        assert(SQLITE_MAX_DEFAULT_PAGE_SIZE<=65536);
40871        for(ii=szPageDflt; ii<=SQLITE_MAX_DEFAULT_PAGE_SIZE; ii=ii*2){
40872          if( iDc&(SQLITE_IOCAP_ATOMIC|(ii>>8)) ){
40873            szPageDflt = ii;
40874          }
40875        }
40876      }
40877#endif
40878    }
40879  }else{
40880    /* If a temporary file is requested, it is not opened immediately.
40881    ** In this case we accept the default page size and delay actually
40882    ** opening the file until the first call to OsWrite().
40883    **
40884    ** This branch is also run for an in-memory database. An in-memory
40885    ** database is the same as a temp-file that is never written out to
40886    ** disk and uses an in-memory rollback journal.
40887    */
40888    tempFile = 1;
40889    pPager->eState = PAGER_READER;
40890    pPager->eLock = EXCLUSIVE_LOCK;
40891    readOnly = (vfsFlags&SQLITE_OPEN_READONLY);
40892  }
40893
40894  /* The following call to PagerSetPagesize() serves to set the value of
40895  ** Pager.pageSize and to allocate the Pager.pTmpSpace buffer.
40896  */
40897  if( rc==SQLITE_OK ){
40898    assert( pPager->memDb==0 );
40899    rc = sqlite3PagerSetPagesize(pPager, &szPageDflt, -1);
40900    testcase( rc!=SQLITE_OK );
40901  }
40902
40903  /* If an error occurred in either of the blocks above, free the
40904  ** Pager structure and close the file.
40905  */
40906  if( rc!=SQLITE_OK ){
40907    assert( !pPager->pTmpSpace );
40908    sqlite3OsClose(pPager->fd);
40909    sqlite3_free(pPager);
40910    return rc;
40911  }
40912
40913  /* Initialize the PCache object. */
40914  assert( nExtra<1000 );
40915  nExtra = ROUND8(nExtra);
40916  sqlite3PcacheOpen(szPageDflt, nExtra, !memDb,
40917                    !memDb?pagerStress:0, (void *)pPager, pPager->pPCache);
40918
40919  PAGERTRACE(("OPEN %d %s\n", FILEHANDLEID(pPager->fd), pPager->zFilename));
40920  IOTRACE(("OPEN %p %s\n", pPager, pPager->zFilename))
40921
40922  pPager->useJournal = (u8)useJournal;
40923  pPager->noReadlock = (noReadlock && readOnly) ?1:0;
40924  /* pPager->stmtOpen = 0; */
40925  /* pPager->stmtInUse = 0; */
40926  /* pPager->nRef = 0; */
40927  /* pPager->stmtSize = 0; */
40928  /* pPager->stmtJSize = 0; */
40929  /* pPager->nPage = 0; */
40930  pPager->mxPgno = SQLITE_MAX_PAGE_COUNT;
40931  /* pPager->state = PAGER_UNLOCK; */
40932#if 0
40933  assert( pPager->state == (tempFile ? PAGER_EXCLUSIVE : PAGER_UNLOCK) );
40934#endif
40935  /* pPager->errMask = 0; */
40936  pPager->tempFile = (u8)tempFile;
40937  assert( tempFile==PAGER_LOCKINGMODE_NORMAL
40938          || tempFile==PAGER_LOCKINGMODE_EXCLUSIVE );
40939  assert( PAGER_LOCKINGMODE_EXCLUSIVE==1 );
40940  pPager->exclusiveMode = (u8)tempFile;
40941  pPager->changeCountDone = pPager->tempFile;
40942  pPager->memDb = (u8)memDb;
40943  pPager->readOnly = (u8)readOnly;
40944  assert( useJournal || pPager->tempFile );
40945  pPager->noSync = pPager->tempFile;
40946  pPager->fullSync = pPager->noSync ?0:1;
40947  pPager->syncFlags = pPager->noSync ? 0 : SQLITE_SYNC_NORMAL;
40948  pPager->ckptSyncFlags = pPager->syncFlags;
40949  /* pPager->pFirst = 0; */
40950  /* pPager->pFirstSynced = 0; */
40951  /* pPager->pLast = 0; */
40952  pPager->nExtra = (u16)nExtra;
40953  pPager->journalSizeLimit = SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT;
40954  assert( isOpen(pPager->fd) || tempFile );
40955  setSectorSize(pPager);
40956  if( !useJournal ){
40957    pPager->journalMode = PAGER_JOURNALMODE_OFF;
40958  }else if( memDb ){
40959    pPager->journalMode = PAGER_JOURNALMODE_MEMORY;
40960  }
40961  /* pPager->xBusyHandler = 0; */
40962  /* pPager->pBusyHandlerArg = 0; */
40963  pPager->xReiniter = xReinit;
40964  /* memset(pPager->aHash, 0, sizeof(pPager->aHash)); */
40965
40966  *ppPager = pPager;
40967  return SQLITE_OK;
40968}
40969
40970
40971
40972/*
40973** This function is called after transitioning from PAGER_UNLOCK to
40974** PAGER_SHARED state. It tests if there is a hot journal present in
40975** the file-system for the given pager. A hot journal is one that
40976** needs to be played back. According to this function, a hot-journal
40977** file exists if the following criteria are met:
40978**
40979**   * The journal file exists in the file system, and
40980**   * No process holds a RESERVED or greater lock on the database file, and
40981**   * The database file itself is greater than 0 bytes in size, and
40982**   * The first byte of the journal file exists and is not 0x00.
40983**
40984** If the current size of the database file is 0 but a journal file
40985** exists, that is probably an old journal left over from a prior
40986** database with the same name. In this case the journal file is
40987** just deleted using OsDelete, *pExists is set to 0 and SQLITE_OK
40988** is returned.
40989**
40990** This routine does not check if there is a master journal filename
40991** at the end of the file. If there is, and that master journal file
40992** does not exist, then the journal file is not really hot. In this
40993** case this routine will return a false-positive. The pager_playback()
40994** routine will discover that the journal file is not really hot and
40995** will not roll it back.
40996**
40997** If a hot-journal file is found to exist, *pExists is set to 1 and
40998** SQLITE_OK returned. If no hot-journal file is present, *pExists is
40999** set to 0 and SQLITE_OK returned. If an IO error occurs while trying
41000** to determine whether or not a hot-journal file exists, the IO error
41001** code is returned and the value of *pExists is undefined.
41002*/
41003static int hasHotJournal(Pager *pPager, int *pExists){
41004  sqlite3_vfs * const pVfs = pPager->pVfs;
41005  int rc = SQLITE_OK;           /* Return code */
41006  int exists = 1;               /* True if a journal file is present */
41007  int jrnlOpen = !!isOpen(pPager->jfd);
41008
41009  assert( pPager->useJournal );
41010  assert( isOpen(pPager->fd) );
41011  assert( pPager->eState==PAGER_OPEN );
41012
41013  assert( jrnlOpen==0 || ( sqlite3OsDeviceCharacteristics(pPager->jfd) &
41014    SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN
41015  ));
41016
41017  *pExists = 0;
41018  if( !jrnlOpen ){
41019    rc = sqlite3OsAccess(pVfs, pPager->zJournal, SQLITE_ACCESS_EXISTS, &exists);
41020  }
41021  if( rc==SQLITE_OK && exists ){
41022    int locked = 0;             /* True if some process holds a RESERVED lock */
41023
41024    /* Race condition here:  Another process might have been holding the
41025    ** the RESERVED lock and have a journal open at the sqlite3OsAccess()
41026    ** call above, but then delete the journal and drop the lock before
41027    ** we get to the following sqlite3OsCheckReservedLock() call.  If that
41028    ** is the case, this routine might think there is a hot journal when
41029    ** in fact there is none.  This results in a false-positive which will
41030    ** be dealt with by the playback routine.  Ticket #3883.
41031    */
41032    rc = sqlite3OsCheckReservedLock(pPager->fd, &locked);
41033    if( rc==SQLITE_OK && !locked ){
41034      Pgno nPage;                 /* Number of pages in database file */
41035
41036      /* Check the size of the database file. If it consists of 0 pages,
41037      ** then delete the journal file. See the header comment above for
41038      ** the reasoning here.  Delete the obsolete journal file under
41039      ** a RESERVED lock to avoid race conditions and to avoid violating
41040      ** [H33020].
41041      */
41042      rc = pagerPagecount(pPager, &nPage);
41043      if( rc==SQLITE_OK ){
41044        if( nPage==0 ){
41045          sqlite3BeginBenignMalloc();
41046          if( pagerLockDb(pPager, RESERVED_LOCK)==SQLITE_OK ){
41047            sqlite3OsDelete(pVfs, pPager->zJournal, 0);
41048            if( !pPager->exclusiveMode ) pagerUnlockDb(pPager, SHARED_LOCK);
41049          }
41050          sqlite3EndBenignMalloc();
41051        }else{
41052          /* The journal file exists and no other connection has a reserved
41053          ** or greater lock on the database file. Now check that there is
41054          ** at least one non-zero bytes at the start of the journal file.
41055          ** If there is, then we consider this journal to be hot. If not,
41056          ** it can be ignored.
41057          */
41058          if( !jrnlOpen ){
41059            int f = SQLITE_OPEN_READONLY|SQLITE_OPEN_MAIN_JOURNAL;
41060            rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &f);
41061          }
41062          if( rc==SQLITE_OK ){
41063            u8 first = 0;
41064            rc = sqlite3OsRead(pPager->jfd, (void *)&first, 1, 0);
41065            if( rc==SQLITE_IOERR_SHORT_READ ){
41066              rc = SQLITE_OK;
41067            }
41068            if( !jrnlOpen ){
41069              sqlite3OsClose(pPager->jfd);
41070            }
41071            *pExists = (first!=0);
41072          }else if( rc==SQLITE_CANTOPEN ){
41073            /* If we cannot open the rollback journal file in order to see if
41074            ** its has a zero header, that might be due to an I/O error, or
41075            ** it might be due to the race condition described above and in
41076            ** ticket #3883.  Either way, assume that the journal is hot.
41077            ** This might be a false positive.  But if it is, then the
41078            ** automatic journal playback and recovery mechanism will deal
41079            ** with it under an EXCLUSIVE lock where we do not need to
41080            ** worry so much with race conditions.
41081            */
41082            *pExists = 1;
41083            rc = SQLITE_OK;
41084          }
41085        }
41086      }
41087    }
41088  }
41089
41090  return rc;
41091}
41092
41093/*
41094** This function is called to obtain a shared lock on the database file.
41095** It is illegal to call sqlite3PagerAcquire() until after this function
41096** has been successfully called. If a shared-lock is already held when
41097** this function is called, it is a no-op.
41098**
41099** The following operations are also performed by this function.
41100**
41101**   1) If the pager is currently in PAGER_OPEN state (no lock held
41102**      on the database file), then an attempt is made to obtain a
41103**      SHARED lock on the database file. Immediately after obtaining
41104**      the SHARED lock, the file-system is checked for a hot-journal,
41105**      which is played back if present. Following any hot-journal
41106**      rollback, the contents of the cache are validated by checking
41107**      the 'change-counter' field of the database file header and
41108**      discarded if they are found to be invalid.
41109**
41110**   2) If the pager is running in exclusive-mode, and there are currently
41111**      no outstanding references to any pages, and is in the error state,
41112**      then an attempt is made to clear the error state by discarding
41113**      the contents of the page cache and rolling back any open journal
41114**      file.
41115**
41116** If everything is successful, SQLITE_OK is returned. If an IO error
41117** occurs while locking the database, checking for a hot-journal file or
41118** rolling back a journal file, the IO error code is returned.
41119*/
41120SQLITE_PRIVATE int sqlite3PagerSharedLock(Pager *pPager){
41121  int rc = SQLITE_OK;                /* Return code */
41122
41123  /* This routine is only called from b-tree and only when there are no
41124  ** outstanding pages. This implies that the pager state should either
41125  ** be OPEN or READER. READER is only possible if the pager is or was in
41126  ** exclusive access mode.
41127  */
41128  assert( sqlite3PcacheRefCount(pPager->pPCache)==0 );
41129  assert( assert_pager_state(pPager) );
41130  assert( pPager->eState==PAGER_OPEN || pPager->eState==PAGER_READER );
41131  if( NEVER(MEMDB && pPager->errCode) ){ return pPager->errCode; }
41132
41133  if( !pagerUseWal(pPager) && pPager->eState==PAGER_OPEN ){
41134    int bHotJournal = 1;          /* True if there exists a hot journal-file */
41135
41136    assert( !MEMDB );
41137    assert( pPager->noReadlock==0 || pPager->readOnly );
41138
41139    if( pPager->noReadlock==0 ){
41140      rc = pager_wait_on_lock(pPager, SHARED_LOCK);
41141      if( rc!=SQLITE_OK ){
41142        assert( pPager->eLock==NO_LOCK || pPager->eLock==UNKNOWN_LOCK );
41143        goto failed;
41144      }
41145    }
41146
41147    /* If a journal file exists, and there is no RESERVED lock on the
41148    ** database file, then it either needs to be played back or deleted.
41149    */
41150    if( pPager->eLock<=SHARED_LOCK ){
41151      rc = hasHotJournal(pPager, &bHotJournal);
41152    }
41153    if( rc!=SQLITE_OK ){
41154      goto failed;
41155    }
41156    if( bHotJournal ){
41157      /* Get an EXCLUSIVE lock on the database file. At this point it is
41158      ** important that a RESERVED lock is not obtained on the way to the
41159      ** EXCLUSIVE lock. If it were, another process might open the
41160      ** database file, detect the RESERVED lock, and conclude that the
41161      ** database is safe to read while this process is still rolling the
41162      ** hot-journal back.
41163      **
41164      ** Because the intermediate RESERVED lock is not requested, any
41165      ** other process attempting to access the database file will get to
41166      ** this point in the code and fail to obtain its own EXCLUSIVE lock
41167      ** on the database file.
41168      **
41169      ** Unless the pager is in locking_mode=exclusive mode, the lock is
41170      ** downgraded to SHARED_LOCK before this function returns.
41171      */
41172      rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
41173      if( rc!=SQLITE_OK ){
41174        goto failed;
41175      }
41176
41177      /* If it is not already open and the file exists on disk, open the
41178      ** journal for read/write access. Write access is required because
41179      ** in exclusive-access mode the file descriptor will be kept open
41180      ** and possibly used for a transaction later on. Also, write-access
41181      ** is usually required to finalize the journal in journal_mode=persist
41182      ** mode (and also for journal_mode=truncate on some systems).
41183      **
41184      ** If the journal does not exist, it usually means that some
41185      ** other connection managed to get in and roll it back before
41186      ** this connection obtained the exclusive lock above. Or, it
41187      ** may mean that the pager was in the error-state when this
41188      ** function was called and the journal file does not exist.
41189      */
41190      if( !isOpen(pPager->jfd) ){
41191        sqlite3_vfs * const pVfs = pPager->pVfs;
41192        int bExists;              /* True if journal file exists */
41193        rc = sqlite3OsAccess(
41194            pVfs, pPager->zJournal, SQLITE_ACCESS_EXISTS, &bExists);
41195        if( rc==SQLITE_OK && bExists ){
41196          int fout = 0;
41197          int f = SQLITE_OPEN_READWRITE|SQLITE_OPEN_MAIN_JOURNAL;
41198          assert( !pPager->tempFile );
41199          rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &fout);
41200          assert( rc!=SQLITE_OK || isOpen(pPager->jfd) );
41201          if( rc==SQLITE_OK && fout&SQLITE_OPEN_READONLY ){
41202            rc = SQLITE_CANTOPEN_BKPT;
41203            sqlite3OsClose(pPager->jfd);
41204          }
41205        }
41206      }
41207
41208      /* Playback and delete the journal.  Drop the database write
41209      ** lock and reacquire the read lock. Purge the cache before
41210      ** playing back the hot-journal so that we don't end up with
41211      ** an inconsistent cache.  Sync the hot journal before playing
41212      ** it back since the process that crashed and left the hot journal
41213      ** probably did not sync it and we are required to always sync
41214      ** the journal before playing it back.
41215      */
41216      if( isOpen(pPager->jfd) ){
41217        assert( rc==SQLITE_OK );
41218        rc = pagerSyncHotJournal(pPager);
41219        if( rc==SQLITE_OK ){
41220          rc = pager_playback(pPager, 1);
41221          pPager->eState = PAGER_OPEN;
41222        }
41223      }else if( !pPager->exclusiveMode ){
41224        pagerUnlockDb(pPager, SHARED_LOCK);
41225      }
41226
41227      if( rc!=SQLITE_OK ){
41228        /* This branch is taken if an error occurs while trying to open
41229        ** or roll back a hot-journal while holding an EXCLUSIVE lock. The
41230        ** pager_unlock() routine will be called before returning to unlock
41231        ** the file. If the unlock attempt fails, then Pager.eLock must be
41232        ** set to UNKNOWN_LOCK (see the comment above the #define for
41233        ** UNKNOWN_LOCK above for an explanation).
41234        **
41235        ** In order to get pager_unlock() to do this, set Pager.eState to
41236        ** PAGER_ERROR now. This is not actually counted as a transition
41237        ** to ERROR state in the state diagram at the top of this file,
41238        ** since we know that the same call to pager_unlock() will very
41239        ** shortly transition the pager object to the OPEN state. Calling
41240        ** assert_pager_state() would fail now, as it should not be possible
41241        ** to be in ERROR state when there are zero outstanding page
41242        ** references.
41243        */
41244        pager_error(pPager, rc);
41245        goto failed;
41246      }
41247
41248      assert( pPager->eState==PAGER_OPEN );
41249      assert( (pPager->eLock==SHARED_LOCK)
41250           || (pPager->exclusiveMode && pPager->eLock>SHARED_LOCK)
41251      );
41252    }
41253
41254    if( !pPager->tempFile
41255     && (pPager->pBackup || sqlite3PcachePagecount(pPager->pPCache)>0)
41256    ){
41257      /* The shared-lock has just been acquired on the database file
41258      ** and there are already pages in the cache (from a previous
41259      ** read or write transaction).  Check to see if the database
41260      ** has been modified.  If the database has changed, flush the
41261      ** cache.
41262      **
41263      ** Database changes is detected by looking at 15 bytes beginning
41264      ** at offset 24 into the file.  The first 4 of these 16 bytes are
41265      ** a 32-bit counter that is incremented with each change.  The
41266      ** other bytes change randomly with each file change when
41267      ** a codec is in use.
41268      **
41269      ** There is a vanishingly small chance that a change will not be
41270      ** detected.  The chance of an undetected change is so small that
41271      ** it can be neglected.
41272      */
41273      Pgno nPage = 0;
41274      char dbFileVers[sizeof(pPager->dbFileVers)];
41275
41276      rc = pagerPagecount(pPager, &nPage);
41277      if( rc ) goto failed;
41278
41279      if( nPage>0 ){
41280        IOTRACE(("CKVERS %p %d\n", pPager, sizeof(dbFileVers)));
41281        rc = sqlite3OsRead(pPager->fd, &dbFileVers, sizeof(dbFileVers), 24);
41282        if( rc!=SQLITE_OK ){
41283          goto failed;
41284        }
41285      }else{
41286        memset(dbFileVers, 0, sizeof(dbFileVers));
41287      }
41288
41289      if( memcmp(pPager->dbFileVers, dbFileVers, sizeof(dbFileVers))!=0 ){
41290        pager_reset(pPager);
41291      }
41292    }
41293
41294    /* If there is a WAL file in the file-system, open this database in WAL
41295    ** mode. Otherwise, the following function call is a no-op.
41296    */
41297    rc = pagerOpenWalIfPresent(pPager);
41298#ifndef SQLITE_OMIT_WAL
41299    assert( pPager->pWal==0 || rc==SQLITE_OK );
41300#endif
41301  }
41302
41303  if( pagerUseWal(pPager) ){
41304    assert( rc==SQLITE_OK );
41305    rc = pagerBeginReadTransaction(pPager);
41306  }
41307
41308  if( pPager->eState==PAGER_OPEN && rc==SQLITE_OK ){
41309    rc = pagerPagecount(pPager, &pPager->dbSize);
41310  }
41311
41312 failed:
41313  if( rc!=SQLITE_OK ){
41314    assert( !MEMDB );
41315    pager_unlock(pPager);
41316    assert( pPager->eState==PAGER_OPEN );
41317  }else{
41318    pPager->eState = PAGER_READER;
41319  }
41320  return rc;
41321}
41322
41323/*
41324** If the reference count has reached zero, rollback any active
41325** transaction and unlock the pager.
41326**
41327** Except, in locking_mode=EXCLUSIVE when there is nothing to in
41328** the rollback journal, the unlock is not performed and there is
41329** nothing to rollback, so this routine is a no-op.
41330*/
41331static void pagerUnlockIfUnused(Pager *pPager){
41332  if( (sqlite3PcacheRefCount(pPager->pPCache)==0) ){
41333    pagerUnlockAndRollback(pPager);
41334  }
41335}
41336
41337/*
41338** Acquire a reference to page number pgno in pager pPager (a page
41339** reference has type DbPage*). If the requested reference is
41340** successfully obtained, it is copied to *ppPage and SQLITE_OK returned.
41341**
41342** If the requested page is already in the cache, it is returned.
41343** Otherwise, a new page object is allocated and populated with data
41344** read from the database file. In some cases, the pcache module may
41345** choose not to allocate a new page object and may reuse an existing
41346** object with no outstanding references.
41347**
41348** The extra data appended to a page is always initialized to zeros the
41349** first time a page is loaded into memory. If the page requested is
41350** already in the cache when this function is called, then the extra
41351** data is left as it was when the page object was last used.
41352**
41353** If the database image is smaller than the requested page or if a
41354** non-zero value is passed as the noContent parameter and the
41355** requested page is not already stored in the cache, then no
41356** actual disk read occurs. In this case the memory image of the
41357** page is initialized to all zeros.
41358**
41359** If noContent is true, it means that we do not care about the contents
41360** of the page. This occurs in two seperate scenarios:
41361**
41362**   a) When reading a free-list leaf page from the database, and
41363**
41364**   b) When a savepoint is being rolled back and we need to load
41365**      a new page into the cache to be filled with the data read
41366**      from the savepoint journal.
41367**
41368** If noContent is true, then the data returned is zeroed instead of
41369** being read from the database. Additionally, the bits corresponding
41370** to pgno in Pager.pInJournal (bitvec of pages already written to the
41371** journal file) and the PagerSavepoint.pInSavepoint bitvecs of any open
41372** savepoints are set. This means if the page is made writable at any
41373** point in the future, using a call to sqlite3PagerWrite(), its contents
41374** will not be journaled. This saves IO.
41375**
41376** The acquisition might fail for several reasons.  In all cases,
41377** an appropriate error code is returned and *ppPage is set to NULL.
41378**
41379** See also sqlite3PagerLookup().  Both this routine and Lookup() attempt
41380** to find a page in the in-memory cache first.  If the page is not already
41381** in memory, this routine goes to disk to read it in whereas Lookup()
41382** just returns 0.  This routine acquires a read-lock the first time it
41383** has to go to disk, and could also playback an old journal if necessary.
41384** Since Lookup() never goes to disk, it never has to deal with locks
41385** or journal files.
41386*/
41387SQLITE_PRIVATE int sqlite3PagerAcquire(
41388  Pager *pPager,      /* The pager open on the database file */
41389  Pgno pgno,          /* Page number to fetch */
41390  DbPage **ppPage,    /* Write a pointer to the page here */
41391  int noContent       /* Do not bother reading content from disk if true */
41392){
41393  int rc;
41394  PgHdr *pPg;
41395
41396  assert( pPager->eState>=PAGER_READER );
41397  assert( assert_pager_state(pPager) );
41398
41399  if( pgno==0 ){
41400    return SQLITE_CORRUPT_BKPT;
41401  }
41402
41403  /* If the pager is in the error state, return an error immediately.
41404  ** Otherwise, request the page from the PCache layer. */
41405  if( pPager->errCode!=SQLITE_OK ){
41406    rc = pPager->errCode;
41407  }else{
41408    rc = sqlite3PcacheFetch(pPager->pPCache, pgno, 1, ppPage);
41409  }
41410
41411  if( rc!=SQLITE_OK ){
41412    /* Either the call to sqlite3PcacheFetch() returned an error or the
41413    ** pager was already in the error-state when this function was called.
41414    ** Set pPg to 0 and jump to the exception handler.  */
41415    pPg = 0;
41416    goto pager_acquire_err;
41417  }
41418  assert( (*ppPage)->pgno==pgno );
41419  assert( (*ppPage)->pPager==pPager || (*ppPage)->pPager==0 );
41420
41421  if( (*ppPage)->pPager && !noContent ){
41422    /* In this case the pcache already contains an initialized copy of
41423    ** the page. Return without further ado.  */
41424    assert( pgno<=PAGER_MAX_PGNO && pgno!=PAGER_MJ_PGNO(pPager) );
41425    PAGER_INCR(pPager->nHit);
41426    return SQLITE_OK;
41427
41428  }else{
41429    /* The pager cache has created a new page. Its content needs to
41430    ** be initialized.  */
41431
41432    PAGER_INCR(pPager->nMiss);
41433    pPg = *ppPage;
41434    pPg->pPager = pPager;
41435
41436    /* The maximum page number is 2^31. Return SQLITE_CORRUPT if a page
41437    ** number greater than this, or the unused locking-page, is requested. */
41438    if( pgno>PAGER_MAX_PGNO || pgno==PAGER_MJ_PGNO(pPager) ){
41439      rc = SQLITE_CORRUPT_BKPT;
41440      goto pager_acquire_err;
41441    }
41442
41443    if( MEMDB || pPager->dbSize<pgno || noContent || !isOpen(pPager->fd) ){
41444      if( pgno>pPager->mxPgno ){
41445        rc = SQLITE_FULL;
41446        goto pager_acquire_err;
41447      }
41448      if( noContent ){
41449        /* Failure to set the bits in the InJournal bit-vectors is benign.
41450        ** It merely means that we might do some extra work to journal a
41451        ** page that does not need to be journaled.  Nevertheless, be sure
41452        ** to test the case where a malloc error occurs while trying to set
41453        ** a bit in a bit vector.
41454        */
41455        sqlite3BeginBenignMalloc();
41456        if( pgno<=pPager->dbOrigSize ){
41457          TESTONLY( rc = ) sqlite3BitvecSet(pPager->pInJournal, pgno);
41458          testcase( rc==SQLITE_NOMEM );
41459        }
41460        TESTONLY( rc = ) addToSavepointBitvecs(pPager, pgno);
41461        testcase( rc==SQLITE_NOMEM );
41462        sqlite3EndBenignMalloc();
41463      }
41464      memset(pPg->pData, 0, pPager->pageSize);
41465      IOTRACE(("ZERO %p %d\n", pPager, pgno));
41466    }else{
41467      assert( pPg->pPager==pPager );
41468      rc = readDbPage(pPg);
41469      if( rc!=SQLITE_OK ){
41470        goto pager_acquire_err;
41471      }
41472    }
41473    pager_set_pagehash(pPg);
41474  }
41475
41476  return SQLITE_OK;
41477
41478pager_acquire_err:
41479  assert( rc!=SQLITE_OK );
41480  if( pPg ){
41481    sqlite3PcacheDrop(pPg);
41482  }
41483  pagerUnlockIfUnused(pPager);
41484
41485  *ppPage = 0;
41486  return rc;
41487}
41488
41489/*
41490** Acquire a page if it is already in the in-memory cache.  Do
41491** not read the page from disk.  Return a pointer to the page,
41492** or 0 if the page is not in cache.
41493**
41494** See also sqlite3PagerGet().  The difference between this routine
41495** and sqlite3PagerGet() is that _get() will go to the disk and read
41496** in the page if the page is not already in cache.  This routine
41497** returns NULL if the page is not in cache or if a disk I/O error
41498** has ever happened.
41499*/
41500SQLITE_PRIVATE DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno){
41501  PgHdr *pPg = 0;
41502  assert( pPager!=0 );
41503  assert( pgno!=0 );
41504  assert( pPager->pPCache!=0 );
41505  assert( pPager->eState>=PAGER_READER && pPager->eState!=PAGER_ERROR );
41506  sqlite3PcacheFetch(pPager->pPCache, pgno, 0, &pPg);
41507  return pPg;
41508}
41509
41510/*
41511** Release a page reference.
41512**
41513** If the number of references to the page drop to zero, then the
41514** page is added to the LRU list.  When all references to all pages
41515** are released, a rollback occurs and the lock on the database is
41516** removed.
41517*/
41518SQLITE_PRIVATE void sqlite3PagerUnref(DbPage *pPg){
41519  if( pPg ){
41520    Pager *pPager = pPg->pPager;
41521    sqlite3PcacheRelease(pPg);
41522    pagerUnlockIfUnused(pPager);
41523  }
41524}
41525
41526#if defined(__APPLE__)
41527/*
41528** Create and return a CFURLRef given a cstring containing the path to a file.
41529*/
41530static CFURLRef create_cfurl_from_cstring(const char* filePath){
41531  CFStringRef urlString = CFStringCreateWithFileSystemRepresentation(
41532      kCFAllocatorDefault, filePath);
41533  CFURLRef urlRef = CFURLCreateWithFileSystemPath(kCFAllocatorDefault,
41534      urlString, kCFURLPOSIXPathStyle, FALSE);
41535  CFRelease(urlString);
41536  return urlRef;
41537}
41538#endif
41539
41540/*
41541** This function is called at the start of every write transaction.
41542** There must already be a RESERVED or EXCLUSIVE lock on the database
41543** file when this routine is called.
41544**
41545** Open the journal file for pager pPager and write a journal header
41546** to the start of it. If there are active savepoints, open the sub-journal
41547** as well. This function is only used when the journal file is being
41548** opened to write a rollback log for a transaction. It is not used
41549** when opening a hot journal file to roll it back.
41550**
41551** If the journal file is already open (as it may be in exclusive mode),
41552** then this function just writes a journal header to the start of the
41553** already open file.
41554**
41555** Whether or not the journal file is opened by this function, the
41556** Pager.pInJournal bitvec structure is allocated.
41557**
41558** Return SQLITE_OK if everything is successful. Otherwise, return
41559** SQLITE_NOMEM if the attempt to allocate Pager.pInJournal fails, or
41560** an IO error code if opening or writing the journal file fails.
41561*/
41562static int pager_open_journal(Pager *pPager){
41563  int rc = SQLITE_OK;                        /* Return code */
41564  sqlite3_vfs * const pVfs = pPager->pVfs;   /* Local cache of vfs pointer */
41565
41566  assert( pPager->eState==PAGER_WRITER_LOCKED );
41567  assert( assert_pager_state(pPager) );
41568  assert( pPager->pInJournal==0 );
41569
41570  /* If already in the error state, this function is a no-op.  But on
41571  ** the other hand, this routine is never called if we are already in
41572  ** an error state. */
41573  if( NEVER(pPager->errCode) ) return pPager->errCode;
41574
41575  if( !pagerUseWal(pPager) && pPager->journalMode!=PAGER_JOURNALMODE_OFF ){
41576    pPager->pInJournal = sqlite3BitvecCreate(pPager->dbSize);
41577    if( pPager->pInJournal==0 ){
41578      return SQLITE_NOMEM;
41579    }
41580
41581    /* Open the journal file if it is not already open. */
41582    if( !isOpen(pPager->jfd) ){
41583      if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY ){
41584        sqlite3MemJournalOpen(pPager->jfd);
41585      }else{
41586        const int flags =                   /* VFS flags to open journal file */
41587          SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|
41588          (pPager->tempFile ?
41589            (SQLITE_OPEN_DELETEONCLOSE|SQLITE_OPEN_TEMP_JOURNAL):
41590            (SQLITE_OPEN_MAIN_JOURNAL)
41591          );
41592  #ifdef SQLITE_ENABLE_ATOMIC_WRITE
41593        rc = sqlite3JournalOpen(
41594            pVfs, pPager->zJournal, pPager->jfd, flags, jrnlBufferSize(pPager)
41595        );
41596  #else
41597        rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, flags, 0);
41598  #endif
41599#if defined(__APPLE__)
41600        /* Set the TimeMachine exclusion metadata for the journal if it has
41601        ** been set for the database. Only do this for unix-type vfs
41602        ** implementations. */
41603        if( rc==SQLITE_OK && pPager->zFilename!=NULL
41604         && strlen(pPager->zFilename)>0
41605         && strncmp(pVfs->zName, "unix", 4)==0
41606         && ( pVfs->zName[4]=='-' || pVfs->zName[4]=='\0' ) ){
41607          CFURLRef database = create_cfurl_from_cstring(pPager->zFilename);
41608          if( CSBackupIsItemExcluded(database, NULL) ){
41609            CFURLRef journal = create_cfurl_from_cstring(pPager->zJournal);
41610            /* Ignore errors from the following exclusion call. */
41611            CSBackupSetItemExcluded(journal, TRUE, FALSE);
41612            CFRelease(journal);
41613          }
41614          CFRelease(database);
41615        }
41616#endif
41617      }
41618      assert( rc!=SQLITE_OK || isOpen(pPager->jfd) );
41619    }
41620
41621
41622    /* Write the first journal header to the journal file and open
41623    ** the sub-journal if necessary.
41624    */
41625    if( rc==SQLITE_OK ){
41626      /* TODO: Check if all of these are really required. */
41627      pPager->nRec = 0;
41628      pPager->journalOff = 0;
41629      pPager->setMaster = 0;
41630      pPager->journalHdr = 0;
41631      rc = writeJournalHdr(pPager);
41632    }
41633  }
41634
41635  if( rc!=SQLITE_OK ){
41636    sqlite3BitvecDestroy(pPager->pInJournal);
41637    pPager->pInJournal = 0;
41638  }else{
41639    assert( pPager->eState==PAGER_WRITER_LOCKED );
41640    pPager->eState = PAGER_WRITER_CACHEMOD;
41641  }
41642
41643  return rc;
41644}
41645
41646/*
41647** Begin a write-transaction on the specified pager object. If a
41648** write-transaction has already been opened, this function is a no-op.
41649**
41650** If the exFlag argument is false, then acquire at least a RESERVED
41651** lock on the database file. If exFlag is true, then acquire at least
41652** an EXCLUSIVE lock. If such a lock is already held, no locking
41653** functions need be called.
41654**
41655** If the subjInMemory argument is non-zero, then any sub-journal opened
41656** within this transaction will be opened as an in-memory file. This
41657** has no effect if the sub-journal is already opened (as it may be when
41658** running in exclusive mode) or if the transaction does not require a
41659** sub-journal. If the subjInMemory argument is zero, then any required
41660** sub-journal is implemented in-memory if pPager is an in-memory database,
41661** or using a temporary file otherwise.
41662*/
41663SQLITE_PRIVATE int sqlite3PagerBegin(Pager *pPager, int exFlag, int subjInMemory){
41664  int rc = SQLITE_OK;
41665
41666  if( pPager->errCode ) return pPager->errCode;
41667  assert( pPager->eState>=PAGER_READER && pPager->eState<PAGER_ERROR );
41668  pPager->subjInMemory = (u8)subjInMemory;
41669
41670  if( ALWAYS(pPager->eState==PAGER_READER) ){
41671    assert( pPager->pInJournal==0 );
41672
41673    if( pagerUseWal(pPager) ){
41674      /* If the pager is configured to use locking_mode=exclusive, and an
41675      ** exclusive lock on the database is not already held, obtain it now.
41676      */
41677      if( pPager->exclusiveMode && sqlite3WalExclusiveMode(pPager->pWal, -1) ){
41678        rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
41679        if( rc!=SQLITE_OK ){
41680          return rc;
41681        }
41682        sqlite3WalExclusiveMode(pPager->pWal, 1);
41683      }
41684
41685      /* Grab the write lock on the log file. If successful, upgrade to
41686      ** PAGER_RESERVED state. Otherwise, return an error code to the caller.
41687      ** The busy-handler is not invoked if another connection already
41688      ** holds the write-lock. If possible, the upper layer will call it.
41689      */
41690      rc = sqlite3WalBeginWriteTransaction(pPager->pWal);
41691    }else{
41692      /* Obtain a RESERVED lock on the database file. If the exFlag parameter
41693      ** is true, then immediately upgrade this to an EXCLUSIVE lock. The
41694      ** busy-handler callback can be used when upgrading to the EXCLUSIVE
41695      ** lock, but not when obtaining the RESERVED lock.
41696      */
41697      rc = pagerLockDb(pPager, RESERVED_LOCK);
41698      if( rc==SQLITE_OK && exFlag ){
41699        rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);
41700      }
41701    }
41702
41703    if( rc==SQLITE_OK ){
41704      /* Change to WRITER_LOCKED state.
41705      **
41706      ** WAL mode sets Pager.eState to PAGER_WRITER_LOCKED or CACHEMOD
41707      ** when it has an open transaction, but never to DBMOD or FINISHED.
41708      ** This is because in those states the code to roll back savepoint
41709      ** transactions may copy data from the sub-journal into the database
41710      ** file as well as into the page cache. Which would be incorrect in
41711      ** WAL mode.
41712      */
41713      pPager->eState = PAGER_WRITER_LOCKED;
41714      pPager->dbHintSize = pPager->dbSize;
41715      pPager->dbFileSize = pPager->dbSize;
41716      pPager->dbOrigSize = pPager->dbSize;
41717      pPager->journalOff = 0;
41718    }
41719
41720    assert( rc==SQLITE_OK || pPager->eState==PAGER_READER );
41721    assert( rc!=SQLITE_OK || pPager->eState==PAGER_WRITER_LOCKED );
41722    assert( assert_pager_state(pPager) );
41723  }
41724
41725  PAGERTRACE(("TRANSACTION %d\n", PAGERID(pPager)));
41726  return rc;
41727}
41728
41729/*
41730** Mark a single data page as writeable. The page is written into the
41731** main journal or sub-journal as required. If the page is written into
41732** one of the journals, the corresponding bit is set in the
41733** Pager.pInJournal bitvec and the PagerSavepoint.pInSavepoint bitvecs
41734** of any open savepoints as appropriate.
41735*/
41736static int pager_write(PgHdr *pPg){
41737  void *pData = pPg->pData;
41738  Pager *pPager = pPg->pPager;
41739  int rc = SQLITE_OK;
41740
41741  /* This routine is not called unless a write-transaction has already
41742  ** been started. The journal file may or may not be open at this point.
41743  ** It is never called in the ERROR state.
41744  */
41745  assert( pPager->eState==PAGER_WRITER_LOCKED
41746       || pPager->eState==PAGER_WRITER_CACHEMOD
41747       || pPager->eState==PAGER_WRITER_DBMOD
41748  );
41749  assert( assert_pager_state(pPager) );
41750
41751  /* If an error has been previously detected, report the same error
41752  ** again. This should not happen, but the check provides robustness. */
41753  if( NEVER(pPager->errCode) )  return pPager->errCode;
41754
41755  /* Higher-level routines never call this function if database is not
41756  ** writable.  But check anyway, just for robustness. */
41757  if( NEVER(pPager->readOnly) ) return SQLITE_PERM;
41758
41759  CHECK_PAGE(pPg);
41760
41761  /* The journal file needs to be opened. Higher level routines have already
41762  ** obtained the necessary locks to begin the write-transaction, but the
41763  ** rollback journal might not yet be open. Open it now if this is the case.
41764  **
41765  ** This is done before calling sqlite3PcacheMakeDirty() on the page.
41766  ** Otherwise, if it were done after calling sqlite3PcacheMakeDirty(), then
41767  ** an error might occur and the pager would end up in WRITER_LOCKED state
41768  ** with pages marked as dirty in the cache.
41769  */
41770  if( pPager->eState==PAGER_WRITER_LOCKED ){
41771    rc = pager_open_journal(pPager);
41772    if( rc!=SQLITE_OK ) return rc;
41773  }
41774  assert( pPager->eState>=PAGER_WRITER_CACHEMOD );
41775  assert( assert_pager_state(pPager) );
41776
41777  /* Mark the page as dirty.  If the page has already been written
41778  ** to the journal then we can return right away.
41779  */
41780  sqlite3PcacheMakeDirty(pPg);
41781  if( pageInJournal(pPg) && !subjRequiresPage(pPg) ){
41782    assert( !pagerUseWal(pPager) );
41783  }else{
41784
41785    /* The transaction journal now exists and we have a RESERVED or an
41786    ** EXCLUSIVE lock on the main database file.  Write the current page to
41787    ** the transaction journal if it is not there already.
41788    */
41789    if( !pageInJournal(pPg) && !pagerUseWal(pPager) ){
41790      assert( pagerUseWal(pPager)==0 );
41791      if( pPg->pgno<=pPager->dbOrigSize && isOpen(pPager->jfd) ){
41792        u32 cksum;
41793        char *pData2;
41794        i64 iOff = pPager->journalOff;
41795
41796        /* We should never write to the journal file the page that
41797        ** contains the database locks.  The following assert verifies
41798        ** that we do not. */
41799        assert( pPg->pgno!=PAGER_MJ_PGNO(pPager) );
41800
41801        assert( pPager->journalHdr<=pPager->journalOff );
41802        CODEC2(pPager, pData, pPg->pgno, 7, return SQLITE_NOMEM, pData2);
41803        cksum = pager_cksum(pPager, (u8*)pData2);
41804
41805        /* Even if an IO or diskfull error occurs while journalling the
41806        ** page in the block above, set the need-sync flag for the page.
41807        ** Otherwise, when the transaction is rolled back, the logic in
41808        ** playback_one_page() will think that the page needs to be restored
41809        ** in the database file. And if an IO error occurs while doing so,
41810        ** then corruption may follow.
41811        */
41812        pPg->flags |= PGHDR_NEED_SYNC;
41813
41814        rc = write32bits(pPager->jfd, iOff, pPg->pgno);
41815        if( rc!=SQLITE_OK ) return rc;
41816        rc = sqlite3OsWrite(pPager->jfd, pData2, pPager->pageSize, iOff+4);
41817        if( rc!=SQLITE_OK ) return rc;
41818        rc = write32bits(pPager->jfd, iOff+pPager->pageSize+4, cksum);
41819        if( rc!=SQLITE_OK ) return rc;
41820
41821        IOTRACE(("JOUT %p %d %lld %d\n", pPager, pPg->pgno,
41822                 pPager->journalOff, pPager->pageSize));
41823        PAGER_INCR(sqlite3_pager_writej_count);
41824        PAGERTRACE(("JOURNAL %d page %d needSync=%d hash(%08x)\n",
41825             PAGERID(pPager), pPg->pgno,
41826             ((pPg->flags&PGHDR_NEED_SYNC)?1:0), pager_pagehash(pPg)));
41827
41828        pPager->journalOff += 8 + pPager->pageSize;
41829        pPager->nRec++;
41830        assert( pPager->pInJournal!=0 );
41831        rc = sqlite3BitvecSet(pPager->pInJournal, pPg->pgno);
41832        testcase( rc==SQLITE_NOMEM );
41833        assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
41834        rc |= addToSavepointBitvecs(pPager, pPg->pgno);
41835        if( rc!=SQLITE_OK ){
41836          assert( rc==SQLITE_NOMEM );
41837          return rc;
41838        }
41839      }else{
41840        if( pPager->eState!=PAGER_WRITER_DBMOD ){
41841          pPg->flags |= PGHDR_NEED_SYNC;
41842        }
41843        PAGERTRACE(("APPEND %d page %d needSync=%d\n",
41844                PAGERID(pPager), pPg->pgno,
41845               ((pPg->flags&PGHDR_NEED_SYNC)?1:0)));
41846      }
41847    }
41848
41849    /* If the statement journal is open and the page is not in it,
41850    ** then write the current page to the statement journal.  Note that
41851    ** the statement journal format differs from the standard journal format
41852    ** in that it omits the checksums and the header.
41853    */
41854    if( subjRequiresPage(pPg) ){
41855      rc = subjournalPage(pPg);
41856    }
41857  }
41858
41859  /* Update the database size and return.
41860  */
41861  if( pPager->dbSize<pPg->pgno ){
41862    pPager->dbSize = pPg->pgno;
41863  }
41864  return rc;
41865}
41866
41867/*
41868** Mark a data page as writeable. This routine must be called before
41869** making changes to a page. The caller must check the return value
41870** of this function and be careful not to change any page data unless
41871** this routine returns SQLITE_OK.
41872**
41873** The difference between this function and pager_write() is that this
41874** function also deals with the special case where 2 or more pages
41875** fit on a single disk sector. In this case all co-resident pages
41876** must have been written to the journal file before returning.
41877**
41878** If an error occurs, SQLITE_NOMEM or an IO error code is returned
41879** as appropriate. Otherwise, SQLITE_OK.
41880*/
41881SQLITE_PRIVATE int sqlite3PagerWrite(DbPage *pDbPage){
41882  int rc = SQLITE_OK;
41883
41884  PgHdr *pPg = pDbPage;
41885  Pager *pPager = pPg->pPager;
41886  Pgno nPagePerSector = (pPager->sectorSize/pPager->pageSize);
41887
41888  assert( pPager->eState>=PAGER_WRITER_LOCKED );
41889  assert( pPager->eState!=PAGER_ERROR );
41890  assert( assert_pager_state(pPager) );
41891
41892  if( nPagePerSector>1 ){
41893    Pgno nPageCount;          /* Total number of pages in database file */
41894    Pgno pg1;                 /* First page of the sector pPg is located on. */
41895    int nPage = 0;            /* Number of pages starting at pg1 to journal */
41896    int ii;                   /* Loop counter */
41897    int needSync = 0;         /* True if any page has PGHDR_NEED_SYNC */
41898
41899    /* Set the doNotSyncSpill flag to 1. This is because we cannot allow
41900    ** a journal header to be written between the pages journaled by
41901    ** this function.
41902    */
41903    assert( !MEMDB );
41904    assert( pPager->doNotSyncSpill==0 );
41905    pPager->doNotSyncSpill++;
41906
41907    /* This trick assumes that both the page-size and sector-size are
41908    ** an integer power of 2. It sets variable pg1 to the identifier
41909    ** of the first page of the sector pPg is located on.
41910    */
41911    pg1 = ((pPg->pgno-1) & ~(nPagePerSector-1)) + 1;
41912
41913    nPageCount = pPager->dbSize;
41914    if( pPg->pgno>nPageCount ){
41915      nPage = (pPg->pgno - pg1)+1;
41916    }else if( (pg1+nPagePerSector-1)>nPageCount ){
41917      nPage = nPageCount+1-pg1;
41918    }else{
41919      nPage = nPagePerSector;
41920    }
41921    assert(nPage>0);
41922    assert(pg1<=pPg->pgno);
41923    assert((pg1+nPage)>pPg->pgno);
41924
41925    for(ii=0; ii<nPage && rc==SQLITE_OK; ii++){
41926      Pgno pg = pg1+ii;
41927      PgHdr *pPage;
41928      if( pg==pPg->pgno || !sqlite3BitvecTest(pPager->pInJournal, pg) ){
41929        if( pg!=PAGER_MJ_PGNO(pPager) ){
41930          rc = sqlite3PagerGet(pPager, pg, &pPage);
41931          if( rc==SQLITE_OK ){
41932            rc = pager_write(pPage);
41933            if( pPage->flags&PGHDR_NEED_SYNC ){
41934              needSync = 1;
41935            }
41936            sqlite3PagerUnref(pPage);
41937          }
41938        }
41939      }else if( (pPage = pager_lookup(pPager, pg))!=0 ){
41940        if( pPage->flags&PGHDR_NEED_SYNC ){
41941          needSync = 1;
41942        }
41943        sqlite3PagerUnref(pPage);
41944      }
41945    }
41946
41947    /* If the PGHDR_NEED_SYNC flag is set for any of the nPage pages
41948    ** starting at pg1, then it needs to be set for all of them. Because
41949    ** writing to any of these nPage pages may damage the others, the
41950    ** journal file must contain sync()ed copies of all of them
41951    ** before any of them can be written out to the database file.
41952    */
41953    if( rc==SQLITE_OK && needSync ){
41954      assert( !MEMDB );
41955      for(ii=0; ii<nPage; ii++){
41956        PgHdr *pPage = pager_lookup(pPager, pg1+ii);
41957        if( pPage ){
41958          pPage->flags |= PGHDR_NEED_SYNC;
41959          sqlite3PagerUnref(pPage);
41960        }
41961      }
41962    }
41963
41964    assert( pPager->doNotSyncSpill==1 );
41965    pPager->doNotSyncSpill--;
41966  }else{
41967    rc = pager_write(pDbPage);
41968  }
41969  return rc;
41970}
41971
41972/*
41973** Return TRUE if the page given in the argument was previously passed
41974** to sqlite3PagerWrite().  In other words, return TRUE if it is ok
41975** to change the content of the page.
41976*/
41977#ifndef NDEBUG
41978SQLITE_PRIVATE int sqlite3PagerIswriteable(DbPage *pPg){
41979  return pPg->flags&PGHDR_DIRTY;
41980}
41981#endif
41982
41983/*
41984** A call to this routine tells the pager that it is not necessary to
41985** write the information on page pPg back to the disk, even though
41986** that page might be marked as dirty.  This happens, for example, when
41987** the page has been added as a leaf of the freelist and so its
41988** content no longer matters.
41989**
41990** The overlying software layer calls this routine when all of the data
41991** on the given page is unused. The pager marks the page as clean so
41992** that it does not get written to disk.
41993**
41994** Tests show that this optimization can quadruple the speed of large
41995** DELETE operations.
41996*/
41997SQLITE_PRIVATE void sqlite3PagerDontWrite(PgHdr *pPg){
41998  Pager *pPager = pPg->pPager;
41999  if( (pPg->flags&PGHDR_DIRTY) && pPager->nSavepoint==0 ){
42000    PAGERTRACE(("DONT_WRITE page %d of %d\n", pPg->pgno, PAGERID(pPager)));
42001    IOTRACE(("CLEAN %p %d\n", pPager, pPg->pgno))
42002    pPg->flags |= PGHDR_DONT_WRITE;
42003    pager_set_pagehash(pPg);
42004  }
42005}
42006
42007/*
42008** This routine is called to increment the value of the database file
42009** change-counter, stored as a 4-byte big-endian integer starting at
42010** byte offset 24 of the pager file.  The secondary change counter at
42011** 92 is also updated, as is the SQLite version number at offset 96.
42012**
42013** But this only happens if the pPager->changeCountDone flag is false.
42014** To avoid excess churning of page 1, the update only happens once.
42015** See also the pager_write_changecounter() routine that does an
42016** unconditional update of the change counters.
42017**
42018** If the isDirectMode flag is zero, then this is done by calling
42019** sqlite3PagerWrite() on page 1, then modifying the contents of the
42020** page data. In this case the file will be updated when the current
42021** transaction is committed.
42022**
42023** The isDirectMode flag may only be non-zero if the library was compiled
42024** with the SQLITE_ENABLE_ATOMIC_WRITE macro defined. In this case,
42025** if isDirect is non-zero, then the database file is updated directly
42026** by writing an updated version of page 1 using a call to the
42027** sqlite3OsWrite() function.
42028*/
42029static int pager_incr_changecounter(Pager *pPager, int isDirectMode){
42030  int rc = SQLITE_OK;
42031
42032  assert( pPager->eState==PAGER_WRITER_CACHEMOD
42033       || pPager->eState==PAGER_WRITER_DBMOD
42034  );
42035  assert( assert_pager_state(pPager) );
42036
42037  /* Declare and initialize constant integer 'isDirect'. If the
42038  ** atomic-write optimization is enabled in this build, then isDirect
42039  ** is initialized to the value passed as the isDirectMode parameter
42040  ** to this function. Otherwise, it is always set to zero.
42041  **
42042  ** The idea is that if the atomic-write optimization is not
42043  ** enabled at compile time, the compiler can omit the tests of
42044  ** 'isDirect' below, as well as the block enclosed in the
42045  ** "if( isDirect )" condition.
42046  */
42047#ifndef SQLITE_ENABLE_ATOMIC_WRITE
42048# define DIRECT_MODE 0
42049  assert( isDirectMode==0 );
42050  UNUSED_PARAMETER(isDirectMode);
42051#else
42052# define DIRECT_MODE isDirectMode
42053#endif
42054
42055  if( !pPager->changeCountDone && pPager->dbSize>0 ){
42056    PgHdr *pPgHdr;                /* Reference to page 1 */
42057
42058    assert( !pPager->tempFile && isOpen(pPager->fd) );
42059
42060    /* Open page 1 of the file for writing. */
42061    rc = sqlite3PagerGet(pPager, 1, &pPgHdr);
42062    assert( pPgHdr==0 || rc==SQLITE_OK );
42063
42064    /* If page one was fetched successfully, and this function is not
42065    ** operating in direct-mode, make page 1 writable.  When not in
42066    ** direct mode, page 1 is always held in cache and hence the PagerGet()
42067    ** above is always successful - hence the ALWAYS on rc==SQLITE_OK.
42068    */
42069    if( !DIRECT_MODE && ALWAYS(rc==SQLITE_OK) ){
42070      rc = sqlite3PagerWrite(pPgHdr);
42071    }
42072
42073    if( rc==SQLITE_OK ){
42074      /* Actually do the update of the change counter */
42075      pager_write_changecounter(pPgHdr);
42076
42077      /* If running in direct mode, write the contents of page 1 to the file. */
42078      if( DIRECT_MODE ){
42079        const void *zBuf;
42080        assert( pPager->dbFileSize>0 );
42081        CODEC2(pPager, pPgHdr->pData, 1, 6, rc=SQLITE_NOMEM, zBuf);
42082        if( rc==SQLITE_OK ){
42083          rc = sqlite3OsWrite(pPager->fd, zBuf, pPager->pageSize, 0);
42084        }
42085        if( rc==SQLITE_OK ){
42086          pPager->changeCountDone = 1;
42087        }
42088      }else{
42089        pPager->changeCountDone = 1;
42090      }
42091    }
42092
42093    /* Release the page reference. */
42094    sqlite3PagerUnref(pPgHdr);
42095  }
42096  return rc;
42097}
42098
42099/*
42100** Sync the database file to disk. This is a no-op for in-memory databases
42101** or pages with the Pager.noSync flag set.
42102**
42103** If successful, or if called on a pager for which it is a no-op, this
42104** function returns SQLITE_OK. Otherwise, an IO error code is returned.
42105*/
42106SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager){
42107  int rc = SQLITE_OK;
42108  if( !pPager->noSync ){
42109    assert( !MEMDB );
42110    rc = sqlite3OsSync(pPager->fd, pPager->syncFlags);
42111  }else if( isOpen(pPager->fd) ){
42112    assert( !MEMDB );
42113    sqlite3OsFileControl(pPager->fd, SQLITE_FCNTL_SYNC_OMITTED, (void *)&rc);
42114  }
42115  return rc;
42116}
42117
42118/*
42119** This function may only be called while a write-transaction is active in
42120** rollback. If the connection is in WAL mode, this call is a no-op.
42121** Otherwise, if the connection does not already have an EXCLUSIVE lock on
42122** the database file, an attempt is made to obtain one.
42123**
42124** If the EXCLUSIVE lock is already held or the attempt to obtain it is
42125** successful, or the connection is in WAL mode, SQLITE_OK is returned.
42126** Otherwise, either SQLITE_BUSY or an SQLITE_IOERR_XXX error code is
42127** returned.
42128*/
42129SQLITE_PRIVATE int sqlite3PagerExclusiveLock(Pager *pPager){
42130  int rc = SQLITE_OK;
42131  assert( pPager->eState==PAGER_WRITER_CACHEMOD
42132       || pPager->eState==PAGER_WRITER_DBMOD
42133       || pPager->eState==PAGER_WRITER_LOCKED
42134  );
42135  assert( assert_pager_state(pPager) );
42136  if( 0==pagerUseWal(pPager) ){
42137    rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);
42138  }
42139  return rc;
42140}
42141
42142/*
42143** Sync the database file for the pager pPager. zMaster points to the name
42144** of a master journal file that should be written into the individual
42145** journal file. zMaster may be NULL, which is interpreted as no master
42146** journal (a single database transaction).
42147**
42148** This routine ensures that:
42149**
42150**   * The database file change-counter is updated,
42151**   * the journal is synced (unless the atomic-write optimization is used),
42152**   * all dirty pages are written to the database file,
42153**   * the database file is truncated (if required), and
42154**   * the database file synced.
42155**
42156** The only thing that remains to commit the transaction is to finalize
42157** (delete, truncate or zero the first part of) the journal file (or
42158** delete the master journal file if specified).
42159**
42160** Note that if zMaster==NULL, this does not overwrite a previous value
42161** passed to an sqlite3PagerCommitPhaseOne() call.
42162**
42163** If the final parameter - noSync - is true, then the database file itself
42164** is not synced. The caller must call sqlite3PagerSync() directly to
42165** sync the database file before calling CommitPhaseTwo() to delete the
42166** journal file in this case.
42167*/
42168SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(
42169  Pager *pPager,                  /* Pager object */
42170  const char *zMaster,            /* If not NULL, the master journal name */
42171  int noSync                      /* True to omit the xSync on the db file */
42172){
42173  int rc = SQLITE_OK;             /* Return code */
42174
42175  assert( pPager->eState==PAGER_WRITER_LOCKED
42176       || pPager->eState==PAGER_WRITER_CACHEMOD
42177       || pPager->eState==PAGER_WRITER_DBMOD
42178       || pPager->eState==PAGER_ERROR
42179  );
42180  assert( assert_pager_state(pPager) );
42181
42182  /* If a prior error occurred, report that error again. */
42183  if( NEVER(pPager->errCode) ) return pPager->errCode;
42184
42185  PAGERTRACE(("DATABASE SYNC: File=%s zMaster=%s nSize=%d\n",
42186      pPager->zFilename, zMaster, pPager->dbSize));
42187
42188  /* If no database changes have been made, return early. */
42189  if( pPager->eState<PAGER_WRITER_CACHEMOD ) return SQLITE_OK;
42190
42191  if( MEMDB ){
42192    /* If this is an in-memory db, or no pages have been written to, or this
42193    ** function has already been called, it is mostly a no-op.  However, any
42194    ** backup in progress needs to be restarted.
42195    */
42196    sqlite3BackupRestart(pPager->pBackup);
42197  }else{
42198    if( pagerUseWal(pPager) ){
42199      PgHdr *pList = sqlite3PcacheDirtyList(pPager->pPCache);
42200      PgHdr *pPageOne = 0;
42201      if( pList==0 ){
42202        /* Must have at least one page for the WAL commit flag.
42203        ** Ticket [2d1a5c67dfc2363e44f29d9bbd57f] 2011-05-18 */
42204        rc = sqlite3PagerGet(pPager, 1, &pPageOne);
42205        pList = pPageOne;
42206        pList->pDirty = 0;
42207      }
42208      assert( pList!=0 || rc!=SQLITE_OK );
42209      if( pList ){
42210        rc = pagerWalFrames(pPager, pList, pPager->dbSize, 1,
42211            (pPager->fullSync ? pPager->syncFlags : 0)
42212        );
42213      }
42214      sqlite3PagerUnref(pPageOne);
42215      if( rc==SQLITE_OK ){
42216        sqlite3PcacheCleanAll(pPager->pPCache);
42217      }
42218    }else{
42219      /* The following block updates the change-counter. Exactly how it
42220      ** does this depends on whether or not the atomic-update optimization
42221      ** was enabled at compile time, and if this transaction meets the
42222      ** runtime criteria to use the operation:
42223      **
42224      **    * The file-system supports the atomic-write property for
42225      **      blocks of size page-size, and
42226      **    * This commit is not part of a multi-file transaction, and
42227      **    * Exactly one page has been modified and store in the journal file.
42228      **
42229      ** If the optimization was not enabled at compile time, then the
42230      ** pager_incr_changecounter() function is called to update the change
42231      ** counter in 'indirect-mode'. If the optimization is compiled in but
42232      ** is not applicable to this transaction, call sqlite3JournalCreate()
42233      ** to make sure the journal file has actually been created, then call
42234      ** pager_incr_changecounter() to update the change-counter in indirect
42235      ** mode.
42236      **
42237      ** Otherwise, if the optimization is both enabled and applicable,
42238      ** then call pager_incr_changecounter() to update the change-counter
42239      ** in 'direct' mode. In this case the journal file will never be
42240      ** created for this transaction.
42241      */
42242  #ifdef SQLITE_ENABLE_ATOMIC_WRITE
42243      PgHdr *pPg;
42244      assert( isOpen(pPager->jfd)
42245           || pPager->journalMode==PAGER_JOURNALMODE_OFF
42246           || pPager->journalMode==PAGER_JOURNALMODE_WAL
42247      );
42248      if( !zMaster && isOpen(pPager->jfd)
42249       && pPager->journalOff==jrnlBufferSize(pPager)
42250       && pPager->dbSize>=pPager->dbOrigSize
42251       && (0==(pPg = sqlite3PcacheDirtyList(pPager->pPCache)) || 0==pPg->pDirty)
42252      ){
42253        /* Update the db file change counter via the direct-write method. The
42254        ** following call will modify the in-memory representation of page 1
42255        ** to include the updated change counter and then write page 1
42256        ** directly to the database file. Because of the atomic-write
42257        ** property of the host file-system, this is safe.
42258        */
42259        rc = pager_incr_changecounter(pPager, 1);
42260      }else{
42261        rc = sqlite3JournalCreate(pPager->jfd);
42262        if( rc==SQLITE_OK ){
42263          rc = pager_incr_changecounter(pPager, 0);
42264        }
42265      }
42266  #else
42267      rc = pager_incr_changecounter(pPager, 0);
42268  #endif
42269      if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
42270
42271      /* If this transaction has made the database smaller, then all pages
42272      ** being discarded by the truncation must be written to the journal
42273      ** file. This can only happen in auto-vacuum mode.
42274      **
42275      ** Before reading the pages with page numbers larger than the
42276      ** current value of Pager.dbSize, set dbSize back to the value
42277      ** that it took at the start of the transaction. Otherwise, the
42278      ** calls to sqlite3PagerGet() return zeroed pages instead of
42279      ** reading data from the database file.
42280      */
42281  #ifndef SQLITE_OMIT_AUTOVACUUM
42282      if( pPager->dbSize<pPager->dbOrigSize
42283       && pPager->journalMode!=PAGER_JOURNALMODE_OFF
42284      ){
42285        Pgno i;                                   /* Iterator variable */
42286        const Pgno iSkip = PAGER_MJ_PGNO(pPager); /* Pending lock page */
42287        const Pgno dbSize = pPager->dbSize;       /* Database image size */
42288        pPager->dbSize = pPager->dbOrigSize;
42289        for( i=dbSize+1; i<=pPager->dbOrigSize; i++ ){
42290          if( !sqlite3BitvecTest(pPager->pInJournal, i) && i!=iSkip ){
42291            PgHdr *pPage;             /* Page to journal */
42292            rc = sqlite3PagerGet(pPager, i, &pPage);
42293            if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
42294            rc = sqlite3PagerWrite(pPage);
42295            sqlite3PagerUnref(pPage);
42296            if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
42297          }
42298        }
42299        pPager->dbSize = dbSize;
42300      }
42301  #endif
42302
42303      /* Write the master journal name into the journal file. If a master
42304      ** journal file name has already been written to the journal file,
42305      ** or if zMaster is NULL (no master journal), then this call is a no-op.
42306      */
42307      rc = writeMasterJournal(pPager, zMaster);
42308      if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
42309
42310      /* Sync the journal file and write all dirty pages to the database.
42311      ** If the atomic-update optimization is being used, this sync will not
42312      ** create the journal file or perform any real IO.
42313      **
42314      ** Because the change-counter page was just modified, unless the
42315      ** atomic-update optimization is used it is almost certain that the
42316      ** journal requires a sync here. However, in locking_mode=exclusive
42317      ** on a system under memory pressure it is just possible that this is
42318      ** not the case. In this case it is likely enough that the redundant
42319      ** xSync() call will be changed to a no-op by the OS anyhow.
42320      */
42321      rc = syncJournal(pPager, 0);
42322      if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
42323
42324      rc = pager_write_pagelist(pPager,sqlite3PcacheDirtyList(pPager->pPCache));
42325      if( rc!=SQLITE_OK ){
42326        assert( rc!=SQLITE_IOERR_BLOCKED );
42327        goto commit_phase_one_exit;
42328      }
42329      sqlite3PcacheCleanAll(pPager->pPCache);
42330
42331      /* If the file on disk is not the same size as the database image,
42332      ** then use pager_truncate to grow or shrink the file here.
42333      */
42334      if( pPager->dbSize!=pPager->dbFileSize ){
42335        Pgno nNew = pPager->dbSize - (pPager->dbSize==PAGER_MJ_PGNO(pPager));
42336        assert( pPager->eState==PAGER_WRITER_DBMOD );
42337        rc = pager_truncate(pPager, nNew);
42338        if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
42339      }
42340
42341      /* Finally, sync the database file. */
42342      if( !noSync ){
42343        rc = sqlite3PagerSync(pPager);
42344      }
42345      IOTRACE(("DBSYNC %p\n", pPager))
42346    }
42347  }
42348
42349commit_phase_one_exit:
42350  if( rc==SQLITE_OK && !pagerUseWal(pPager) ){
42351    pPager->eState = PAGER_WRITER_FINISHED;
42352  }
42353  return rc;
42354}
42355
42356
42357/*
42358** When this function is called, the database file has been completely
42359** updated to reflect the changes made by the current transaction and
42360** synced to disk. The journal file still exists in the file-system
42361** though, and if a failure occurs at this point it will eventually
42362** be used as a hot-journal and the current transaction rolled back.
42363**
42364** This function finalizes the journal file, either by deleting,
42365** truncating or partially zeroing it, so that it cannot be used
42366** for hot-journal rollback. Once this is done the transaction is
42367** irrevocably committed.
42368**
42369** If an error occurs, an IO error code is returned and the pager
42370** moves into the error state. Otherwise, SQLITE_OK is returned.
42371*/
42372SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager *pPager){
42373  int rc = SQLITE_OK;                  /* Return code */
42374
42375  /* This routine should not be called if a prior error has occurred.
42376  ** But if (due to a coding error elsewhere in the system) it does get
42377  ** called, just return the same error code without doing anything. */
42378  if( NEVER(pPager->errCode) ) return pPager->errCode;
42379
42380  assert( pPager->eState==PAGER_WRITER_LOCKED
42381       || pPager->eState==PAGER_WRITER_FINISHED
42382       || (pagerUseWal(pPager) && pPager->eState==PAGER_WRITER_CACHEMOD)
42383  );
42384  assert( assert_pager_state(pPager) );
42385
42386  /* An optimization. If the database was not actually modified during
42387  ** this transaction, the pager is running in exclusive-mode and is
42388  ** using persistent journals, then this function is a no-op.
42389  **
42390  ** The start of the journal file currently contains a single journal
42391  ** header with the nRec field set to 0. If such a journal is used as
42392  ** a hot-journal during hot-journal rollback, 0 changes will be made
42393  ** to the database file. So there is no need to zero the journal
42394  ** header. Since the pager is in exclusive mode, there is no need
42395  ** to drop any locks either.
42396  */
42397  if( pPager->eState==PAGER_WRITER_LOCKED
42398   && pPager->exclusiveMode
42399   && pPager->journalMode==PAGER_JOURNALMODE_PERSIST
42400  ){
42401    assert( pPager->journalOff==JOURNAL_HDR_SZ(pPager) || !pPager->journalOff );
42402    pPager->eState = PAGER_READER;
42403    return SQLITE_OK;
42404  }
42405
42406  PAGERTRACE(("COMMIT %d\n", PAGERID(pPager)));
42407  rc = pager_end_transaction(pPager, pPager->setMaster);
42408  return pager_error(pPager, rc);
42409}
42410
42411/*
42412** If a write transaction is open, then all changes made within the
42413** transaction are reverted and the current write-transaction is closed.
42414** The pager falls back to PAGER_READER state if successful, or PAGER_ERROR
42415** state if an error occurs.
42416**
42417** If the pager is already in PAGER_ERROR state when this function is called,
42418** it returns Pager.errCode immediately. No work is performed in this case.
42419**
42420** Otherwise, in rollback mode, this function performs two functions:
42421**
42422**   1) It rolls back the journal file, restoring all database file and
42423**      in-memory cache pages to the state they were in when the transaction
42424**      was opened, and
42425**
42426**   2) It finalizes the journal file, so that it is not used for hot
42427**      rollback at any point in the future.
42428**
42429** Finalization of the journal file (task 2) is only performed if the
42430** rollback is successful.
42431**
42432** In WAL mode, all cache-entries containing data modified within the
42433** current transaction are either expelled from the cache or reverted to
42434** their pre-transaction state by re-reading data from the database or
42435** WAL files. The WAL transaction is then closed.
42436*/
42437SQLITE_PRIVATE int sqlite3PagerRollback(Pager *pPager){
42438  int rc = SQLITE_OK;                  /* Return code */
42439  PAGERTRACE(("ROLLBACK %d\n", PAGERID(pPager)));
42440
42441  /* PagerRollback() is a no-op if called in READER or OPEN state. If
42442  ** the pager is already in the ERROR state, the rollback is not
42443  ** attempted here. Instead, the error code is returned to the caller.
42444  */
42445  assert( assert_pager_state(pPager) );
42446  if( pPager->eState==PAGER_ERROR ) return pPager->errCode;
42447  if( pPager->eState<=PAGER_READER ) return SQLITE_OK;
42448
42449  if( pagerUseWal(pPager) ){
42450    int rc2;
42451    rc = sqlite3PagerSavepoint(pPager, SAVEPOINT_ROLLBACK, -1);
42452    rc2 = pager_end_transaction(pPager, pPager->setMaster);
42453    if( rc==SQLITE_OK ) rc = rc2;
42454  }else if( !isOpen(pPager->jfd) || pPager->eState==PAGER_WRITER_LOCKED ){
42455    int eState = pPager->eState;
42456    rc = pager_end_transaction(pPager, 0);
42457    if( !MEMDB && eState>PAGER_WRITER_LOCKED ){
42458      /* This can happen using journal_mode=off. Move the pager to the error
42459      ** state to indicate that the contents of the cache may not be trusted.
42460      ** Any active readers will get SQLITE_ABORT.
42461      */
42462      pPager->errCode = SQLITE_ABORT;
42463      pPager->eState = PAGER_ERROR;
42464      return rc;
42465    }
42466  }else{
42467    rc = pager_playback(pPager, 0);
42468  }
42469
42470  assert( pPager->eState==PAGER_READER || rc!=SQLITE_OK );
42471  assert( rc==SQLITE_OK || rc==SQLITE_FULL || (rc&0xFF)==SQLITE_IOERR );
42472
42473  /* If an error occurs during a ROLLBACK, we can no longer trust the pager
42474  ** cache. So call pager_error() on the way out to make any error persistent.
42475  */
42476  return pager_error(pPager, rc);
42477}
42478
42479/*
42480** Return TRUE if the database file is opened read-only.  Return FALSE
42481** if the database is (in theory) writable.
42482*/
42483SQLITE_PRIVATE u8 sqlite3PagerIsreadonly(Pager *pPager){
42484  return pPager->readOnly;
42485}
42486
42487/*
42488** Return the number of references to the pager.
42489*/
42490SQLITE_PRIVATE int sqlite3PagerRefcount(Pager *pPager){
42491  return sqlite3PcacheRefCount(pPager->pPCache);
42492}
42493
42494/*
42495** Return the approximate number of bytes of memory currently
42496** used by the pager and its associated cache.
42497*/
42498SQLITE_PRIVATE int sqlite3PagerMemUsed(Pager *pPager){
42499  int perPageSize = pPager->pageSize + pPager->nExtra + sizeof(PgHdr)
42500                                     + 5*sizeof(void*);
42501  return perPageSize*sqlite3PcachePagecount(pPager->pPCache)
42502           + sqlite3MallocSize(pPager)
42503           + pPager->pageSize;
42504}
42505
42506/*
42507** Return the number of references to the specified page.
42508*/
42509SQLITE_PRIVATE int sqlite3PagerPageRefcount(DbPage *pPage){
42510  return sqlite3PcachePageRefcount(pPage);
42511}
42512
42513#ifdef SQLITE_TEST
42514/*
42515** This routine is used for testing and analysis only.
42516*/
42517SQLITE_PRIVATE int *sqlite3PagerStats(Pager *pPager){
42518  static int a[11];
42519  a[0] = sqlite3PcacheRefCount(pPager->pPCache);
42520  a[1] = sqlite3PcachePagecount(pPager->pPCache);
42521  a[2] = sqlite3PcacheGetCachesize(pPager->pPCache);
42522  a[3] = pPager->eState==PAGER_OPEN ? -1 : (int) pPager->dbSize;
42523  a[4] = pPager->eState;
42524  a[5] = pPager->errCode;
42525  a[6] = pPager->nHit;
42526  a[7] = pPager->nMiss;
42527  a[8] = 0;  /* Used to be pPager->nOvfl */
42528  a[9] = pPager->nRead;
42529  a[10] = pPager->nWrite;
42530  return a;
42531}
42532#endif
42533
42534/*
42535** Return true if this is an in-memory pager.
42536*/
42537SQLITE_PRIVATE int sqlite3PagerIsMemdb(Pager *pPager){
42538  return MEMDB;
42539}
42540
42541/*
42542** Check that there are at least nSavepoint savepoints open. If there are
42543** currently less than nSavepoints open, then open one or more savepoints
42544** to make up the difference. If the number of savepoints is already
42545** equal to nSavepoint, then this function is a no-op.
42546**
42547** If a memory allocation fails, SQLITE_NOMEM is returned. If an error
42548** occurs while opening the sub-journal file, then an IO error code is
42549** returned. Otherwise, SQLITE_OK.
42550*/
42551SQLITE_PRIVATE int sqlite3PagerOpenSavepoint(Pager *pPager, int nSavepoint){
42552  int rc = SQLITE_OK;                       /* Return code */
42553  int nCurrent = pPager->nSavepoint;        /* Current number of savepoints */
42554
42555  assert( pPager->eState>=PAGER_WRITER_LOCKED );
42556  assert( assert_pager_state(pPager) );
42557
42558  if( nSavepoint>nCurrent && pPager->useJournal ){
42559    int ii;                                 /* Iterator variable */
42560    PagerSavepoint *aNew;                   /* New Pager.aSavepoint array */
42561
42562    /* Grow the Pager.aSavepoint array using realloc(). Return SQLITE_NOMEM
42563    ** if the allocation fails. Otherwise, zero the new portion in case a
42564    ** malloc failure occurs while populating it in the for(...) loop below.
42565    */
42566    aNew = (PagerSavepoint *)sqlite3Realloc(
42567        pPager->aSavepoint, sizeof(PagerSavepoint)*nSavepoint
42568    );
42569    if( !aNew ){
42570      return SQLITE_NOMEM;
42571    }
42572    memset(&aNew[nCurrent], 0, (nSavepoint-nCurrent) * sizeof(PagerSavepoint));
42573    pPager->aSavepoint = aNew;
42574
42575    /* Populate the PagerSavepoint structures just allocated. */
42576    for(ii=nCurrent; ii<nSavepoint; ii++){
42577      aNew[ii].nOrig = pPager->dbSize;
42578      if( isOpen(pPager->jfd) && pPager->journalOff>0 ){
42579        aNew[ii].iOffset = pPager->journalOff;
42580      }else{
42581        aNew[ii].iOffset = JOURNAL_HDR_SZ(pPager);
42582      }
42583      aNew[ii].iSubRec = pPager->nSubRec;
42584      aNew[ii].pInSavepoint = sqlite3BitvecCreate(pPager->dbSize);
42585      if( !aNew[ii].pInSavepoint ){
42586        return SQLITE_NOMEM;
42587      }
42588      if( pagerUseWal(pPager) ){
42589        sqlite3WalSavepoint(pPager->pWal, aNew[ii].aWalData);
42590      }
42591      pPager->nSavepoint = ii+1;
42592    }
42593    assert( pPager->nSavepoint==nSavepoint );
42594    assertTruncateConstraint(pPager);
42595  }
42596
42597  return rc;
42598}
42599
42600/*
42601** This function is called to rollback or release (commit) a savepoint.
42602** The savepoint to release or rollback need not be the most recently
42603** created savepoint.
42604**
42605** Parameter op is always either SAVEPOINT_ROLLBACK or SAVEPOINT_RELEASE.
42606** If it is SAVEPOINT_RELEASE, then release and destroy the savepoint with
42607** index iSavepoint. If it is SAVEPOINT_ROLLBACK, then rollback all changes
42608** that have occurred since the specified savepoint was created.
42609**
42610** The savepoint to rollback or release is identified by parameter
42611** iSavepoint. A value of 0 means to operate on the outermost savepoint
42612** (the first created). A value of (Pager.nSavepoint-1) means operate
42613** on the most recently created savepoint. If iSavepoint is greater than
42614** (Pager.nSavepoint-1), then this function is a no-op.
42615**
42616** If a negative value is passed to this function, then the current
42617** transaction is rolled back. This is different to calling
42618** sqlite3PagerRollback() because this function does not terminate
42619** the transaction or unlock the database, it just restores the
42620** contents of the database to its original state.
42621**
42622** In any case, all savepoints with an index greater than iSavepoint
42623** are destroyed. If this is a release operation (op==SAVEPOINT_RELEASE),
42624** then savepoint iSavepoint is also destroyed.
42625**
42626** This function may return SQLITE_NOMEM if a memory allocation fails,
42627** or an IO error code if an IO error occurs while rolling back a
42628** savepoint. If no errors occur, SQLITE_OK is returned.
42629*/
42630SQLITE_PRIVATE int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint){
42631  int rc = pPager->errCode;       /* Return code */
42632
42633  assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );
42634  assert( iSavepoint>=0 || op==SAVEPOINT_ROLLBACK );
42635
42636  if( rc==SQLITE_OK && iSavepoint<pPager->nSavepoint ){
42637    int ii;            /* Iterator variable */
42638    int nNew;          /* Number of remaining savepoints after this op. */
42639
42640    /* Figure out how many savepoints will still be active after this
42641    ** operation. Store this value in nNew. Then free resources associated
42642    ** with any savepoints that are destroyed by this operation.
42643    */
42644    nNew = iSavepoint + (( op==SAVEPOINT_RELEASE ) ? 0 : 1);
42645    for(ii=nNew; ii<pPager->nSavepoint; ii++){
42646      sqlite3BitvecDestroy(pPager->aSavepoint[ii].pInSavepoint);
42647    }
42648    pPager->nSavepoint = nNew;
42649
42650    /* If this is a release of the outermost savepoint, truncate
42651    ** the sub-journal to zero bytes in size. */
42652    if( op==SAVEPOINT_RELEASE ){
42653      if( nNew==0 && isOpen(pPager->sjfd) ){
42654        /* Only truncate if it is an in-memory sub-journal. */
42655        if( sqlite3IsMemJournal(pPager->sjfd) ){
42656          rc = sqlite3OsTruncate(pPager->sjfd, 0);
42657          assert( rc==SQLITE_OK );
42658        }
42659        pPager->nSubRec = 0;
42660      }
42661    }
42662    /* Else this is a rollback operation, playback the specified savepoint.
42663    ** If this is a temp-file, it is possible that the journal file has
42664    ** not yet been opened. In this case there have been no changes to
42665    ** the database file, so the playback operation can be skipped.
42666    */
42667    else if( pagerUseWal(pPager) || isOpen(pPager->jfd) ){
42668      PagerSavepoint *pSavepoint = (nNew==0)?0:&pPager->aSavepoint[nNew-1];
42669      rc = pagerPlaybackSavepoint(pPager, pSavepoint);
42670      assert(rc!=SQLITE_DONE);
42671    }
42672  }
42673
42674  return rc;
42675}
42676
42677/*
42678** Return the full pathname of the database file.
42679*/
42680SQLITE_PRIVATE const char *sqlite3PagerFilename(Pager *pPager){
42681  return pPager->zFilename;
42682}
42683
42684/*
42685** Return the VFS structure for the pager.
42686*/
42687SQLITE_PRIVATE const sqlite3_vfs *sqlite3PagerVfs(Pager *pPager){
42688  return pPager->pVfs;
42689}
42690
42691/*
42692** Return the file handle for the database file associated
42693** with the pager.  This might return NULL if the file has
42694** not yet been opened.
42695*/
42696SQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager *pPager){
42697  return pPager->fd;
42698}
42699
42700/*
42701** Return the full pathname of the journal file.
42702*/
42703SQLITE_PRIVATE const char *sqlite3PagerJournalname(Pager *pPager){
42704  return pPager->zJournal;
42705}
42706
42707/*
42708** Return true if fsync() calls are disabled for this pager.  Return FALSE
42709** if fsync()s are executed normally.
42710*/
42711SQLITE_PRIVATE int sqlite3PagerNosync(Pager *pPager){
42712  return pPager->noSync;
42713}
42714
42715#ifdef SQLITE_HAS_CODEC
42716/*
42717** Set or retrieve the codec for this pager
42718*/
42719SQLITE_PRIVATE void sqlite3PagerSetCodec(
42720  Pager *pPager,
42721  void *(*xCodec)(void*,void*,Pgno,int),
42722  void (*xCodecSizeChng)(void*,int,int),
42723  void (*xCodecFree)(void*),
42724  void *pCodec
42725){
42726  if( pPager->xCodecFree ) pPager->xCodecFree(pPager->pCodec);
42727  pPager->xCodec = pPager->memDb ? 0 : xCodec;
42728  pPager->xCodecSizeChng = xCodecSizeChng;
42729  pPager->xCodecFree = xCodecFree;
42730  pPager->pCodec = pCodec;
42731  pagerReportSize(pPager);
42732}
42733SQLITE_PRIVATE void *sqlite3PagerGetCodec(Pager *pPager){
42734  return pPager->pCodec;
42735}
42736#endif
42737
42738#ifndef SQLITE_OMIT_AUTOVACUUM
42739/*
42740** Move the page pPg to location pgno in the file.
42741**
42742** There must be no references to the page previously located at
42743** pgno (which we call pPgOld) though that page is allowed to be
42744** in cache.  If the page previously located at pgno is not already
42745** in the rollback journal, it is not put there by by this routine.
42746**
42747** References to the page pPg remain valid. Updating any
42748** meta-data associated with pPg (i.e. data stored in the nExtra bytes
42749** allocated along with the page) is the responsibility of the caller.
42750**
42751** A transaction must be active when this routine is called. It used to be
42752** required that a statement transaction was not active, but this restriction
42753** has been removed (CREATE INDEX needs to move a page when a statement
42754** transaction is active).
42755**
42756** If the fourth argument, isCommit, is non-zero, then this page is being
42757** moved as part of a database reorganization just before the transaction
42758** is being committed. In this case, it is guaranteed that the database page
42759** pPg refers to will not be written to again within this transaction.
42760**
42761** This function may return SQLITE_NOMEM or an IO error code if an error
42762** occurs. Otherwise, it returns SQLITE_OK.
42763*/
42764SQLITE_PRIVATE int sqlite3PagerMovepage(Pager *pPager, DbPage *pPg, Pgno pgno, int isCommit){
42765  PgHdr *pPgOld;               /* The page being overwritten. */
42766  Pgno needSyncPgno = 0;       /* Old value of pPg->pgno, if sync is required */
42767  int rc;                      /* Return code */
42768  Pgno origPgno;               /* The original page number */
42769
42770  assert( pPg->nRef>0 );
42771  assert( pPager->eState==PAGER_WRITER_CACHEMOD
42772       || pPager->eState==PAGER_WRITER_DBMOD
42773  );
42774  assert( assert_pager_state(pPager) );
42775
42776  /* In order to be able to rollback, an in-memory database must journal
42777  ** the page we are moving from.
42778  */
42779  if( MEMDB ){
42780    rc = sqlite3PagerWrite(pPg);
42781    if( rc ) return rc;
42782  }
42783
42784  /* If the page being moved is dirty and has not been saved by the latest
42785  ** savepoint, then save the current contents of the page into the
42786  ** sub-journal now. This is required to handle the following scenario:
42787  **
42788  **   BEGIN;
42789  **     <journal page X, then modify it in memory>
42790  **     SAVEPOINT one;
42791  **       <Move page X to location Y>
42792  **     ROLLBACK TO one;
42793  **
42794  ** If page X were not written to the sub-journal here, it would not
42795  ** be possible to restore its contents when the "ROLLBACK TO one"
42796  ** statement were is processed.
42797  **
42798  ** subjournalPage() may need to allocate space to store pPg->pgno into
42799  ** one or more savepoint bitvecs. This is the reason this function
42800  ** may return SQLITE_NOMEM.
42801  */
42802  if( pPg->flags&PGHDR_DIRTY
42803   && subjRequiresPage(pPg)
42804   && SQLITE_OK!=(rc = subjournalPage(pPg))
42805  ){
42806    return rc;
42807  }
42808
42809  PAGERTRACE(("MOVE %d page %d (needSync=%d) moves to %d\n",
42810      PAGERID(pPager), pPg->pgno, (pPg->flags&PGHDR_NEED_SYNC)?1:0, pgno));
42811  IOTRACE(("MOVE %p %d %d\n", pPager, pPg->pgno, pgno))
42812
42813  /* If the journal needs to be sync()ed before page pPg->pgno can
42814  ** be written to, store pPg->pgno in local variable needSyncPgno.
42815  **
42816  ** If the isCommit flag is set, there is no need to remember that
42817  ** the journal needs to be sync()ed before database page pPg->pgno
42818  ** can be written to. The caller has already promised not to write to it.
42819  */
42820  if( (pPg->flags&PGHDR_NEED_SYNC) && !isCommit ){
42821    needSyncPgno = pPg->pgno;
42822    assert( pageInJournal(pPg) || pPg->pgno>pPager->dbOrigSize );
42823    assert( pPg->flags&PGHDR_DIRTY );
42824  }
42825
42826  /* If the cache contains a page with page-number pgno, remove it
42827  ** from its hash chain. Also, if the PGHDR_NEED_SYNC flag was set for
42828  ** page pgno before the 'move' operation, it needs to be retained
42829  ** for the page moved there.
42830  */
42831  pPg->flags &= ~PGHDR_NEED_SYNC;
42832  pPgOld = pager_lookup(pPager, pgno);
42833  assert( !pPgOld || pPgOld->nRef==1 );
42834  if( pPgOld ){
42835    pPg->flags |= (pPgOld->flags&PGHDR_NEED_SYNC);
42836    if( MEMDB ){
42837      /* Do not discard pages from an in-memory database since we might
42838      ** need to rollback later.  Just move the page out of the way. */
42839      sqlite3PcacheMove(pPgOld, pPager->dbSize+1);
42840    }else{
42841      sqlite3PcacheDrop(pPgOld);
42842    }
42843  }
42844
42845  origPgno = pPg->pgno;
42846  sqlite3PcacheMove(pPg, pgno);
42847  sqlite3PcacheMakeDirty(pPg);
42848
42849  /* For an in-memory database, make sure the original page continues
42850  ** to exist, in case the transaction needs to roll back.  Use pPgOld
42851  ** as the original page since it has already been allocated.
42852  */
42853  if( MEMDB ){
42854    assert( pPgOld );
42855    sqlite3PcacheMove(pPgOld, origPgno);
42856    sqlite3PagerUnref(pPgOld);
42857  }
42858
42859  if( needSyncPgno ){
42860    /* If needSyncPgno is non-zero, then the journal file needs to be
42861    ** sync()ed before any data is written to database file page needSyncPgno.
42862    ** Currently, no such page exists in the page-cache and the
42863    ** "is journaled" bitvec flag has been set. This needs to be remedied by
42864    ** loading the page into the pager-cache and setting the PGHDR_NEED_SYNC
42865    ** flag.
42866    **
42867    ** If the attempt to load the page into the page-cache fails, (due
42868    ** to a malloc() or IO failure), clear the bit in the pInJournal[]
42869    ** array. Otherwise, if the page is loaded and written again in
42870    ** this transaction, it may be written to the database file before
42871    ** it is synced into the journal file. This way, it may end up in
42872    ** the journal file twice, but that is not a problem.
42873    */
42874    PgHdr *pPgHdr;
42875    rc = sqlite3PagerGet(pPager, needSyncPgno, &pPgHdr);
42876    if( rc!=SQLITE_OK ){
42877      if( needSyncPgno<=pPager->dbOrigSize ){
42878        assert( pPager->pTmpSpace!=0 );
42879        sqlite3BitvecClear(pPager->pInJournal, needSyncPgno, pPager->pTmpSpace);
42880      }
42881      return rc;
42882    }
42883    pPgHdr->flags |= PGHDR_NEED_SYNC;
42884    sqlite3PcacheMakeDirty(pPgHdr);
42885    sqlite3PagerUnref(pPgHdr);
42886  }
42887
42888  return SQLITE_OK;
42889}
42890#endif
42891
42892/*
42893** Return a pointer to the data for the specified page.
42894*/
42895SQLITE_PRIVATE void *sqlite3PagerGetData(DbPage *pPg){
42896  assert( pPg->nRef>0 || pPg->pPager->memDb );
42897  return pPg->pData;
42898}
42899
42900/*
42901** Return a pointer to the Pager.nExtra bytes of "extra" space
42902** allocated along with the specified page.
42903*/
42904SQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *pPg){
42905  return pPg->pExtra;
42906}
42907
42908/*
42909** Get/set the locking-mode for this pager. Parameter eMode must be one
42910** of PAGER_LOCKINGMODE_QUERY, PAGER_LOCKINGMODE_NORMAL or
42911** PAGER_LOCKINGMODE_EXCLUSIVE. If the parameter is not _QUERY, then
42912** the locking-mode is set to the value specified.
42913**
42914** The returned value is either PAGER_LOCKINGMODE_NORMAL or
42915** PAGER_LOCKINGMODE_EXCLUSIVE, indicating the current (possibly updated)
42916** locking-mode.
42917*/
42918SQLITE_PRIVATE int sqlite3PagerLockingMode(Pager *pPager, int eMode){
42919  assert( eMode==PAGER_LOCKINGMODE_QUERY
42920            || eMode==PAGER_LOCKINGMODE_NORMAL
42921            || eMode==PAGER_LOCKINGMODE_EXCLUSIVE );
42922  assert( PAGER_LOCKINGMODE_QUERY<0 );
42923  assert( PAGER_LOCKINGMODE_NORMAL>=0 && PAGER_LOCKINGMODE_EXCLUSIVE>=0 );
42924  assert( pPager->exclusiveMode || 0==sqlite3WalHeapMemory(pPager->pWal) );
42925  if( eMode>=0 && !pPager->tempFile && !sqlite3WalHeapMemory(pPager->pWal) ){
42926    pPager->exclusiveMode = (u8)eMode;
42927  }
42928  return (int)pPager->exclusiveMode;
42929}
42930
42931/*
42932** Set the journal-mode for this pager. Parameter eMode must be one of:
42933**
42934**    PAGER_JOURNALMODE_DELETE
42935**    PAGER_JOURNALMODE_TRUNCATE
42936**    PAGER_JOURNALMODE_PERSIST
42937**    PAGER_JOURNALMODE_OFF
42938**    PAGER_JOURNALMODE_MEMORY
42939**    PAGER_JOURNALMODE_WAL
42940**
42941** The journalmode is set to the value specified if the change is allowed.
42942** The change may be disallowed for the following reasons:
42943**
42944**   *  An in-memory database can only have its journal_mode set to _OFF
42945**      or _MEMORY.
42946**
42947**   *  Temporary databases cannot have _WAL journalmode.
42948**
42949** The returned indicate the current (possibly updated) journal-mode.
42950*/
42951SQLITE_PRIVATE int sqlite3PagerSetJournalMode(Pager *pPager, int eMode){
42952  u8 eOld = pPager->journalMode;    /* Prior journalmode */
42953
42954#ifdef SQLITE_DEBUG
42955  /* The print_pager_state() routine is intended to be used by the debugger
42956  ** only.  We invoke it once here to suppress a compiler warning. */
42957  print_pager_state(pPager);
42958#endif
42959
42960
42961  /* The eMode parameter is always valid */
42962  assert(      eMode==PAGER_JOURNALMODE_DELETE
42963            || eMode==PAGER_JOURNALMODE_TRUNCATE
42964            || eMode==PAGER_JOURNALMODE_PERSIST
42965            || eMode==PAGER_JOURNALMODE_OFF
42966            || eMode==PAGER_JOURNALMODE_WAL
42967            || eMode==PAGER_JOURNALMODE_MEMORY );
42968
42969  /* This routine is only called from the OP_JournalMode opcode, and
42970  ** the logic there will never allow a temporary file to be changed
42971  ** to WAL mode.
42972  */
42973  assert( pPager->tempFile==0 || eMode!=PAGER_JOURNALMODE_WAL );
42974
42975  /* Do allow the journalmode of an in-memory database to be set to
42976  ** anything other than MEMORY or OFF
42977  */
42978  if( MEMDB ){
42979    assert( eOld==PAGER_JOURNALMODE_MEMORY || eOld==PAGER_JOURNALMODE_OFF );
42980    if( eMode!=PAGER_JOURNALMODE_MEMORY && eMode!=PAGER_JOURNALMODE_OFF ){
42981      eMode = eOld;
42982    }
42983  }
42984
42985  if( eMode!=eOld ){
42986
42987    /* Change the journal mode. */
42988    assert( pPager->eState!=PAGER_ERROR );
42989    pPager->journalMode = (u8)eMode;
42990
42991    /* When transistioning from TRUNCATE or PERSIST to any other journal
42992    ** mode except WAL, unless the pager is in locking_mode=exclusive mode,
42993    ** delete the journal file.
42994    */
42995    assert( (PAGER_JOURNALMODE_TRUNCATE & 5)==1 );
42996    assert( (PAGER_JOURNALMODE_PERSIST & 5)==1 );
42997    assert( (PAGER_JOURNALMODE_DELETE & 5)==0 );
42998    assert( (PAGER_JOURNALMODE_MEMORY & 5)==4 );
42999    assert( (PAGER_JOURNALMODE_OFF & 5)==0 );
43000    assert( (PAGER_JOURNALMODE_WAL & 5)==5 );
43001
43002    assert( isOpen(pPager->fd) || pPager->exclusiveMode );
43003    if( !pPager->exclusiveMode && (eOld & 5)==1 && (eMode & 1)==0 ){
43004
43005      /* In this case we would like to delete the journal file. If it is
43006      ** not possible, then that is not a problem. Deleting the journal file
43007      ** here is an optimization only.
43008      **
43009      ** Before deleting the journal file, obtain a RESERVED lock on the
43010      ** database file. This ensures that the journal file is not deleted
43011      ** while it is in use by some other client.
43012      */
43013      sqlite3OsClose(pPager->jfd);
43014      if( pPager->eLock>=RESERVED_LOCK ){
43015        sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
43016      }else{
43017        int rc = SQLITE_OK;
43018        int state = pPager->eState;
43019        assert( state==PAGER_OPEN || state==PAGER_READER );
43020        if( state==PAGER_OPEN ){
43021          rc = sqlite3PagerSharedLock(pPager);
43022        }
43023        if( pPager->eState==PAGER_READER ){
43024          assert( rc==SQLITE_OK );
43025          rc = pagerLockDb(pPager, RESERVED_LOCK);
43026        }
43027        if( rc==SQLITE_OK ){
43028          sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
43029        }
43030        if( rc==SQLITE_OK && state==PAGER_READER ){
43031          pagerUnlockDb(pPager, SHARED_LOCK);
43032        }else if( state==PAGER_OPEN ){
43033          pager_unlock(pPager);
43034        }
43035        assert( state==pPager->eState );
43036      }
43037    }
43038  }
43039
43040  /* Return the new journal mode */
43041  return (int)pPager->journalMode;
43042}
43043
43044/*
43045** Return the current journal mode.
43046*/
43047SQLITE_PRIVATE int sqlite3PagerGetJournalMode(Pager *pPager){
43048  return (int)pPager->journalMode;
43049}
43050
43051/*
43052** Return TRUE if the pager is in a state where it is OK to change the
43053** journalmode.  Journalmode changes can only happen when the database
43054** is unmodified.
43055*/
43056SQLITE_PRIVATE int sqlite3PagerOkToChangeJournalMode(Pager *pPager){
43057  assert( assert_pager_state(pPager) );
43058  if( pPager->eState>=PAGER_WRITER_CACHEMOD ) return 0;
43059  if( NEVER(isOpen(pPager->jfd) && pPager->journalOff>0) ) return 0;
43060  return 1;
43061}
43062
43063/*
43064** Get/set the size-limit used for persistent journal files.
43065**
43066** Setting the size limit to -1 means no limit is enforced.
43067** An attempt to set a limit smaller than -1 is a no-op.
43068*/
43069SQLITE_PRIVATE i64 sqlite3PagerJournalSizeLimit(Pager *pPager, i64 iLimit){
43070  if( iLimit>=-1 ){
43071    pPager->journalSizeLimit = iLimit;
43072  }
43073  return pPager->journalSizeLimit;
43074}
43075
43076/*
43077** Return a pointer to the pPager->pBackup variable. The backup module
43078** in backup.c maintains the content of this variable. This module
43079** uses it opaquely as an argument to sqlite3BackupRestart() and
43080** sqlite3BackupUpdate() only.
43081*/
43082SQLITE_PRIVATE sqlite3_backup **sqlite3PagerBackupPtr(Pager *pPager){
43083  return &pPager->pBackup;
43084}
43085
43086#ifndef SQLITE_OMIT_WAL
43087/*
43088** This function is called when the user invokes "PRAGMA wal_checkpoint",
43089** "PRAGMA wal_blocking_checkpoint" or calls the sqlite3_wal_checkpoint()
43090** or wal_blocking_checkpoint() API functions.
43091**
43092** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
43093*/
43094SQLITE_PRIVATE int sqlite3PagerCheckpoint(Pager *pPager, int eMode, int *pnLog, int *pnCkpt){
43095  int rc = SQLITE_OK;
43096  if( pPager->pWal ){
43097    rc = sqlite3WalCheckpoint(pPager->pWal, eMode,
43098        pPager->xBusyHandler, pPager->pBusyHandlerArg,
43099        pPager->ckptSyncFlags, pPager->pageSize, (u8 *)pPager->pTmpSpace,
43100        pnLog, pnCkpt
43101    );
43102  }
43103  return rc;
43104}
43105
43106SQLITE_PRIVATE int sqlite3PagerWalCallback(Pager *pPager){
43107  return sqlite3WalCallback(pPager->pWal);
43108}
43109
43110/*
43111** Return true if the underlying VFS for the given pager supports the
43112** primitives necessary for write-ahead logging.
43113*/
43114SQLITE_PRIVATE int sqlite3PagerWalSupported(Pager *pPager){
43115  const sqlite3_io_methods *pMethods = pPager->fd->pMethods;
43116  return pPager->exclusiveMode || (pMethods->iVersion>=2 && pMethods->xShmMap);
43117}
43118
43119/*
43120** Attempt to take an exclusive lock on the database file. If a PENDING lock
43121** is obtained instead, immediately release it.
43122*/
43123static int pagerExclusiveLock(Pager *pPager){
43124  int rc;                         /* Return code */
43125
43126  assert( pPager->eLock==SHARED_LOCK || pPager->eLock==EXCLUSIVE_LOCK );
43127  rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
43128  if( rc!=SQLITE_OK ){
43129    /* If the attempt to grab the exclusive lock failed, release the
43130    ** pending lock that may have been obtained instead.  */
43131    pagerUnlockDb(pPager, SHARED_LOCK);
43132  }
43133
43134  return rc;
43135}
43136
43137/*
43138** Call sqlite3WalOpen() to open the WAL handle. If the pager is in
43139** exclusive-locking mode when this function is called, take an EXCLUSIVE
43140** lock on the database file and use heap-memory to store the wal-index
43141** in. Otherwise, use the normal shared-memory.
43142*/
43143static int pagerOpenWal(Pager *pPager){
43144  int rc = SQLITE_OK;
43145
43146  assert( pPager->pWal==0 && pPager->tempFile==0 );
43147  assert( pPager->eLock==SHARED_LOCK || pPager->eLock==EXCLUSIVE_LOCK || pPager->noReadlock);
43148
43149  /* If the pager is already in exclusive-mode, the WAL module will use
43150  ** heap-memory for the wal-index instead of the VFS shared-memory
43151  ** implementation. Take the exclusive lock now, before opening the WAL
43152  ** file, to make sure this is safe.
43153  */
43154  if( pPager->exclusiveMode ){
43155    rc = pagerExclusiveLock(pPager);
43156  }
43157
43158  /* Open the connection to the log file. If this operation fails,
43159  ** (e.g. due to malloc() failure), return an error code.
43160  */
43161  if( rc==SQLITE_OK ){
43162    rc = sqlite3WalOpen(pPager->pVfs,
43163        pPager->fd, pPager->zWal, pPager->exclusiveMode, &pPager->pWal
43164    );
43165  }
43166
43167  return rc;
43168}
43169
43170
43171/*
43172** The caller must be holding a SHARED lock on the database file to call
43173** this function.
43174**
43175** If the pager passed as the first argument is open on a real database
43176** file (not a temp file or an in-memory database), and the WAL file
43177** is not already open, make an attempt to open it now. If successful,
43178** return SQLITE_OK. If an error occurs or the VFS used by the pager does
43179** not support the xShmXXX() methods, return an error code. *pbOpen is
43180** not modified in either case.
43181**
43182** If the pager is open on a temp-file (or in-memory database), or if
43183** the WAL file is already open, set *pbOpen to 1 and return SQLITE_OK
43184** without doing anything.
43185*/
43186SQLITE_PRIVATE int sqlite3PagerOpenWal(
43187  Pager *pPager,                  /* Pager object */
43188  int *pbOpen                     /* OUT: Set to true if call is a no-op */
43189){
43190  int rc = SQLITE_OK;             /* Return code */
43191
43192  assert( assert_pager_state(pPager) );
43193  assert( pPager->eState==PAGER_OPEN   || pbOpen );
43194  assert( pPager->eState==PAGER_READER || !pbOpen );
43195  assert( pbOpen==0 || *pbOpen==0 );
43196  assert( pbOpen!=0 || (!pPager->tempFile && !pPager->pWal) );
43197
43198  if( !pPager->tempFile && !pPager->pWal ){
43199    if( !sqlite3PagerWalSupported(pPager) ) return SQLITE_CANTOPEN;
43200
43201    /* Close any rollback journal previously open */
43202    sqlite3OsClose(pPager->jfd);
43203
43204    rc = pagerOpenWal(pPager);
43205    if( rc==SQLITE_OK ){
43206      pPager->journalMode = PAGER_JOURNALMODE_WAL;
43207      pPager->eState = PAGER_OPEN;
43208    }
43209  }else{
43210    *pbOpen = 1;
43211  }
43212
43213  return rc;
43214}
43215
43216/*
43217** This function is called to close the connection to the log file prior
43218** to switching from WAL to rollback mode.
43219**
43220** Before closing the log file, this function attempts to take an
43221** EXCLUSIVE lock on the database file. If this cannot be obtained, an
43222** error (SQLITE_BUSY) is returned and the log connection is not closed.
43223** If successful, the EXCLUSIVE lock is not released before returning.
43224*/
43225SQLITE_PRIVATE int sqlite3PagerCloseWal(Pager *pPager){
43226  int rc = SQLITE_OK;
43227
43228  assert( pPager->journalMode==PAGER_JOURNALMODE_WAL );
43229
43230  /* If the log file is not already open, but does exist in the file-system,
43231  ** it may need to be checkpointed before the connection can switch to
43232  ** rollback mode. Open it now so this can happen.
43233  */
43234  if( !pPager->pWal ){
43235    int logexists = 0;
43236    rc = pagerLockDb(pPager, SHARED_LOCK);
43237    if( rc==SQLITE_OK ){
43238      rc = sqlite3OsAccess(
43239          pPager->pVfs, pPager->zWal, SQLITE_ACCESS_EXISTS, &logexists
43240      );
43241    }
43242    if( rc==SQLITE_OK && logexists ){
43243      rc = pagerOpenWal(pPager);
43244    }
43245  }
43246
43247  /* Checkpoint and close the log. Because an EXCLUSIVE lock is held on
43248  ** the database file, the log and log-summary files will be deleted.
43249  */
43250  if( rc==SQLITE_OK && pPager->pWal ){
43251    rc = pagerExclusiveLock(pPager);
43252    if( rc==SQLITE_OK ){
43253      rc = sqlite3WalClose(pPager->pWal, pPager->ckptSyncFlags,
43254                           pPager->pageSize, (u8*)pPager->pTmpSpace);
43255      pPager->pWal = 0;
43256    }
43257  }
43258  return rc;
43259}
43260
43261#ifdef SQLITE_HAS_CODEC
43262/*
43263** This function is called by the wal module when writing page content
43264** into the log file.
43265**
43266** This function returns a pointer to a buffer containing the encrypted
43267** page content. If a malloc fails, this function may return NULL.
43268*/
43269SQLITE_PRIVATE void *sqlite3PagerCodec(PgHdr *pPg){
43270  void *aData = 0;
43271  CODEC2(pPg->pPager, pPg->pData, pPg->pgno, 6, return 0, aData);
43272  return aData;
43273}
43274#endif /* SQLITE_HAS_CODEC */
43275
43276#endif /* !SQLITE_OMIT_WAL */
43277
43278#endif /* SQLITE_OMIT_DISKIO */
43279
43280/************** End of pager.c ***********************************************/
43281/************** Begin file wal.c *********************************************/
43282/*
43283** 2010 February 1
43284**
43285** The author disclaims copyright to this source code.  In place of
43286** a legal notice, here is a blessing:
43287**
43288**    May you do good and not evil.
43289**    May you find forgiveness for yourself and forgive others.
43290**    May you share freely, never taking more than you give.
43291**
43292*************************************************************************
43293**
43294** This file contains the implementation of a write-ahead log (WAL) used in
43295** "journal_mode=WAL" mode.
43296**
43297** WRITE-AHEAD LOG (WAL) FILE FORMAT
43298**
43299** A WAL file consists of a header followed by zero or more "frames".
43300** Each frame records the revised content of a single page from the
43301** database file.  All changes to the database are recorded by writing
43302** frames into the WAL.  Transactions commit when a frame is written that
43303** contains a commit marker.  A single WAL can and usually does record
43304** multiple transactions.  Periodically, the content of the WAL is
43305** transferred back into the database file in an operation called a
43306** "checkpoint".
43307**
43308** A single WAL file can be used multiple times.  In other words, the
43309** WAL can fill up with frames and then be checkpointed and then new
43310** frames can overwrite the old ones.  A WAL always grows from beginning
43311** toward the end.  Checksums and counters attached to each frame are
43312** used to determine which frames within the WAL are valid and which
43313** are leftovers from prior checkpoints.
43314**
43315** The WAL header is 32 bytes in size and consists of the following eight
43316** big-endian 32-bit unsigned integer values:
43317**
43318**     0: Magic number.  0x377f0682 or 0x377f0683
43319**     4: File format version.  Currently 3007000
43320**     8: Database page size.  Example: 1024
43321**    12: Checkpoint sequence number
43322**    16: Salt-1, random integer incremented with each checkpoint
43323**    20: Salt-2, a different random integer changing with each ckpt
43324**    24: Checksum-1 (first part of checksum for first 24 bytes of header).
43325**    28: Checksum-2 (second part of checksum for first 24 bytes of header).
43326**
43327** Immediately following the wal-header are zero or more frames. Each
43328** frame consists of a 24-byte frame-header followed by a <page-size> bytes
43329** of page data. The frame-header is six big-endian 32-bit unsigned
43330** integer values, as follows:
43331**
43332**     0: Page number.
43333**     4: For commit records, the size of the database image in pages
43334**        after the commit. For all other records, zero.
43335**     8: Salt-1 (copied from the header)
43336**    12: Salt-2 (copied from the header)
43337**    16: Checksum-1.
43338**    20: Checksum-2.
43339**
43340** A frame is considered valid if and only if the following conditions are
43341** true:
43342**
43343**    (1) The salt-1 and salt-2 values in the frame-header match
43344**        salt values in the wal-header
43345**
43346**    (2) The checksum values in the final 8 bytes of the frame-header
43347**        exactly match the checksum computed consecutively on the
43348**        WAL header and the first 8 bytes and the content of all frames
43349**        up to and including the current frame.
43350**
43351** The checksum is computed using 32-bit big-endian integers if the
43352** magic number in the first 4 bytes of the WAL is 0x377f0683 and it
43353** is computed using little-endian if the magic number is 0x377f0682.
43354** The checksum values are always stored in the frame header in a
43355** big-endian format regardless of which byte order is used to compute
43356** the checksum.  The checksum is computed by interpreting the input as
43357** an even number of unsigned 32-bit integers: x[0] through x[N].  The
43358** algorithm used for the checksum is as follows:
43359**
43360**   for i from 0 to n-1 step 2:
43361**     s0 += x[i] + s1;
43362**     s1 += x[i+1] + s0;
43363**   endfor
43364**
43365** Note that s0 and s1 are both weighted checksums using fibonacci weights
43366** in reverse order (the largest fibonacci weight occurs on the first element
43367** of the sequence being summed.)  The s1 value spans all 32-bit
43368** terms of the sequence whereas s0 omits the final term.
43369**
43370** On a checkpoint, the WAL is first VFS.xSync-ed, then valid content of the
43371** WAL is transferred into the database, then the database is VFS.xSync-ed.
43372** The VFS.xSync operations serve as write barriers - all writes launched
43373** before the xSync must complete before any write that launches after the
43374** xSync begins.
43375**
43376** After each checkpoint, the salt-1 value is incremented and the salt-2
43377** value is randomized.  This prevents old and new frames in the WAL from
43378** being considered valid at the same time and being checkpointing together
43379** following a crash.
43380**
43381** READER ALGORITHM
43382**
43383** To read a page from the database (call it page number P), a reader
43384** first checks the WAL to see if it contains page P.  If so, then the
43385** last valid instance of page P that is a followed by a commit frame
43386** or is a commit frame itself becomes the value read.  If the WAL
43387** contains no copies of page P that are valid and which are a commit
43388** frame or are followed by a commit frame, then page P is read from
43389** the database file.
43390**
43391** To start a read transaction, the reader records the index of the last
43392** valid frame in the WAL.  The reader uses this recorded "mxFrame" value
43393** for all subsequent read operations.  New transactions can be appended
43394** to the WAL, but as long as the reader uses its original mxFrame value
43395** and ignores the newly appended content, it will see a consistent snapshot
43396** of the database from a single point in time.  This technique allows
43397** multiple concurrent readers to view different versions of the database
43398** content simultaneously.
43399**
43400** The reader algorithm in the previous paragraphs works correctly, but
43401** because frames for page P can appear anywhere within the WAL, the
43402** reader has to scan the entire WAL looking for page P frames.  If the
43403** WAL is large (multiple megabytes is typical) that scan can be slow,
43404** and read performance suffers.  To overcome this problem, a separate
43405** data structure called the wal-index is maintained to expedite the
43406** search for frames of a particular page.
43407**
43408** WAL-INDEX FORMAT
43409**
43410** Conceptually, the wal-index is shared memory, though VFS implementations
43411** might choose to implement the wal-index using a mmapped file.  Because
43412** the wal-index is shared memory, SQLite does not support journal_mode=WAL
43413** on a network filesystem.  All users of the database must be able to
43414** share memory.
43415**
43416** The wal-index is transient.  After a crash, the wal-index can (and should
43417** be) reconstructed from the original WAL file.  In fact, the VFS is required
43418** to either truncate or zero the header of the wal-index when the last
43419** connection to it closes.  Because the wal-index is transient, it can
43420** use an architecture-specific format; it does not have to be cross-platform.
43421** Hence, unlike the database and WAL file formats which store all values
43422** as big endian, the wal-index can store multi-byte values in the native
43423** byte order of the host computer.
43424**
43425** The purpose of the wal-index is to answer this question quickly:  Given
43426** a page number P, return the index of the last frame for page P in the WAL,
43427** or return NULL if there are no frames for page P in the WAL.
43428**
43429** The wal-index consists of a header region, followed by an one or
43430** more index blocks.
43431**
43432** The wal-index header contains the total number of frames within the WAL
43433** in the the mxFrame field.
43434**
43435** Each index block except for the first contains information on
43436** HASHTABLE_NPAGE frames. The first index block contains information on
43437** HASHTABLE_NPAGE_ONE frames. The values of HASHTABLE_NPAGE_ONE and
43438** HASHTABLE_NPAGE are selected so that together the wal-index header and
43439** first index block are the same size as all other index blocks in the
43440** wal-index.
43441**
43442** Each index block contains two sections, a page-mapping that contains the
43443** database page number associated with each wal frame, and a hash-table
43444** that allows readers to query an index block for a specific page number.
43445** The page-mapping is an array of HASHTABLE_NPAGE (or HASHTABLE_NPAGE_ONE
43446** for the first index block) 32-bit page numbers. The first entry in the
43447** first index-block contains the database page number corresponding to the
43448** first frame in the WAL file. The first entry in the second index block
43449** in the WAL file corresponds to the (HASHTABLE_NPAGE_ONE+1)th frame in
43450** the log, and so on.
43451**
43452** The last index block in a wal-index usually contains less than the full
43453** complement of HASHTABLE_NPAGE (or HASHTABLE_NPAGE_ONE) page-numbers,
43454** depending on the contents of the WAL file. This does not change the
43455** allocated size of the page-mapping array - the page-mapping array merely
43456** contains unused entries.
43457**
43458** Even without using the hash table, the last frame for page P
43459** can be found by scanning the page-mapping sections of each index block
43460** starting with the last index block and moving toward the first, and
43461** within each index block, starting at the end and moving toward the
43462** beginning.  The first entry that equals P corresponds to the frame
43463** holding the content for that page.
43464**
43465** The hash table consists of HASHTABLE_NSLOT 16-bit unsigned integers.
43466** HASHTABLE_NSLOT = 2*HASHTABLE_NPAGE, and there is one entry in the
43467** hash table for each page number in the mapping section, so the hash
43468** table is never more than half full.  The expected number of collisions
43469** prior to finding a match is 1.  Each entry of the hash table is an
43470** 1-based index of an entry in the mapping section of the same
43471** index block.   Let K be the 1-based index of the largest entry in
43472** the mapping section.  (For index blocks other than the last, K will
43473** always be exactly HASHTABLE_NPAGE (4096) and for the last index block
43474** K will be (mxFrame%HASHTABLE_NPAGE).)  Unused slots of the hash table
43475** contain a value of 0.
43476**
43477** To look for page P in the hash table, first compute a hash iKey on
43478** P as follows:
43479**
43480**      iKey = (P * 383) % HASHTABLE_NSLOT
43481**
43482** Then start scanning entries of the hash table, starting with iKey
43483** (wrapping around to the beginning when the end of the hash table is
43484** reached) until an unused hash slot is found. Let the first unused slot
43485** be at index iUnused.  (iUnused might be less than iKey if there was
43486** wrap-around.) Because the hash table is never more than half full,
43487** the search is guaranteed to eventually hit an unused entry.  Let
43488** iMax be the value between iKey and iUnused, closest to iUnused,
43489** where aHash[iMax]==P.  If there is no iMax entry (if there exists
43490** no hash slot such that aHash[i]==p) then page P is not in the
43491** current index block.  Otherwise the iMax-th mapping entry of the
43492** current index block corresponds to the last entry that references
43493** page P.
43494**
43495** A hash search begins with the last index block and moves toward the
43496** first index block, looking for entries corresponding to page P.  On
43497** average, only two or three slots in each index block need to be
43498** examined in order to either find the last entry for page P, or to
43499** establish that no such entry exists in the block.  Each index block
43500** holds over 4000 entries.  So two or three index blocks are sufficient
43501** to cover a typical 10 megabyte WAL file, assuming 1K pages.  8 or 10
43502** comparisons (on average) suffice to either locate a frame in the
43503** WAL or to establish that the frame does not exist in the WAL.  This
43504** is much faster than scanning the entire 10MB WAL.
43505**
43506** Note that entries are added in order of increasing K.  Hence, one
43507** reader might be using some value K0 and a second reader that started
43508** at a later time (after additional transactions were added to the WAL
43509** and to the wal-index) might be using a different value K1, where K1>K0.
43510** Both readers can use the same hash table and mapping section to get
43511** the correct result.  There may be entries in the hash table with
43512** K>K0 but to the first reader, those entries will appear to be unused
43513** slots in the hash table and so the first reader will get an answer as
43514** if no values greater than K0 had ever been inserted into the hash table
43515** in the first place - which is what reader one wants.  Meanwhile, the
43516** second reader using K1 will see additional values that were inserted
43517** later, which is exactly what reader two wants.
43518**
43519** When a rollback occurs, the value of K is decreased. Hash table entries
43520** that correspond to frames greater than the new K value are removed
43521** from the hash table at this point.
43522*/
43523#ifndef SQLITE_OMIT_WAL
43524
43525
43526/*
43527** Trace output macros
43528*/
43529#if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
43530SQLITE_PRIVATE int sqlite3WalTrace = 0;
43531# define WALTRACE(X)  if(sqlite3WalTrace) sqlite3DebugPrintf X
43532#else
43533# define WALTRACE(X)
43534#endif
43535
43536/*
43537** The maximum (and only) versions of the wal and wal-index formats
43538** that may be interpreted by this version of SQLite.
43539**
43540** If a client begins recovering a WAL file and finds that (a) the checksum
43541** values in the wal-header are correct and (b) the version field is not
43542** WAL_MAX_VERSION, recovery fails and SQLite returns SQLITE_CANTOPEN.
43543**
43544** Similarly, if a client successfully reads a wal-index header (i.e. the
43545** checksum test is successful) and finds that the version field is not
43546** WALINDEX_MAX_VERSION, then no read-transaction is opened and SQLite
43547** returns SQLITE_CANTOPEN.
43548*/
43549#define WAL_MAX_VERSION      3007000
43550#define WALINDEX_MAX_VERSION 3007000
43551
43552/*
43553** Indices of various locking bytes.   WAL_NREADER is the number
43554** of available reader locks and should be at least 3.
43555*/
43556#define WAL_WRITE_LOCK         0
43557#define WAL_ALL_BUT_WRITE      1
43558#define WAL_CKPT_LOCK          1
43559#define WAL_RECOVER_LOCK       2
43560#define WAL_READ_LOCK(I)       (3+(I))
43561#define WAL_NREADER            (SQLITE_SHM_NLOCK-3)
43562
43563
43564/* Object declarations */
43565typedef struct WalIndexHdr WalIndexHdr;
43566typedef struct WalIterator WalIterator;
43567typedef struct WalCkptInfo WalCkptInfo;
43568
43569
43570/*
43571** The following object holds a copy of the wal-index header content.
43572**
43573** The actual header in the wal-index consists of two copies of this
43574** object.
43575**
43576** The szPage value can be any power of 2 between 512 and 32768, inclusive.
43577** Or it can be 1 to represent a 65536-byte page.  The latter case was
43578** added in 3.7.1 when support for 64K pages was added.
43579*/
43580struct WalIndexHdr {
43581  u32 iVersion;                   /* Wal-index version */
43582  u32 unused;                     /* Unused (padding) field */
43583  u32 iChange;                    /* Counter incremented each transaction */
43584  u8 isInit;                      /* 1 when initialized */
43585  u8 bigEndCksum;                 /* True if checksums in WAL are big-endian */
43586  u16 szPage;                     /* Database page size in bytes. 1==64K */
43587  u32 mxFrame;                    /* Index of last valid frame in the WAL */
43588  u32 nPage;                      /* Size of database in pages */
43589  u32 aFrameCksum[2];             /* Checksum of last frame in log */
43590  u32 aSalt[2];                   /* Two salt values copied from WAL header */
43591  u32 aCksum[2];                  /* Checksum over all prior fields */
43592};
43593
43594/*
43595** A copy of the following object occurs in the wal-index immediately
43596** following the second copy of the WalIndexHdr.  This object stores
43597** information used by checkpoint.
43598**
43599** nBackfill is the number of frames in the WAL that have been written
43600** back into the database. (We call the act of moving content from WAL to
43601** database "backfilling".)  The nBackfill number is never greater than
43602** WalIndexHdr.mxFrame.  nBackfill can only be increased by threads
43603** holding the WAL_CKPT_LOCK lock (which includes a recovery thread).
43604** However, a WAL_WRITE_LOCK thread can move the value of nBackfill from
43605** mxFrame back to zero when the WAL is reset.
43606**
43607** There is one entry in aReadMark[] for each reader lock.  If a reader
43608** holds read-lock K, then the value in aReadMark[K] is no greater than
43609** the mxFrame for that reader.  The value READMARK_NOT_USED (0xffffffff)
43610** for any aReadMark[] means that entry is unused.  aReadMark[0] is
43611** a special case; its value is never used and it exists as a place-holder
43612** to avoid having to offset aReadMark[] indexs by one.  Readers holding
43613** WAL_READ_LOCK(0) always ignore the entire WAL and read all content
43614** directly from the database.
43615**
43616** The value of aReadMark[K] may only be changed by a thread that
43617** is holding an exclusive lock on WAL_READ_LOCK(K).  Thus, the value of
43618** aReadMark[K] cannot changed while there is a reader is using that mark
43619** since the reader will be holding a shared lock on WAL_READ_LOCK(K).
43620**
43621** The checkpointer may only transfer frames from WAL to database where
43622** the frame numbers are less than or equal to every aReadMark[] that is
43623** in use (that is, every aReadMark[j] for which there is a corresponding
43624** WAL_READ_LOCK(j)).  New readers (usually) pick the aReadMark[] with the
43625** largest value and will increase an unused aReadMark[] to mxFrame if there
43626** is not already an aReadMark[] equal to mxFrame.  The exception to the
43627** previous sentence is when nBackfill equals mxFrame (meaning that everything
43628** in the WAL has been backfilled into the database) then new readers
43629** will choose aReadMark[0] which has value 0 and hence such reader will
43630** get all their all content directly from the database file and ignore
43631** the WAL.
43632**
43633** Writers normally append new frames to the end of the WAL.  However,
43634** if nBackfill equals mxFrame (meaning that all WAL content has been
43635** written back into the database) and if no readers are using the WAL
43636** (in other words, if there are no WAL_READ_LOCK(i) where i>0) then
43637** the writer will first "reset" the WAL back to the beginning and start
43638** writing new content beginning at frame 1.
43639**
43640** We assume that 32-bit loads are atomic and so no locks are needed in
43641** order to read from any aReadMark[] entries.
43642*/
43643struct WalCkptInfo {
43644  u32 nBackfill;                  /* Number of WAL frames backfilled into DB */
43645  u32 aReadMark[WAL_NREADER];     /* Reader marks */
43646};
43647#define READMARK_NOT_USED  0xffffffff
43648
43649
43650/* A block of WALINDEX_LOCK_RESERVED bytes beginning at
43651** WALINDEX_LOCK_OFFSET is reserved for locks. Since some systems
43652** only support mandatory file-locks, we do not read or write data
43653** from the region of the file on which locks are applied.
43654*/
43655#define WALINDEX_LOCK_OFFSET   (sizeof(WalIndexHdr)*2 + sizeof(WalCkptInfo))
43656#define WALINDEX_LOCK_RESERVED 16
43657#define WALINDEX_HDR_SIZE      (WALINDEX_LOCK_OFFSET+WALINDEX_LOCK_RESERVED)
43658
43659/* Size of header before each frame in wal */
43660#define WAL_FRAME_HDRSIZE 24
43661
43662/* Size of write ahead log header, including checksum. */
43663/* #define WAL_HDRSIZE 24 */
43664#define WAL_HDRSIZE 32
43665
43666/* WAL magic value. Either this value, or the same value with the least
43667** significant bit also set (WAL_MAGIC | 0x00000001) is stored in 32-bit
43668** big-endian format in the first 4 bytes of a WAL file.
43669**
43670** If the LSB is set, then the checksums for each frame within the WAL
43671** file are calculated by treating all data as an array of 32-bit
43672** big-endian words. Otherwise, they are calculated by interpreting
43673** all data as 32-bit little-endian words.
43674*/
43675#define WAL_MAGIC 0x377f0682
43676
43677/*
43678** Return the offset of frame iFrame in the write-ahead log file,
43679** assuming a database page size of szPage bytes. The offset returned
43680** is to the start of the write-ahead log frame-header.
43681*/
43682#define walFrameOffset(iFrame, szPage) (                               \
43683  WAL_HDRSIZE + ((iFrame)-1)*(i64)((szPage)+WAL_FRAME_HDRSIZE)         \
43684)
43685
43686/*
43687** An open write-ahead log file is represented by an instance of the
43688** following object.
43689*/
43690struct Wal {
43691  sqlite3_vfs *pVfs;         /* The VFS used to create pDbFd */
43692  sqlite3_file *pDbFd;       /* File handle for the database file */
43693  sqlite3_file *pWalFd;      /* File handle for WAL file */
43694  u32 iCallback;             /* Value to pass to log callback (or 0) */
43695  int nWiData;               /* Size of array apWiData */
43696  volatile u32 **apWiData;   /* Pointer to wal-index content in memory */
43697  u32 szPage;                /* Database page size */
43698  i16 readLock;              /* Which read lock is being held.  -1 for none */
43699  u8 exclusiveMode;          /* Non-zero if connection is in exclusive mode */
43700  u8 writeLock;              /* True if in a write transaction */
43701  u8 ckptLock;               /* True if holding a checkpoint lock */
43702  u8 readOnly;               /* True if the WAL file is open read-only */
43703  WalIndexHdr hdr;           /* Wal-index header for current transaction */
43704  const char *zWalName;      /* Name of WAL file */
43705  u32 nCkpt;                 /* Checkpoint sequence counter in the wal-header */
43706#ifdef SQLITE_DEBUG
43707  u8 lockError;              /* True if a locking error has occurred */
43708#endif
43709};
43710
43711/*
43712** Candidate values for Wal.exclusiveMode.
43713*/
43714#define WAL_NORMAL_MODE     0
43715#define WAL_EXCLUSIVE_MODE  1
43716#define WAL_HEAPMEMORY_MODE 2
43717
43718/*
43719** Each page of the wal-index mapping contains a hash-table made up of
43720** an array of HASHTABLE_NSLOT elements of the following type.
43721*/
43722typedef u16 ht_slot;
43723
43724/*
43725** This structure is used to implement an iterator that loops through
43726** all frames in the WAL in database page order. Where two or more frames
43727** correspond to the same database page, the iterator visits only the
43728** frame most recently written to the WAL (in other words, the frame with
43729** the largest index).
43730**
43731** The internals of this structure are only accessed by:
43732**
43733**   walIteratorInit() - Create a new iterator,
43734**   walIteratorNext() - Step an iterator,
43735**   walIteratorFree() - Free an iterator.
43736**
43737** This functionality is used by the checkpoint code (see walCheckpoint()).
43738*/
43739struct WalIterator {
43740  int iPrior;                     /* Last result returned from the iterator */
43741  int nSegment;                   /* Number of entries in aSegment[] */
43742  struct WalSegment {
43743    int iNext;                    /* Next slot in aIndex[] not yet returned */
43744    ht_slot *aIndex;              /* i0, i1, i2... such that aPgno[iN] ascend */
43745    u32 *aPgno;                   /* Array of page numbers. */
43746    int nEntry;                   /* Nr. of entries in aPgno[] and aIndex[] */
43747    int iZero;                    /* Frame number associated with aPgno[0] */
43748  } aSegment[1];                  /* One for every 32KB page in the wal-index */
43749};
43750
43751/*
43752** Define the parameters of the hash tables in the wal-index file. There
43753** is a hash-table following every HASHTABLE_NPAGE page numbers in the
43754** wal-index.
43755**
43756** Changing any of these constants will alter the wal-index format and
43757** create incompatibilities.
43758*/
43759#define HASHTABLE_NPAGE      4096                 /* Must be power of 2 */
43760#define HASHTABLE_HASH_1     383                  /* Should be prime */
43761#define HASHTABLE_NSLOT      (HASHTABLE_NPAGE*2)  /* Must be a power of 2 */
43762
43763/*
43764** The block of page numbers associated with the first hash-table in a
43765** wal-index is smaller than usual. This is so that there is a complete
43766** hash-table on each aligned 32KB page of the wal-index.
43767*/
43768#define HASHTABLE_NPAGE_ONE  (HASHTABLE_NPAGE - (WALINDEX_HDR_SIZE/sizeof(u32)))
43769
43770/* The wal-index is divided into pages of WALINDEX_PGSZ bytes each. */
43771#define WALINDEX_PGSZ   (                                         \
43772    sizeof(ht_slot)*HASHTABLE_NSLOT + HASHTABLE_NPAGE*sizeof(u32) \
43773)
43774
43775/*
43776** Obtain a pointer to the iPage'th page of the wal-index. The wal-index
43777** is broken into pages of WALINDEX_PGSZ bytes. Wal-index pages are
43778** numbered from zero.
43779**
43780** If this call is successful, *ppPage is set to point to the wal-index
43781** page and SQLITE_OK is returned. If an error (an OOM or VFS error) occurs,
43782** then an SQLite error code is returned and *ppPage is set to 0.
43783*/
43784static int walIndexPage(Wal *pWal, int iPage, volatile u32 **ppPage){
43785  int rc = SQLITE_OK;
43786
43787  /* Enlarge the pWal->apWiData[] array if required */
43788  if( pWal->nWiData<=iPage ){
43789    int nByte = sizeof(u32*)*(iPage+1);
43790    volatile u32 **apNew;
43791    apNew = (volatile u32 **)sqlite3_realloc((void *)pWal->apWiData, nByte);
43792    if( !apNew ){
43793      *ppPage = 0;
43794      return SQLITE_NOMEM;
43795    }
43796    memset((void*)&apNew[pWal->nWiData], 0,
43797           sizeof(u32*)*(iPage+1-pWal->nWiData));
43798    pWal->apWiData = apNew;
43799    pWal->nWiData = iPage+1;
43800  }
43801
43802  /* Request a pointer to the required page from the VFS */
43803  if( pWal->apWiData[iPage]==0 ){
43804    if( pWal->exclusiveMode==WAL_HEAPMEMORY_MODE ){
43805      pWal->apWiData[iPage] = (u32 volatile *)sqlite3MallocZero(WALINDEX_PGSZ);
43806      if( !pWal->apWiData[iPage] ) rc = SQLITE_NOMEM;
43807    }else{
43808      rc = sqlite3OsShmMap(pWal->pDbFd, iPage, WALINDEX_PGSZ,
43809          pWal->writeLock, (void volatile **)&pWal->apWiData[iPage]
43810      );
43811    }
43812  }
43813
43814  *ppPage = pWal->apWiData[iPage];
43815  assert( iPage==0 || *ppPage || rc!=SQLITE_OK );
43816  return rc;
43817}
43818
43819/*
43820** Return a pointer to the WalCkptInfo structure in the wal-index.
43821*/
43822static volatile WalCkptInfo *walCkptInfo(Wal *pWal){
43823  assert( pWal->nWiData>0 && pWal->apWiData[0] );
43824  return (volatile WalCkptInfo*)&(pWal->apWiData[0][sizeof(WalIndexHdr)/2]);
43825}
43826
43827/*
43828** Return a pointer to the WalIndexHdr structure in the wal-index.
43829*/
43830static volatile WalIndexHdr *walIndexHdr(Wal *pWal){
43831  assert( pWal->nWiData>0 && pWal->apWiData[0] );
43832  return (volatile WalIndexHdr*)pWal->apWiData[0];
43833}
43834
43835/*
43836** The argument to this macro must be of type u32. On a little-endian
43837** architecture, it returns the u32 value that results from interpreting
43838** the 4 bytes as a big-endian value. On a big-endian architecture, it
43839** returns the value that would be produced by intepreting the 4 bytes
43840** of the input value as a little-endian integer.
43841*/
43842#define BYTESWAP32(x) ( \
43843    (((x)&0x000000FF)<<24) + (((x)&0x0000FF00)<<8)  \
43844  + (((x)&0x00FF0000)>>8)  + (((x)&0xFF000000)>>24) \
43845)
43846
43847/*
43848** Generate or extend an 8 byte checksum based on the data in
43849** array aByte[] and the initial values of aIn[0] and aIn[1] (or
43850** initial values of 0 and 0 if aIn==NULL).
43851**
43852** The checksum is written back into aOut[] before returning.
43853**
43854** nByte must be a positive multiple of 8.
43855*/
43856static void walChecksumBytes(
43857  int nativeCksum, /* True for native byte-order, false for non-native */
43858  u8 *a,           /* Content to be checksummed */
43859  int nByte,       /* Bytes of content in a[].  Must be a multiple of 8. */
43860  const u32 *aIn,  /* Initial checksum value input */
43861  u32 *aOut        /* OUT: Final checksum value output */
43862){
43863  u32 s1, s2;
43864  u32 *aData = (u32 *)a;
43865  u32 *aEnd = (u32 *)&a[nByte];
43866
43867  if( aIn ){
43868    s1 = aIn[0];
43869    s2 = aIn[1];
43870  }else{
43871    s1 = s2 = 0;
43872  }
43873
43874  assert( nByte>=8 );
43875  assert( (nByte&0x00000007)==0 );
43876
43877  if( nativeCksum ){
43878    do {
43879      s1 += *aData++ + s2;
43880      s2 += *aData++ + s1;
43881    }while( aData<aEnd );
43882  }else{
43883    do {
43884      s1 += BYTESWAP32(aData[0]) + s2;
43885      s2 += BYTESWAP32(aData[1]) + s1;
43886      aData += 2;
43887    }while( aData<aEnd );
43888  }
43889
43890  aOut[0] = s1;
43891  aOut[1] = s2;
43892}
43893
43894static void walShmBarrier(Wal *pWal){
43895  if( pWal->exclusiveMode!=WAL_HEAPMEMORY_MODE ){
43896    sqlite3OsShmBarrier(pWal->pDbFd);
43897  }
43898}
43899
43900/*
43901** Write the header information in pWal->hdr into the wal-index.
43902**
43903** The checksum on pWal->hdr is updated before it is written.
43904*/
43905static void walIndexWriteHdr(Wal *pWal){
43906  volatile WalIndexHdr *aHdr = walIndexHdr(pWal);
43907  const int nCksum = offsetof(WalIndexHdr, aCksum);
43908
43909  assert( pWal->writeLock );
43910  pWal->hdr.isInit = 1;
43911  pWal->hdr.iVersion = WALINDEX_MAX_VERSION;
43912  walChecksumBytes(1, (u8*)&pWal->hdr, nCksum, 0, pWal->hdr.aCksum);
43913  memcpy((void *)&aHdr[1], (void *)&pWal->hdr, sizeof(WalIndexHdr));
43914  walShmBarrier(pWal);
43915  memcpy((void *)&aHdr[0], (void *)&pWal->hdr, sizeof(WalIndexHdr));
43916}
43917
43918/*
43919** This function encodes a single frame header and writes it to a buffer
43920** supplied by the caller. A frame-header is made up of a series of
43921** 4-byte big-endian integers, as follows:
43922**
43923**     0: Page number.
43924**     4: For commit records, the size of the database image in pages
43925**        after the commit. For all other records, zero.
43926**     8: Salt-1 (copied from the wal-header)
43927**    12: Salt-2 (copied from the wal-header)
43928**    16: Checksum-1.
43929**    20: Checksum-2.
43930*/
43931static void walEncodeFrame(
43932  Wal *pWal,                      /* The write-ahead log */
43933  u32 iPage,                      /* Database page number for frame */
43934  u32 nTruncate,                  /* New db size (or 0 for non-commit frames) */
43935  u8 *aData,                      /* Pointer to page data */
43936  u8 *aFrame                      /* OUT: Write encoded frame here */
43937){
43938  int nativeCksum;                /* True for native byte-order checksums */
43939  u32 *aCksum = pWal->hdr.aFrameCksum;
43940  assert( WAL_FRAME_HDRSIZE==24 );
43941  sqlite3Put4byte(&aFrame[0], iPage);
43942  sqlite3Put4byte(&aFrame[4], nTruncate);
43943  memcpy(&aFrame[8], pWal->hdr.aSalt, 8);
43944
43945  nativeCksum = (pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN);
43946  walChecksumBytes(nativeCksum, aFrame, 8, aCksum, aCksum);
43947  walChecksumBytes(nativeCksum, aData, pWal->szPage, aCksum, aCksum);
43948
43949  sqlite3Put4byte(&aFrame[16], aCksum[0]);
43950  sqlite3Put4byte(&aFrame[20], aCksum[1]);
43951}
43952
43953/*
43954** Check to see if the frame with header in aFrame[] and content
43955** in aData[] is valid.  If it is a valid frame, fill *piPage and
43956** *pnTruncate and return true.  Return if the frame is not valid.
43957*/
43958static int walDecodeFrame(
43959  Wal *pWal,                      /* The write-ahead log */
43960  u32 *piPage,                    /* OUT: Database page number for frame */
43961  u32 *pnTruncate,                /* OUT: New db size (or 0 if not commit) */
43962  u8 *aData,                      /* Pointer to page data (for checksum) */
43963  u8 *aFrame                      /* Frame data */
43964){
43965  int nativeCksum;                /* True for native byte-order checksums */
43966  u32 *aCksum = pWal->hdr.aFrameCksum;
43967  u32 pgno;                       /* Page number of the frame */
43968  assert( WAL_FRAME_HDRSIZE==24 );
43969
43970  /* A frame is only valid if the salt values in the frame-header
43971  ** match the salt values in the wal-header.
43972  */
43973  if( memcmp(&pWal->hdr.aSalt, &aFrame[8], 8)!=0 ){
43974    return 0;
43975  }
43976
43977  /* A frame is only valid if the page number is creater than zero.
43978  */
43979  pgno = sqlite3Get4byte(&aFrame[0]);
43980  if( pgno==0 ){
43981    return 0;
43982  }
43983
43984  /* A frame is only valid if a checksum of the WAL header,
43985  ** all prior frams, the first 16 bytes of this frame-header,
43986  ** and the frame-data matches the checksum in the last 8
43987  ** bytes of this frame-header.
43988  */
43989  nativeCksum = (pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN);
43990  walChecksumBytes(nativeCksum, aFrame, 8, aCksum, aCksum);
43991  walChecksumBytes(nativeCksum, aData, pWal->szPage, aCksum, aCksum);
43992  if( aCksum[0]!=sqlite3Get4byte(&aFrame[16])
43993   || aCksum[1]!=sqlite3Get4byte(&aFrame[20])
43994  ){
43995    /* Checksum failed. */
43996    return 0;
43997  }
43998
43999  /* If we reach this point, the frame is valid.  Return the page number
44000  ** and the new database size.
44001  */
44002  *piPage = pgno;
44003  *pnTruncate = sqlite3Get4byte(&aFrame[4]);
44004  return 1;
44005}
44006
44007
44008#if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
44009/*
44010** Names of locks.  This routine is used to provide debugging output and is not
44011** a part of an ordinary build.
44012*/
44013static const char *walLockName(int lockIdx){
44014  if( lockIdx==WAL_WRITE_LOCK ){
44015    return "WRITE-LOCK";
44016  }else if( lockIdx==WAL_CKPT_LOCK ){
44017    return "CKPT-LOCK";
44018  }else if( lockIdx==WAL_RECOVER_LOCK ){
44019    return "RECOVER-LOCK";
44020  }else{
44021    static char zName[15];
44022    sqlite3_snprintf(sizeof(zName), zName, "READ-LOCK[%d]",
44023                     lockIdx-WAL_READ_LOCK(0));
44024    return zName;
44025  }
44026}
44027#endif /*defined(SQLITE_TEST) || defined(SQLITE_DEBUG) */
44028
44029
44030/*
44031** Set or release locks on the WAL.  Locks are either shared or exclusive.
44032** A lock cannot be moved directly between shared and exclusive - it must go
44033** through the unlocked state first.
44034**
44035** In locking_mode=EXCLUSIVE, all of these routines become no-ops.
44036*/
44037static int walLockShared(Wal *pWal, int lockIdx){
44038  int rc;
44039  if( pWal->exclusiveMode ) return SQLITE_OK;
44040  rc = sqlite3OsShmLock(pWal->pDbFd, lockIdx, 1,
44041                        SQLITE_SHM_LOCK | SQLITE_SHM_SHARED);
44042  WALTRACE(("WAL%p: acquire SHARED-%s %s\n", pWal,
44043            walLockName(lockIdx), rc ? "failed" : "ok"));
44044  VVA_ONLY( pWal->lockError = (u8)(rc!=SQLITE_OK && rc!=SQLITE_BUSY); )
44045  return rc;
44046}
44047static void walUnlockShared(Wal *pWal, int lockIdx){
44048  if( pWal->exclusiveMode ) return;
44049  (void)sqlite3OsShmLock(pWal->pDbFd, lockIdx, 1,
44050                         SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED);
44051  WALTRACE(("WAL%p: release SHARED-%s\n", pWal, walLockName(lockIdx)));
44052}
44053static int walLockExclusive(Wal *pWal, int lockIdx, int n){
44054  int rc;
44055  if( pWal->exclusiveMode ) return SQLITE_OK;
44056  rc = sqlite3OsShmLock(pWal->pDbFd, lockIdx, n,
44057                        SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE);
44058  WALTRACE(("WAL%p: acquire EXCLUSIVE-%s cnt=%d %s\n", pWal,
44059            walLockName(lockIdx), n, rc ? "failed" : "ok"));
44060  VVA_ONLY( pWal->lockError = (u8)(rc!=SQLITE_OK && rc!=SQLITE_BUSY); )
44061  return rc;
44062}
44063static void walUnlockExclusive(Wal *pWal, int lockIdx, int n){
44064  if( pWal->exclusiveMode ) return;
44065  (void)sqlite3OsShmLock(pWal->pDbFd, lockIdx, n,
44066                         SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE);
44067  WALTRACE(("WAL%p: release EXCLUSIVE-%s cnt=%d\n", pWal,
44068             walLockName(lockIdx), n));
44069}
44070
44071/*
44072** Compute a hash on a page number.  The resulting hash value must land
44073** between 0 and (HASHTABLE_NSLOT-1).  The walHashNext() function advances
44074** the hash to the next value in the event of a collision.
44075*/
44076static int walHash(u32 iPage){
44077  assert( iPage>0 );
44078  assert( (HASHTABLE_NSLOT & (HASHTABLE_NSLOT-1))==0 );
44079  return (iPage*HASHTABLE_HASH_1) & (HASHTABLE_NSLOT-1);
44080}
44081static int walNextHash(int iPriorHash){
44082  return (iPriorHash+1)&(HASHTABLE_NSLOT-1);
44083}
44084
44085/*
44086** Return pointers to the hash table and page number array stored on
44087** page iHash of the wal-index. The wal-index is broken into 32KB pages
44088** numbered starting from 0.
44089**
44090** Set output variable *paHash to point to the start of the hash table
44091** in the wal-index file. Set *piZero to one less than the frame
44092** number of the first frame indexed by this hash table. If a
44093** slot in the hash table is set to N, it refers to frame number
44094** (*piZero+N) in the log.
44095**
44096** Finally, set *paPgno so that *paPgno[1] is the page number of the
44097** first frame indexed by the hash table, frame (*piZero+1).
44098*/
44099static int walHashGet(
44100  Wal *pWal,                      /* WAL handle */
44101  int iHash,                      /* Find the iHash'th table */
44102  volatile ht_slot **paHash,      /* OUT: Pointer to hash index */
44103  volatile u32 **paPgno,          /* OUT: Pointer to page number array */
44104  u32 *piZero                     /* OUT: Frame associated with *paPgno[0] */
44105){
44106  int rc;                         /* Return code */
44107  volatile u32 *aPgno;
44108
44109  rc = walIndexPage(pWal, iHash, &aPgno);
44110  assert( rc==SQLITE_OK || iHash>0 );
44111
44112  if( rc==SQLITE_OK ){
44113    u32 iZero;
44114    volatile ht_slot *aHash;
44115
44116    aHash = (volatile ht_slot *)&aPgno[HASHTABLE_NPAGE];
44117    if( iHash==0 ){
44118      aPgno = &aPgno[WALINDEX_HDR_SIZE/sizeof(u32)];
44119      iZero = 0;
44120    }else{
44121      iZero = HASHTABLE_NPAGE_ONE + (iHash-1)*HASHTABLE_NPAGE;
44122    }
44123
44124    *paPgno = &aPgno[-1];
44125    *paHash = aHash;
44126    *piZero = iZero;
44127  }
44128  return rc;
44129}
44130
44131/*
44132** Return the number of the wal-index page that contains the hash-table
44133** and page-number array that contain entries corresponding to WAL frame
44134** iFrame. The wal-index is broken up into 32KB pages. Wal-index pages
44135** are numbered starting from 0.
44136*/
44137static int walFramePage(u32 iFrame){
44138  int iHash = (iFrame+HASHTABLE_NPAGE-HASHTABLE_NPAGE_ONE-1) / HASHTABLE_NPAGE;
44139  assert( (iHash==0 || iFrame>HASHTABLE_NPAGE_ONE)
44140       && (iHash>=1 || iFrame<=HASHTABLE_NPAGE_ONE)
44141       && (iHash<=1 || iFrame>(HASHTABLE_NPAGE_ONE+HASHTABLE_NPAGE))
44142       && (iHash>=2 || iFrame<=HASHTABLE_NPAGE_ONE+HASHTABLE_NPAGE)
44143       && (iHash<=2 || iFrame>(HASHTABLE_NPAGE_ONE+2*HASHTABLE_NPAGE))
44144  );
44145  return iHash;
44146}
44147
44148/*
44149** Return the page number associated with frame iFrame in this WAL.
44150*/
44151static u32 walFramePgno(Wal *pWal, u32 iFrame){
44152  int iHash = walFramePage(iFrame);
44153  if( iHash==0 ){
44154    return pWal->apWiData[0][WALINDEX_HDR_SIZE/sizeof(u32) + iFrame - 1];
44155  }
44156  return pWal->apWiData[iHash][(iFrame-1-HASHTABLE_NPAGE_ONE)%HASHTABLE_NPAGE];
44157}
44158
44159/*
44160** Remove entries from the hash table that point to WAL slots greater
44161** than pWal->hdr.mxFrame.
44162**
44163** This function is called whenever pWal->hdr.mxFrame is decreased due
44164** to a rollback or savepoint.
44165**
44166** At most only the hash table containing pWal->hdr.mxFrame needs to be
44167** updated.  Any later hash tables will be automatically cleared when
44168** pWal->hdr.mxFrame advances to the point where those hash tables are
44169** actually needed.
44170*/
44171static void walCleanupHash(Wal *pWal){
44172  volatile ht_slot *aHash = 0;    /* Pointer to hash table to clear */
44173  volatile u32 *aPgno = 0;        /* Page number array for hash table */
44174  u32 iZero = 0;                  /* frame == (aHash[x]+iZero) */
44175  int iLimit = 0;                 /* Zero values greater than this */
44176  int nByte;                      /* Number of bytes to zero in aPgno[] */
44177  int i;                          /* Used to iterate through aHash[] */
44178
44179  assert( pWal->writeLock );
44180  testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE-1 );
44181  testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE );
44182  testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE+1 );
44183
44184  if( pWal->hdr.mxFrame==0 ) return;
44185
44186  /* Obtain pointers to the hash-table and page-number array containing
44187  ** the entry that corresponds to frame pWal->hdr.mxFrame. It is guaranteed
44188  ** that the page said hash-table and array reside on is already mapped.
44189  */
44190  assert( pWal->nWiData>walFramePage(pWal->hdr.mxFrame) );
44191  assert( pWal->apWiData[walFramePage(pWal->hdr.mxFrame)] );
44192  walHashGet(pWal, walFramePage(pWal->hdr.mxFrame), &aHash, &aPgno, &iZero);
44193
44194  /* Zero all hash-table entries that correspond to frame numbers greater
44195  ** than pWal->hdr.mxFrame.
44196  */
44197  iLimit = pWal->hdr.mxFrame - iZero;
44198  assert( iLimit>0 );
44199  for(i=0; i<HASHTABLE_NSLOT; i++){
44200    if( aHash[i]>iLimit ){
44201      aHash[i] = 0;
44202    }
44203  }
44204
44205  /* Zero the entries in the aPgno array that correspond to frames with
44206  ** frame numbers greater than pWal->hdr.mxFrame.
44207  */
44208  nByte = (int)((char *)aHash - (char *)&aPgno[iLimit+1]);
44209  memset((void *)&aPgno[iLimit+1], 0, nByte);
44210
44211#ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
44212  /* Verify that the every entry in the mapping region is still reachable
44213  ** via the hash table even after the cleanup.
44214  */
44215  if( iLimit ){
44216    int i;           /* Loop counter */
44217    int iKey;        /* Hash key */
44218    for(i=1; i<=iLimit; i++){
44219      for(iKey=walHash(aPgno[i]); aHash[iKey]; iKey=walNextHash(iKey)){
44220        if( aHash[iKey]==i ) break;
44221      }
44222      assert( aHash[iKey]==i );
44223    }
44224  }
44225#endif /* SQLITE_ENABLE_EXPENSIVE_ASSERT */
44226}
44227
44228
44229/*
44230** Set an entry in the wal-index that will map database page number
44231** pPage into WAL frame iFrame.
44232*/
44233static int walIndexAppend(Wal *pWal, u32 iFrame, u32 iPage){
44234  int rc;                         /* Return code */
44235  u32 iZero = 0;                  /* One less than frame number of aPgno[1] */
44236  volatile u32 *aPgno = 0;        /* Page number array */
44237  volatile ht_slot *aHash = 0;    /* Hash table */
44238
44239  rc = walHashGet(pWal, walFramePage(iFrame), &aHash, &aPgno, &iZero);
44240
44241  /* Assuming the wal-index file was successfully mapped, populate the
44242  ** page number array and hash table entry.
44243  */
44244  if( rc==SQLITE_OK ){
44245    int iKey;                     /* Hash table key */
44246    int idx;                      /* Value to write to hash-table slot */
44247    int nCollide;                 /* Number of hash collisions */
44248
44249    idx = iFrame - iZero;
44250    assert( idx <= HASHTABLE_NSLOT/2 + 1 );
44251
44252    /* If this is the first entry to be added to this hash-table, zero the
44253    ** entire hash table and aPgno[] array before proceding.
44254    */
44255    if( idx==1 ){
44256      int nByte = (int)((u8 *)&aHash[HASHTABLE_NSLOT] - (u8 *)&aPgno[1]);
44257      memset((void*)&aPgno[1], 0, nByte);
44258    }
44259
44260    /* If the entry in aPgno[] is already set, then the previous writer
44261    ** must have exited unexpectedly in the middle of a transaction (after
44262    ** writing one or more dirty pages to the WAL to free up memory).
44263    ** Remove the remnants of that writers uncommitted transaction from
44264    ** the hash-table before writing any new entries.
44265    */
44266    if( aPgno[idx] ){
44267      walCleanupHash(pWal);
44268      assert( !aPgno[idx] );
44269    }
44270
44271    /* Write the aPgno[] array entry and the hash-table slot. */
44272    nCollide = idx;
44273    for(iKey=walHash(iPage); aHash[iKey]; iKey=walNextHash(iKey)){
44274      if( (nCollide--)==0 ) return SQLITE_CORRUPT_BKPT;
44275    }
44276    aPgno[idx] = iPage;
44277    aHash[iKey] = (ht_slot)idx;
44278
44279#ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
44280    /* Verify that the number of entries in the hash table exactly equals
44281    ** the number of entries in the mapping region.
44282    */
44283    {
44284      int i;           /* Loop counter */
44285      int nEntry = 0;  /* Number of entries in the hash table */
44286      for(i=0; i<HASHTABLE_NSLOT; i++){ if( aHash[i] ) nEntry++; }
44287      assert( nEntry==idx );
44288    }
44289
44290    /* Verify that the every entry in the mapping region is reachable
44291    ** via the hash table.  This turns out to be a really, really expensive
44292    ** thing to check, so only do this occasionally - not on every
44293    ** iteration.
44294    */
44295    if( (idx&0x3ff)==0 ){
44296      int i;           /* Loop counter */
44297      for(i=1; i<=idx; i++){
44298        for(iKey=walHash(aPgno[i]); aHash[iKey]; iKey=walNextHash(iKey)){
44299          if( aHash[iKey]==i ) break;
44300        }
44301        assert( aHash[iKey]==i );
44302      }
44303    }
44304#endif /* SQLITE_ENABLE_EXPENSIVE_ASSERT */
44305  }
44306
44307
44308  return rc;
44309}
44310
44311
44312/*
44313** Recover the wal-index by reading the write-ahead log file.
44314**
44315** This routine first tries to establish an exclusive lock on the
44316** wal-index to prevent other threads/processes from doing anything
44317** with the WAL or wal-index while recovery is running.  The
44318** WAL_RECOVER_LOCK is also held so that other threads will know
44319** that this thread is running recovery.  If unable to establish
44320** the necessary locks, this routine returns SQLITE_BUSY.
44321*/
44322static int walIndexRecover(Wal *pWal){
44323  int rc;                         /* Return Code */
44324  i64 nSize;                      /* Size of log file */
44325  u32 aFrameCksum[2] = {0, 0};
44326  int iLock;                      /* Lock offset to lock for checkpoint */
44327  int nLock;                      /* Number of locks to hold */
44328
44329  /* Obtain an exclusive lock on all byte in the locking range not already
44330  ** locked by the caller. The caller is guaranteed to have locked the
44331  ** WAL_WRITE_LOCK byte, and may have also locked the WAL_CKPT_LOCK byte.
44332  ** If successful, the same bytes that are locked here are unlocked before
44333  ** this function returns.
44334  */
44335  assert( pWal->ckptLock==1 || pWal->ckptLock==0 );
44336  assert( WAL_ALL_BUT_WRITE==WAL_WRITE_LOCK+1 );
44337  assert( WAL_CKPT_LOCK==WAL_ALL_BUT_WRITE );
44338  assert( pWal->writeLock );
44339  iLock = WAL_ALL_BUT_WRITE + pWal->ckptLock;
44340  nLock = SQLITE_SHM_NLOCK - iLock;
44341  rc = walLockExclusive(pWal, iLock, nLock);
44342  if( rc ){
44343    return rc;
44344  }
44345  WALTRACE(("WAL%p: recovery begin...\n", pWal));
44346
44347  memset(&pWal->hdr, 0, sizeof(WalIndexHdr));
44348
44349  rc = sqlite3OsFileSize(pWal->pWalFd, &nSize);
44350  if( rc!=SQLITE_OK ){
44351    goto recovery_error;
44352  }
44353
44354  if( nSize>WAL_HDRSIZE ){
44355    u8 aBuf[WAL_HDRSIZE];         /* Buffer to load WAL header into */
44356    u8 *aFrame = 0;               /* Malloc'd buffer to load entire frame */
44357    int szFrame;                  /* Number of bytes in buffer aFrame[] */
44358    u8 *aData;                    /* Pointer to data part of aFrame buffer */
44359    int iFrame;                   /* Index of last frame read */
44360    i64 iOffset;                  /* Next offset to read from log file */
44361    int szPage;                   /* Page size according to the log */
44362    u32 magic;                    /* Magic value read from WAL header */
44363    u32 version;                  /* Magic value read from WAL header */
44364
44365    /* Read in the WAL header. */
44366    rc = sqlite3OsRead(pWal->pWalFd, aBuf, WAL_HDRSIZE, 0);
44367    if( rc!=SQLITE_OK ){
44368      goto recovery_error;
44369    }
44370
44371    /* If the database page size is not a power of two, or is greater than
44372    ** SQLITE_MAX_PAGE_SIZE, conclude that the WAL file contains no valid
44373    ** data. Similarly, if the 'magic' value is invalid, ignore the whole
44374    ** WAL file.
44375    */
44376    magic = sqlite3Get4byte(&aBuf[0]);
44377    szPage = sqlite3Get4byte(&aBuf[8]);
44378    if( (magic&0xFFFFFFFE)!=WAL_MAGIC
44379     || szPage&(szPage-1)
44380     || szPage>SQLITE_MAX_PAGE_SIZE
44381     || szPage<512
44382    ){
44383      goto finished;
44384    }
44385    pWal->hdr.bigEndCksum = (u8)(magic&0x00000001);
44386    pWal->szPage = szPage;
44387    pWal->nCkpt = sqlite3Get4byte(&aBuf[12]);
44388    memcpy(&pWal->hdr.aSalt, &aBuf[16], 8);
44389
44390    /* Verify that the WAL header checksum is correct */
44391    walChecksumBytes(pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN,
44392        aBuf, WAL_HDRSIZE-2*4, 0, pWal->hdr.aFrameCksum
44393    );
44394    if( pWal->hdr.aFrameCksum[0]!=sqlite3Get4byte(&aBuf[24])
44395     || pWal->hdr.aFrameCksum[1]!=sqlite3Get4byte(&aBuf[28])
44396    ){
44397      goto finished;
44398    }
44399
44400    /* Verify that the version number on the WAL format is one that
44401    ** are able to understand */
44402    version = sqlite3Get4byte(&aBuf[4]);
44403    if( version!=WAL_MAX_VERSION ){
44404      rc = SQLITE_CANTOPEN_BKPT;
44405      goto finished;
44406    }
44407
44408    /* Malloc a buffer to read frames into. */
44409    szFrame = szPage + WAL_FRAME_HDRSIZE;
44410    aFrame = (u8 *)sqlite3_malloc(szFrame);
44411    if( !aFrame ){
44412      rc = SQLITE_NOMEM;
44413      goto recovery_error;
44414    }
44415    aData = &aFrame[WAL_FRAME_HDRSIZE];
44416
44417    /* Read all frames from the log file. */
44418    iFrame = 0;
44419    for(iOffset=WAL_HDRSIZE; (iOffset+szFrame)<=nSize; iOffset+=szFrame){
44420      u32 pgno;                   /* Database page number for frame */
44421      u32 nTruncate;              /* dbsize field from frame header */
44422      int isValid;                /* True if this frame is valid */
44423
44424      /* Read and decode the next log frame. */
44425      rc = sqlite3OsRead(pWal->pWalFd, aFrame, szFrame, iOffset);
44426      if( rc!=SQLITE_OK ) break;
44427      isValid = walDecodeFrame(pWal, &pgno, &nTruncate, aData, aFrame);
44428      if( !isValid ) break;
44429      rc = walIndexAppend(pWal, ++iFrame, pgno);
44430      if( rc!=SQLITE_OK ) break;
44431
44432      /* If nTruncate is non-zero, this is a commit record. */
44433      if( nTruncate ){
44434        pWal->hdr.mxFrame = iFrame;
44435        pWal->hdr.nPage = nTruncate;
44436        pWal->hdr.szPage = (u16)((szPage&0xff00) | (szPage>>16));
44437        testcase( szPage<=32768 );
44438        testcase( szPage>=65536 );
44439        aFrameCksum[0] = pWal->hdr.aFrameCksum[0];
44440        aFrameCksum[1] = pWal->hdr.aFrameCksum[1];
44441      }
44442    }
44443
44444    sqlite3_free(aFrame);
44445  }
44446
44447finished:
44448  if( rc==SQLITE_OK ){
44449    volatile WalCkptInfo *pInfo;
44450    int i;
44451    pWal->hdr.aFrameCksum[0] = aFrameCksum[0];
44452    pWal->hdr.aFrameCksum[1] = aFrameCksum[1];
44453    walIndexWriteHdr(pWal);
44454
44455    /* Reset the checkpoint-header. This is safe because this thread is
44456    ** currently holding locks that exclude all other readers, writers and
44457    ** checkpointers.
44458    */
44459    pInfo = walCkptInfo(pWal);
44460    pInfo->nBackfill = 0;
44461    pInfo->aReadMark[0] = 0;
44462    for(i=1; i<WAL_NREADER; i++) pInfo->aReadMark[i] = READMARK_NOT_USED;
44463
44464    /* If more than one frame was recovered from the log file, report an
44465    ** event via sqlite3_log(). This is to help with identifying performance
44466    ** problems caused by applications routinely shutting down without
44467    ** checkpointing the log file.
44468    */
44469    if( pWal->hdr.nPage ){
44470      sqlite3_log(SQLITE_OK, "Recovered %d frames from WAL file %s",
44471          pWal->hdr.nPage, pWal->zWalName
44472      );
44473    }
44474  }
44475
44476recovery_error:
44477  WALTRACE(("WAL%p: recovery %s\n", pWal, rc ? "failed" : "ok"));
44478  walUnlockExclusive(pWal, iLock, nLock);
44479  return rc;
44480}
44481
44482/*
44483** Close an open wal-index.
44484*/
44485static void walIndexClose(Wal *pWal, int isDelete){
44486  if( pWal->exclusiveMode==WAL_HEAPMEMORY_MODE ){
44487    int i;
44488    for(i=0; i<pWal->nWiData; i++){
44489      sqlite3_free((void *)pWal->apWiData[i]);
44490      pWal->apWiData[i] = 0;
44491    }
44492  }else{
44493    sqlite3OsShmUnmap(pWal->pDbFd, isDelete);
44494  }
44495}
44496
44497/*
44498** Open a connection to the WAL file zWalName. The database file must
44499** already be opened on connection pDbFd. The buffer that zWalName points
44500** to must remain valid for the lifetime of the returned Wal* handle.
44501**
44502** A SHARED lock should be held on the database file when this function
44503** is called. The purpose of this SHARED lock is to prevent any other
44504** client from unlinking the WAL or wal-index file. If another process
44505** were to do this just after this client opened one of these files, the
44506** system would be badly broken.
44507**
44508** If the log file is successfully opened, SQLITE_OK is returned and
44509** *ppWal is set to point to a new WAL handle. If an error occurs,
44510** an SQLite error code is returned and *ppWal is left unmodified.
44511*/
44512SQLITE_PRIVATE int sqlite3WalOpen(
44513  sqlite3_vfs *pVfs,              /* vfs module to open wal and wal-index */
44514  sqlite3_file *pDbFd,            /* The open database file */
44515  const char *zWalName,           /* Name of the WAL file */
44516  int bNoShm,                     /* True to run in heap-memory mode */
44517  Wal **ppWal                     /* OUT: Allocated Wal handle */
44518){
44519  int rc;                         /* Return Code */
44520  Wal *pRet;                      /* Object to allocate and return */
44521  int flags;                      /* Flags passed to OsOpen() */
44522
44523  assert( zWalName && zWalName[0] );
44524  assert( pDbFd );
44525
44526  /* In the amalgamation, the os_unix.c and os_win.c source files come before
44527  ** this source file.  Verify that the #defines of the locking byte offsets
44528  ** in os_unix.c and os_win.c agree with the WALINDEX_LOCK_OFFSET value.
44529  */
44530#ifdef WIN_SHM_BASE
44531  assert( WIN_SHM_BASE==WALINDEX_LOCK_OFFSET );
44532#endif
44533#ifdef UNIX_SHM_BASE
44534  assert( UNIX_SHM_BASE==WALINDEX_LOCK_OFFSET );
44535#endif
44536
44537
44538  /* Allocate an instance of struct Wal to return. */
44539  *ppWal = 0;
44540  pRet = (Wal*)sqlite3MallocZero(sizeof(Wal) + pVfs->szOsFile);
44541  if( !pRet ){
44542    return SQLITE_NOMEM;
44543  }
44544
44545  pRet->pVfs = pVfs;
44546  pRet->pWalFd = (sqlite3_file *)&pRet[1];
44547  pRet->pDbFd = pDbFd;
44548  pRet->readLock = -1;
44549  pRet->zWalName = zWalName;
44550  pRet->exclusiveMode = (bNoShm ? WAL_HEAPMEMORY_MODE: WAL_NORMAL_MODE);
44551
44552  /* Open file handle on the write-ahead log file. */
44553  flags = (SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|SQLITE_OPEN_WAL);
44554  rc = sqlite3OsOpen(pVfs, zWalName, pRet->pWalFd, flags, &flags);
44555  if( rc==SQLITE_OK && flags&SQLITE_OPEN_READONLY ){
44556    pRet->readOnly = 1;
44557  }
44558
44559  if( rc!=SQLITE_OK ){
44560    walIndexClose(pRet, 0);
44561    sqlite3OsClose(pRet->pWalFd);
44562    sqlite3_free(pRet);
44563  }else{
44564    *ppWal = pRet;
44565    WALTRACE(("WAL%d: opened\n", pRet));
44566  }
44567  return rc;
44568}
44569
44570/*
44571** Find the smallest page number out of all pages held in the WAL that
44572** has not been returned by any prior invocation of this method on the
44573** same WalIterator object.   Write into *piFrame the frame index where
44574** that page was last written into the WAL.  Write into *piPage the page
44575** number.
44576**
44577** Return 0 on success.  If there are no pages in the WAL with a page
44578** number larger than *piPage, then return 1.
44579*/
44580static int walIteratorNext(
44581  WalIterator *p,               /* Iterator */
44582  u32 *piPage,                  /* OUT: The page number of the next page */
44583  u32 *piFrame                  /* OUT: Wal frame index of next page */
44584){
44585  u32 iMin;                     /* Result pgno must be greater than iMin */
44586  u32 iRet = 0xFFFFFFFF;        /* 0xffffffff is never a valid page number */
44587  int i;                        /* For looping through segments */
44588
44589  iMin = p->iPrior;
44590  assert( iMin<0xffffffff );
44591  for(i=p->nSegment-1; i>=0; i--){
44592    struct WalSegment *pSegment = &p->aSegment[i];
44593    while( pSegment->iNext<pSegment->nEntry ){
44594      u32 iPg = pSegment->aPgno[pSegment->aIndex[pSegment->iNext]];
44595      if( iPg>iMin ){
44596        if( iPg<iRet ){
44597          iRet = iPg;
44598          *piFrame = pSegment->iZero + pSegment->aIndex[pSegment->iNext];
44599        }
44600        break;
44601      }
44602      pSegment->iNext++;
44603    }
44604  }
44605
44606  *piPage = p->iPrior = iRet;
44607  return (iRet==0xFFFFFFFF);
44608}
44609
44610/*
44611** This function merges two sorted lists into a single sorted list.
44612**
44613** aLeft[] and aRight[] are arrays of indices.  The sort key is
44614** aContent[aLeft[]] and aContent[aRight[]].  Upon entry, the following
44615** is guaranteed for all J<K:
44616**
44617**        aContent[aLeft[J]] < aContent[aLeft[K]]
44618**        aContent[aRight[J]] < aContent[aRight[K]]
44619**
44620** This routine overwrites aRight[] with a new (probably longer) sequence
44621** of indices such that the aRight[] contains every index that appears in
44622** either aLeft[] or the old aRight[] and such that the second condition
44623** above is still met.
44624**
44625** The aContent[aLeft[X]] values will be unique for all X.  And the
44626** aContent[aRight[X]] values will be unique too.  But there might be
44627** one or more combinations of X and Y such that
44628**
44629**      aLeft[X]!=aRight[Y]  &&  aContent[aLeft[X]] == aContent[aRight[Y]]
44630**
44631** When that happens, omit the aLeft[X] and use the aRight[Y] index.
44632*/
44633static void walMerge(
44634  const u32 *aContent,            /* Pages in wal - keys for the sort */
44635  ht_slot *aLeft,                 /* IN: Left hand input list */
44636  int nLeft,                      /* IN: Elements in array *paLeft */
44637  ht_slot **paRight,              /* IN/OUT: Right hand input list */
44638  int *pnRight,                   /* IN/OUT: Elements in *paRight */
44639  ht_slot *aTmp                   /* Temporary buffer */
44640){
44641  int iLeft = 0;                  /* Current index in aLeft */
44642  int iRight = 0;                 /* Current index in aRight */
44643  int iOut = 0;                   /* Current index in output buffer */
44644  int nRight = *pnRight;
44645  ht_slot *aRight = *paRight;
44646
44647  assert( nLeft>0 && nRight>0 );
44648  while( iRight<nRight || iLeft<nLeft ){
44649    ht_slot logpage;
44650    Pgno dbpage;
44651
44652    if( (iLeft<nLeft)
44653     && (iRight>=nRight || aContent[aLeft[iLeft]]<aContent[aRight[iRight]])
44654    ){
44655      logpage = aLeft[iLeft++];
44656    }else{
44657      logpage = aRight[iRight++];
44658    }
44659    dbpage = aContent[logpage];
44660
44661    aTmp[iOut++] = logpage;
44662    if( iLeft<nLeft && aContent[aLeft[iLeft]]==dbpage ) iLeft++;
44663
44664    assert( iLeft>=nLeft || aContent[aLeft[iLeft]]>dbpage );
44665    assert( iRight>=nRight || aContent[aRight[iRight]]>dbpage );
44666  }
44667
44668  *paRight = aLeft;
44669  *pnRight = iOut;
44670  memcpy(aLeft, aTmp, sizeof(aTmp[0])*iOut);
44671}
44672
44673/*
44674** Sort the elements in list aList using aContent[] as the sort key.
44675** Remove elements with duplicate keys, preferring to keep the
44676** larger aList[] values.
44677**
44678** The aList[] entries are indices into aContent[].  The values in
44679** aList[] are to be sorted so that for all J<K:
44680**
44681**      aContent[aList[J]] < aContent[aList[K]]
44682**
44683** For any X and Y such that
44684**
44685**      aContent[aList[X]] == aContent[aList[Y]]
44686**
44687** Keep the larger of the two values aList[X] and aList[Y] and discard
44688** the smaller.
44689*/
44690static void walMergesort(
44691  const u32 *aContent,            /* Pages in wal */
44692  ht_slot *aBuffer,               /* Buffer of at least *pnList items to use */
44693  ht_slot *aList,                 /* IN/OUT: List to sort */
44694  int *pnList                     /* IN/OUT: Number of elements in aList[] */
44695){
44696  struct Sublist {
44697    int nList;                    /* Number of elements in aList */
44698    ht_slot *aList;               /* Pointer to sub-list content */
44699  };
44700
44701  const int nList = *pnList;      /* Size of input list */
44702  int nMerge = 0;                 /* Number of elements in list aMerge */
44703  ht_slot *aMerge = 0;            /* List to be merged */
44704  int iList;                      /* Index into input list */
44705  int iSub = 0;                   /* Index into aSub array */
44706  struct Sublist aSub[13];        /* Array of sub-lists */
44707
44708  memset(aSub, 0, sizeof(aSub));
44709  assert( nList<=HASHTABLE_NPAGE && nList>0 );
44710  assert( HASHTABLE_NPAGE==(1<<(ArraySize(aSub)-1)) );
44711
44712  for(iList=0; iList<nList; iList++){
44713    nMerge = 1;
44714    aMerge = &aList[iList];
44715    for(iSub=0; iList & (1<<iSub); iSub++){
44716      struct Sublist *p = &aSub[iSub];
44717      assert( p->aList && p->nList<=(1<<iSub) );
44718      assert( p->aList==&aList[iList&~((2<<iSub)-1)] );
44719      walMerge(aContent, p->aList, p->nList, &aMerge, &nMerge, aBuffer);
44720    }
44721    aSub[iSub].aList = aMerge;
44722    aSub[iSub].nList = nMerge;
44723  }
44724
44725  for(iSub++; iSub<ArraySize(aSub); iSub++){
44726    if( nList & (1<<iSub) ){
44727      struct Sublist *p = &aSub[iSub];
44728      assert( p->nList<=(1<<iSub) );
44729      assert( p->aList==&aList[nList&~((2<<iSub)-1)] );
44730      walMerge(aContent, p->aList, p->nList, &aMerge, &nMerge, aBuffer);
44731    }
44732  }
44733  assert( aMerge==aList );
44734  *pnList = nMerge;
44735
44736#ifdef SQLITE_DEBUG
44737  {
44738    int i;
44739    for(i=1; i<*pnList; i++){
44740      assert( aContent[aList[i]] > aContent[aList[i-1]] );
44741    }
44742  }
44743#endif
44744}
44745
44746/*
44747** Free an iterator allocated by walIteratorInit().
44748*/
44749static void walIteratorFree(WalIterator *p){
44750  sqlite3ScratchFree(p);
44751}
44752
44753/*
44754** Construct a WalInterator object that can be used to loop over all
44755** pages in the WAL in ascending order. The caller must hold the checkpoint
44756** lock.
44757**
44758** On success, make *pp point to the newly allocated WalInterator object
44759** return SQLITE_OK. Otherwise, return an error code. If this routine
44760** returns an error, the value of *pp is undefined.
44761**
44762** The calling routine should invoke walIteratorFree() to destroy the
44763** WalIterator object when it has finished with it.
44764*/
44765static int walIteratorInit(Wal *pWal, WalIterator **pp){
44766  WalIterator *p;                 /* Return value */
44767  int nSegment;                   /* Number of segments to merge */
44768  u32 iLast;                      /* Last frame in log */
44769  int nByte;                      /* Number of bytes to allocate */
44770  int i;                          /* Iterator variable */
44771  ht_slot *aTmp;                  /* Temp space used by merge-sort */
44772  int rc = SQLITE_OK;             /* Return Code */
44773
44774  /* This routine only runs while holding the checkpoint lock. And
44775  ** it only runs if there is actually content in the log (mxFrame>0).
44776  */
44777  assert( pWal->ckptLock && pWal->hdr.mxFrame>0 );
44778  iLast = pWal->hdr.mxFrame;
44779
44780  /* Allocate space for the WalIterator object. */
44781  nSegment = walFramePage(iLast) + 1;
44782  nByte = sizeof(WalIterator)
44783        + (nSegment-1)*sizeof(struct WalSegment)
44784        + iLast*sizeof(ht_slot);
44785  p = (WalIterator *)sqlite3ScratchMalloc(nByte);
44786  if( !p ){
44787    return SQLITE_NOMEM;
44788  }
44789  memset(p, 0, nByte);
44790  p->nSegment = nSegment;
44791
44792  /* Allocate temporary space used by the merge-sort routine. This block
44793  ** of memory will be freed before this function returns.
44794  */
44795  aTmp = (ht_slot *)sqlite3ScratchMalloc(
44796      sizeof(ht_slot) * (iLast>HASHTABLE_NPAGE?HASHTABLE_NPAGE:iLast)
44797  );
44798  if( !aTmp ){
44799    rc = SQLITE_NOMEM;
44800  }
44801
44802  for(i=0; rc==SQLITE_OK && i<nSegment; i++){
44803    volatile ht_slot *aHash;
44804    u32 iZero;
44805    volatile u32 *aPgno;
44806
44807    rc = walHashGet(pWal, i, &aHash, &aPgno, &iZero);
44808    if( rc==SQLITE_OK ){
44809      int j;                      /* Counter variable */
44810      int nEntry;                 /* Number of entries in this segment */
44811      ht_slot *aIndex;            /* Sorted index for this segment */
44812
44813      aPgno++;
44814      if( (i+1)==nSegment ){
44815        nEntry = (int)(iLast - iZero);
44816      }else{
44817        nEntry = (int)((u32*)aHash - (u32*)aPgno);
44818      }
44819      aIndex = &((ht_slot *)&p->aSegment[p->nSegment])[iZero];
44820      iZero++;
44821
44822      for(j=0; j<nEntry; j++){
44823        aIndex[j] = (ht_slot)j;
44824      }
44825      walMergesort((u32 *)aPgno, aTmp, aIndex, &nEntry);
44826      p->aSegment[i].iZero = iZero;
44827      p->aSegment[i].nEntry = nEntry;
44828      p->aSegment[i].aIndex = aIndex;
44829      p->aSegment[i].aPgno = (u32 *)aPgno;
44830    }
44831  }
44832  sqlite3ScratchFree(aTmp);
44833
44834  if( rc!=SQLITE_OK ){
44835    walIteratorFree(p);
44836  }
44837  *pp = p;
44838  return rc;
44839}
44840
44841/*
44842** Attempt to obtain the exclusive WAL lock defined by parameters lockIdx and
44843** n. If the attempt fails and parameter xBusy is not NULL, then it is a
44844** busy-handler function. Invoke it and retry the lock until either the
44845** lock is successfully obtained or the busy-handler returns 0.
44846*/
44847static int walBusyLock(
44848  Wal *pWal,                      /* WAL connection */
44849  int (*xBusy)(void*),            /* Function to call when busy */
44850  void *pBusyArg,                 /* Context argument for xBusyHandler */
44851  int lockIdx,                    /* Offset of first byte to lock */
44852  int n                           /* Number of bytes to lock */
44853){
44854  int rc;
44855  do {
44856    rc = walLockExclusive(pWal, lockIdx, n);
44857  }while( xBusy && rc==SQLITE_BUSY && xBusy(pBusyArg) );
44858  return rc;
44859}
44860
44861/*
44862** The cache of the wal-index header must be valid to call this function.
44863** Return the page-size in bytes used by the database.
44864*/
44865static int walPagesize(Wal *pWal){
44866  return (pWal->hdr.szPage&0xfe00) + ((pWal->hdr.szPage&0x0001)<<16);
44867}
44868
44869/*
44870** Copy as much content as we can from the WAL back into the database file
44871** in response to an sqlite3_wal_checkpoint() request or the equivalent.
44872**
44873** The amount of information copies from WAL to database might be limited
44874** by active readers.  This routine will never overwrite a database page
44875** that a concurrent reader might be using.
44876**
44877** All I/O barrier operations (a.k.a fsyncs) occur in this routine when
44878** SQLite is in WAL-mode in synchronous=NORMAL.  That means that if
44879** checkpoints are always run by a background thread or background
44880** process, foreground threads will never block on a lengthy fsync call.
44881**
44882** Fsync is called on the WAL before writing content out of the WAL and
44883** into the database.  This ensures that if the new content is persistent
44884** in the WAL and can be recovered following a power-loss or hard reset.
44885**
44886** Fsync is also called on the database file if (and only if) the entire
44887** WAL content is copied into the database file.  This second fsync makes
44888** it safe to delete the WAL since the new content will persist in the
44889** database file.
44890**
44891** This routine uses and updates the nBackfill field of the wal-index header.
44892** This is the only routine tha will increase the value of nBackfill.
44893** (A WAL reset or recovery will revert nBackfill to zero, but not increase
44894** its value.)
44895**
44896** The caller must be holding sufficient locks to ensure that no other
44897** checkpoint is running (in any other thread or process) at the same
44898** time.
44899*/
44900static int walCheckpoint(
44901  Wal *pWal,                      /* Wal connection */
44902  int eMode,                      /* One of PASSIVE, FULL or RESTART */
44903  int (*xBusyCall)(void*),        /* Function to call when busy */
44904  void *pBusyArg,                 /* Context argument for xBusyHandler */
44905  int sync_flags,                 /* Flags for OsSync() (or 0) */
44906  u8 *zBuf                        /* Temporary buffer to use */
44907){
44908  int rc;                         /* Return code */
44909  int szPage;                     /* Database page-size */
44910  WalIterator *pIter = 0;         /* Wal iterator context */
44911  u32 iDbpage = 0;                /* Next database page to write */
44912  u32 iFrame = 0;                 /* Wal frame containing data for iDbpage */
44913  u32 mxSafeFrame;                /* Max frame that can be backfilled */
44914  u32 mxPage;                     /* Max database page to write */
44915  int i;                          /* Loop counter */
44916  volatile WalCkptInfo *pInfo;    /* The checkpoint status information */
44917  int (*xBusy)(void*) = 0;        /* Function to call when waiting for locks */
44918
44919  szPage = walPagesize(pWal);
44920  testcase( szPage<=32768 );
44921  testcase( szPage>=65536 );
44922  pInfo = walCkptInfo(pWal);
44923  if( pInfo->nBackfill>=pWal->hdr.mxFrame ) return SQLITE_OK;
44924
44925  /* Allocate the iterator */
44926  rc = walIteratorInit(pWal, &pIter);
44927  if( rc!=SQLITE_OK ){
44928    return rc;
44929  }
44930  assert( pIter );
44931
44932  if( eMode!=SQLITE_CHECKPOINT_PASSIVE ) xBusy = xBusyCall;
44933
44934  /* Compute in mxSafeFrame the index of the last frame of the WAL that is
44935  ** safe to write into the database.  Frames beyond mxSafeFrame might
44936  ** overwrite database pages that are in use by active readers and thus
44937  ** cannot be backfilled from the WAL.
44938  */
44939  mxSafeFrame = pWal->hdr.mxFrame;
44940  mxPage = pWal->hdr.nPage;
44941  for(i=1; i<WAL_NREADER; i++){
44942    u32 y = pInfo->aReadMark[i];
44943    if( mxSafeFrame>y ){
44944      assert( y<=pWal->hdr.mxFrame );
44945      rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(i), 1);
44946      if( rc==SQLITE_OK ){
44947        pInfo->aReadMark[i] = READMARK_NOT_USED;
44948        walUnlockExclusive(pWal, WAL_READ_LOCK(i), 1);
44949      }else if( rc==SQLITE_BUSY ){
44950        mxSafeFrame = y;
44951        xBusy = 0;
44952      }else{
44953        goto walcheckpoint_out;
44954      }
44955    }
44956  }
44957
44958  if( pInfo->nBackfill<mxSafeFrame
44959   && (rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(0), 1))==SQLITE_OK
44960  ){
44961    i64 nSize;                    /* Current size of database file */
44962    u32 nBackfill = pInfo->nBackfill;
44963
44964    /* Sync the WAL to disk */
44965    if( sync_flags ){
44966      rc = sqlite3OsSync(pWal->pWalFd, sync_flags);
44967    }
44968
44969    /* If the database file may grow as a result of this checkpoint, hint
44970    ** about the eventual size of the db file to the VFS layer.
44971    */
44972    if( rc==SQLITE_OK ){
44973      i64 nReq = ((i64)mxPage * szPage);
44974      rc = sqlite3OsFileSize(pWal->pDbFd, &nSize);
44975      if( rc==SQLITE_OK && nSize<nReq ){
44976        sqlite3OsFileControl(pWal->pDbFd, SQLITE_FCNTL_SIZE_HINT, &nReq);
44977      }
44978    }
44979
44980    /* Iterate through the contents of the WAL, copying data to the db file. */
44981    while( rc==SQLITE_OK && 0==walIteratorNext(pIter, &iDbpage, &iFrame) ){
44982      i64 iOffset;
44983      assert( walFramePgno(pWal, iFrame)==iDbpage );
44984      if( iFrame<=nBackfill || iFrame>mxSafeFrame || iDbpage>mxPage ) continue;
44985      iOffset = walFrameOffset(iFrame, szPage) + WAL_FRAME_HDRSIZE;
44986      /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL file */
44987      rc = sqlite3OsRead(pWal->pWalFd, zBuf, szPage, iOffset);
44988      if( rc!=SQLITE_OK ) break;
44989      iOffset = (iDbpage-1)*(i64)szPage;
44990      testcase( IS_BIG_INT(iOffset) );
44991      rc = sqlite3OsWrite(pWal->pDbFd, zBuf, szPage, iOffset);
44992      if( rc!=SQLITE_OK ) break;
44993    }
44994
44995    /* If work was actually accomplished... */
44996    if( rc==SQLITE_OK ){
44997      if( mxSafeFrame==walIndexHdr(pWal)->mxFrame ){
44998        i64 szDb = pWal->hdr.nPage*(i64)szPage;
44999        testcase( IS_BIG_INT(szDb) );
45000        rc = sqlite3OsTruncate(pWal->pDbFd, szDb);
45001        if( rc==SQLITE_OK && sync_flags ){
45002          rc = sqlite3OsSync(pWal->pDbFd, sync_flags);
45003        }
45004      }
45005      if( rc==SQLITE_OK ){
45006        pInfo->nBackfill = mxSafeFrame;
45007      }
45008    }
45009
45010    /* Release the reader lock held while backfilling */
45011    walUnlockExclusive(pWal, WAL_READ_LOCK(0), 1);
45012  }
45013
45014  if( rc==SQLITE_BUSY ){
45015    /* Reset the return code so as not to report a checkpoint failure
45016    ** just because there are active readers.  */
45017    rc = SQLITE_OK;
45018  }
45019
45020  /* If this is an SQLITE_CHECKPOINT_RESTART operation, and the entire wal
45021  ** file has been copied into the database file, then block until all
45022  ** readers have finished using the wal file. This ensures that the next
45023  ** process to write to the database restarts the wal file.
45024  */
45025  if( rc==SQLITE_OK && eMode!=SQLITE_CHECKPOINT_PASSIVE ){
45026    assert( pWal->writeLock );
45027    if( pInfo->nBackfill<pWal->hdr.mxFrame ){
45028      rc = SQLITE_BUSY;
45029    }else if( eMode==SQLITE_CHECKPOINT_RESTART ){
45030      assert( mxSafeFrame==pWal->hdr.mxFrame );
45031      rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(1), WAL_NREADER-1);
45032      if( rc==SQLITE_OK ){
45033        walUnlockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
45034      }
45035    }
45036  }
45037
45038 walcheckpoint_out:
45039  walIteratorFree(pIter);
45040  return rc;
45041}
45042
45043/*
45044** Close a connection to a log file.
45045*/
45046SQLITE_PRIVATE int sqlite3WalClose(
45047  Wal *pWal,                      /* Wal to close */
45048  int sync_flags,                 /* Flags to pass to OsSync() (or 0) */
45049  int nBuf,
45050  u8 *zBuf                        /* Buffer of at least nBuf bytes */
45051){
45052  int rc = SQLITE_OK;
45053  if( pWal ){
45054    int isDelete = 0;             /* True to unlink wal and wal-index files */
45055
45056    /* If an EXCLUSIVE lock can be obtained on the database file (using the
45057    ** ordinary, rollback-mode locking methods, this guarantees that the
45058    ** connection associated with this log file is the only connection to
45059    ** the database. In this case checkpoint the database and unlink both
45060    ** the wal and wal-index files.
45061    **
45062    ** The EXCLUSIVE lock is not released before returning.
45063    */
45064    rc = sqlite3OsLock(pWal->pDbFd, SQLITE_LOCK_EXCLUSIVE);
45065    if( rc==SQLITE_OK ){
45066      if( pWal->exclusiveMode==WAL_NORMAL_MODE ){
45067        pWal->exclusiveMode = WAL_EXCLUSIVE_MODE;
45068      }
45069      rc = sqlite3WalCheckpoint(
45070          pWal, SQLITE_CHECKPOINT_PASSIVE, 0, 0, sync_flags, nBuf, zBuf, 0, 0
45071      );
45072      if( rc==SQLITE_OK ){
45073        isDelete = 1;
45074      }
45075    }
45076
45077    walIndexClose(pWal, isDelete);
45078    sqlite3OsClose(pWal->pWalFd);
45079    if( isDelete ){
45080      sqlite3OsDelete(pWal->pVfs, pWal->zWalName, 0);
45081    }
45082    WALTRACE(("WAL%p: closed\n", pWal));
45083    sqlite3_free((void *)pWal->apWiData);
45084    sqlite3_free(pWal);
45085  }
45086  return rc;
45087}
45088
45089/*
45090** Try to read the wal-index header.  Return 0 on success and 1 if
45091** there is a problem.
45092**
45093** The wal-index is in shared memory.  Another thread or process might
45094** be writing the header at the same time this procedure is trying to
45095** read it, which might result in inconsistency.  A dirty read is detected
45096** by verifying that both copies of the header are the same and also by
45097** a checksum on the header.
45098**
45099** If and only if the read is consistent and the header is different from
45100** pWal->hdr, then pWal->hdr is updated to the content of the new header
45101** and *pChanged is set to 1.
45102**
45103** If the checksum cannot be verified return non-zero. If the header
45104** is read successfully and the checksum verified, return zero.
45105*/
45106static int walIndexTryHdr(Wal *pWal, int *pChanged){
45107  u32 aCksum[2];                  /* Checksum on the header content */
45108  WalIndexHdr h1, h2;             /* Two copies of the header content */
45109  WalIndexHdr volatile *aHdr;     /* Header in shared memory */
45110
45111  /* The first page of the wal-index must be mapped at this point. */
45112  assert( pWal->nWiData>0 && pWal->apWiData[0] );
45113
45114  /* Read the header. This might happen concurrently with a write to the
45115  ** same area of shared memory on a different CPU in a SMP,
45116  ** meaning it is possible that an inconsistent snapshot is read
45117  ** from the file. If this happens, return non-zero.
45118  **
45119  ** There are two copies of the header at the beginning of the wal-index.
45120  ** When reading, read [0] first then [1].  Writes are in the reverse order.
45121  ** Memory barriers are used to prevent the compiler or the hardware from
45122  ** reordering the reads and writes.
45123  */
45124  aHdr = walIndexHdr(pWal);
45125  memcpy(&h1, (void *)&aHdr[0], sizeof(h1));
45126  walShmBarrier(pWal);
45127  memcpy(&h2, (void *)&aHdr[1], sizeof(h2));
45128
45129  if( memcmp(&h1, &h2, sizeof(h1))!=0 ){
45130    return 1;   /* Dirty read */
45131  }
45132  if( h1.isInit==0 ){
45133    return 1;   /* Malformed header - probably all zeros */
45134  }
45135  walChecksumBytes(1, (u8*)&h1, sizeof(h1)-sizeof(h1.aCksum), 0, aCksum);
45136  if( aCksum[0]!=h1.aCksum[0] || aCksum[1]!=h1.aCksum[1] ){
45137    return 1;   /* Checksum does not match */
45138  }
45139
45140  if( memcmp(&pWal->hdr, &h1, sizeof(WalIndexHdr)) ){
45141    *pChanged = 1;
45142    memcpy(&pWal->hdr, &h1, sizeof(WalIndexHdr));
45143    pWal->szPage = (pWal->hdr.szPage&0xfe00) + ((pWal->hdr.szPage&0x0001)<<16);
45144    testcase( pWal->szPage<=32768 );
45145    testcase( pWal->szPage>=65536 );
45146  }
45147
45148  /* The header was successfully read. Return zero. */
45149  return 0;
45150}
45151
45152/*
45153** Read the wal-index header from the wal-index and into pWal->hdr.
45154** If the wal-header appears to be corrupt, try to reconstruct the
45155** wal-index from the WAL before returning.
45156**
45157** Set *pChanged to 1 if the wal-index header value in pWal->hdr is
45158** changed by this opertion.  If pWal->hdr is unchanged, set *pChanged
45159** to 0.
45160**
45161** If the wal-index header is successfully read, return SQLITE_OK.
45162** Otherwise an SQLite error code.
45163*/
45164static int walIndexReadHdr(Wal *pWal, int *pChanged){
45165  int rc;                         /* Return code */
45166  int badHdr;                     /* True if a header read failed */
45167  volatile u32 *page0;            /* Chunk of wal-index containing header */
45168
45169  /* Ensure that page 0 of the wal-index (the page that contains the
45170  ** wal-index header) is mapped. Return early if an error occurs here.
45171  */
45172  assert( pChanged );
45173  rc = walIndexPage(pWal, 0, &page0);
45174  if( rc!=SQLITE_OK ){
45175    return rc;
45176  };
45177  assert( page0 || pWal->writeLock==0 );
45178
45179  /* If the first page of the wal-index has been mapped, try to read the
45180  ** wal-index header immediately, without holding any lock. This usually
45181  ** works, but may fail if the wal-index header is corrupt or currently
45182  ** being modified by another thread or process.
45183  */
45184  badHdr = (page0 ? walIndexTryHdr(pWal, pChanged) : 1);
45185
45186  /* If the first attempt failed, it might have been due to a race
45187  ** with a writer.  So get a WRITE lock and try again.
45188  */
45189  assert( badHdr==0 || pWal->writeLock==0 );
45190  if( badHdr && SQLITE_OK==(rc = walLockExclusive(pWal, WAL_WRITE_LOCK, 1)) ){
45191    pWal->writeLock = 1;
45192    if( SQLITE_OK==(rc = walIndexPage(pWal, 0, &page0)) ){
45193      badHdr = walIndexTryHdr(pWal, pChanged);
45194      if( badHdr ){
45195        /* If the wal-index header is still malformed even while holding
45196        ** a WRITE lock, it can only mean that the header is corrupted and
45197        ** needs to be reconstructed.  So run recovery to do exactly that.
45198        */
45199        rc = walIndexRecover(pWal);
45200        *pChanged = 1;
45201      }
45202    }
45203    pWal->writeLock = 0;
45204    walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
45205  }
45206
45207  /* If the header is read successfully, check the version number to make
45208  ** sure the wal-index was not constructed with some future format that
45209  ** this version of SQLite cannot understand.
45210  */
45211  if( badHdr==0 && pWal->hdr.iVersion!=WALINDEX_MAX_VERSION ){
45212    rc = SQLITE_CANTOPEN_BKPT;
45213  }
45214
45215  return rc;
45216}
45217
45218/*
45219** This is the value that walTryBeginRead returns when it needs to
45220** be retried.
45221*/
45222#define WAL_RETRY  (-1)
45223
45224/*
45225** Attempt to start a read transaction.  This might fail due to a race or
45226** other transient condition.  When that happens, it returns WAL_RETRY to
45227** indicate to the caller that it is safe to retry immediately.
45228**
45229** On success return SQLITE_OK.  On a permanent failure (such an
45230** I/O error or an SQLITE_BUSY because another process is running
45231** recovery) return a positive error code.
45232**
45233** The useWal parameter is true to force the use of the WAL and disable
45234** the case where the WAL is bypassed because it has been completely
45235** checkpointed.  If useWal==0 then this routine calls walIndexReadHdr()
45236** to make a copy of the wal-index header into pWal->hdr.  If the
45237** wal-index header has changed, *pChanged is set to 1 (as an indication
45238** to the caller that the local paget cache is obsolete and needs to be
45239** flushed.)  When useWal==1, the wal-index header is assumed to already
45240** be loaded and the pChanged parameter is unused.
45241**
45242** The caller must set the cnt parameter to the number of prior calls to
45243** this routine during the current read attempt that returned WAL_RETRY.
45244** This routine will start taking more aggressive measures to clear the
45245** race conditions after multiple WAL_RETRY returns, and after an excessive
45246** number of errors will ultimately return SQLITE_PROTOCOL.  The
45247** SQLITE_PROTOCOL return indicates that some other process has gone rogue
45248** and is not honoring the locking protocol.  There is a vanishingly small
45249** chance that SQLITE_PROTOCOL could be returned because of a run of really
45250** bad luck when there is lots of contention for the wal-index, but that
45251** possibility is so small that it can be safely neglected, we believe.
45252**
45253** On success, this routine obtains a read lock on
45254** WAL_READ_LOCK(pWal->readLock).  The pWal->readLock integer is
45255** in the range 0 <= pWal->readLock < WAL_NREADER.  If pWal->readLock==(-1)
45256** that means the Wal does not hold any read lock.  The reader must not
45257** access any database page that is modified by a WAL frame up to and
45258** including frame number aReadMark[pWal->readLock].  The reader will
45259** use WAL frames up to and including pWal->hdr.mxFrame if pWal->readLock>0
45260** Or if pWal->readLock==0, then the reader will ignore the WAL
45261** completely and get all content directly from the database file.
45262** If the useWal parameter is 1 then the WAL will never be ignored and
45263** this routine will always set pWal->readLock>0 on success.
45264** When the read transaction is completed, the caller must release the
45265** lock on WAL_READ_LOCK(pWal->readLock) and set pWal->readLock to -1.
45266**
45267** This routine uses the nBackfill and aReadMark[] fields of the header
45268** to select a particular WAL_READ_LOCK() that strives to let the
45269** checkpoint process do as much work as possible.  This routine might
45270** update values of the aReadMark[] array in the header, but if it does
45271** so it takes care to hold an exclusive lock on the corresponding
45272** WAL_READ_LOCK() while changing values.
45273*/
45274static int walTryBeginRead(Wal *pWal, int *pChanged, int useWal, int cnt){
45275  volatile WalCkptInfo *pInfo;    /* Checkpoint information in wal-index */
45276  u32 mxReadMark;                 /* Largest aReadMark[] value */
45277  int mxI;                        /* Index of largest aReadMark[] value */
45278  int i;                          /* Loop counter */
45279  int rc = SQLITE_OK;             /* Return code  */
45280
45281  assert( pWal->readLock<0 );     /* Not currently locked */
45282
45283  /* Take steps to avoid spinning forever if there is a protocol error.
45284  **
45285  ** Circumstances that cause a RETRY should only last for the briefest
45286  ** instances of time.  No I/O or other system calls are done while the
45287  ** locks are held, so the locks should not be held for very long. But
45288  ** if we are unlucky, another process that is holding a lock might get
45289  ** paged out or take a page-fault that is time-consuming to resolve,
45290  ** during the few nanoseconds that it is holding the lock.  In that case,
45291  ** it might take longer than normal for the lock to free.
45292  **
45293  ** After 5 RETRYs, we begin calling sqlite3OsSleep().  The first few
45294  ** calls to sqlite3OsSleep() have a delay of 1 microsecond.  Really this
45295  ** is more of a scheduler yield than an actual delay.  But on the 10th
45296  ** an subsequent retries, the delays start becoming longer and longer,
45297  ** so that on the 100th (and last) RETRY we delay for 21 milliseconds.
45298  ** The total delay time before giving up is less than 1 second.
45299  */
45300  if( cnt>5 ){
45301    int nDelay = 1;                      /* Pause time in microseconds */
45302    if( cnt>100 ){
45303      VVA_ONLY( pWal->lockError = 1; )
45304      return SQLITE_PROTOCOL;
45305    }
45306    if( cnt>=10 ) nDelay = (cnt-9)*238;  /* Max delay 21ms. Total delay 996ms */
45307    sqlite3OsSleep(pWal->pVfs, nDelay);
45308  }
45309
45310  if( !useWal ){
45311    rc = walIndexReadHdr(pWal, pChanged);
45312    if( rc==SQLITE_BUSY ){
45313      /* If there is not a recovery running in another thread or process
45314      ** then convert BUSY errors to WAL_RETRY.  If recovery is known to
45315      ** be running, convert BUSY to BUSY_RECOVERY.  There is a race here
45316      ** which might cause WAL_RETRY to be returned even if BUSY_RECOVERY
45317      ** would be technically correct.  But the race is benign since with
45318      ** WAL_RETRY this routine will be called again and will probably be
45319      ** right on the second iteration.
45320      */
45321      if( pWal->apWiData[0]==0 ){
45322        /* This branch is taken when the xShmMap() method returns SQLITE_BUSY.
45323        ** We assume this is a transient condition, so return WAL_RETRY. The
45324        ** xShmMap() implementation used by the default unix and win32 VFS
45325        ** modules may return SQLITE_BUSY due to a race condition in the
45326        ** code that determines whether or not the shared-memory region
45327        ** must be zeroed before the requested page is returned.
45328        */
45329        rc = WAL_RETRY;
45330      }else if( SQLITE_OK==(rc = walLockShared(pWal, WAL_RECOVER_LOCK)) ){
45331        walUnlockShared(pWal, WAL_RECOVER_LOCK);
45332        rc = WAL_RETRY;
45333      }else if( rc==SQLITE_BUSY ){
45334        rc = SQLITE_BUSY_RECOVERY;
45335      }
45336    }
45337    if( rc!=SQLITE_OK ){
45338      return rc;
45339    }
45340  }
45341
45342  pInfo = walCkptInfo(pWal);
45343  if( !useWal && pInfo->nBackfill==pWal->hdr.mxFrame ){
45344    /* The WAL has been completely backfilled (or it is empty).
45345    ** and can be safely ignored.
45346    */
45347    rc = walLockShared(pWal, WAL_READ_LOCK(0));
45348    walShmBarrier(pWal);
45349    if( rc==SQLITE_OK ){
45350      if( memcmp((void *)walIndexHdr(pWal), &pWal->hdr, sizeof(WalIndexHdr)) ){
45351        /* It is not safe to allow the reader to continue here if frames
45352        ** may have been appended to the log before READ_LOCK(0) was obtained.
45353        ** When holding READ_LOCK(0), the reader ignores the entire log file,
45354        ** which implies that the database file contains a trustworthy
45355        ** snapshoT. Since holding READ_LOCK(0) prevents a checkpoint from
45356        ** happening, this is usually correct.
45357        **
45358        ** However, if frames have been appended to the log (or if the log
45359        ** is wrapped and written for that matter) before the READ_LOCK(0)
45360        ** is obtained, that is not necessarily true. A checkpointer may
45361        ** have started to backfill the appended frames but crashed before
45362        ** it finished. Leaving a corrupt image in the database file.
45363        */
45364        walUnlockShared(pWal, WAL_READ_LOCK(0));
45365        return WAL_RETRY;
45366      }
45367      pWal->readLock = 0;
45368      return SQLITE_OK;
45369    }else if( rc!=SQLITE_BUSY ){
45370      return rc;
45371    }
45372  }
45373
45374  /* If we get this far, it means that the reader will want to use
45375  ** the WAL to get at content from recent commits.  The job now is
45376  ** to select one of the aReadMark[] entries that is closest to
45377  ** but not exceeding pWal->hdr.mxFrame and lock that entry.
45378  */
45379  mxReadMark = 0;
45380  mxI = 0;
45381  for(i=1; i<WAL_NREADER; i++){
45382    u32 thisMark = pInfo->aReadMark[i];
45383    if( mxReadMark<=thisMark && thisMark<=pWal->hdr.mxFrame ){
45384      assert( thisMark!=READMARK_NOT_USED );
45385      mxReadMark = thisMark;
45386      mxI = i;
45387    }
45388  }
45389  /* There was once an "if" here. The extra "{" is to preserve indentation. */
45390  {
45391    if( mxReadMark < pWal->hdr.mxFrame || mxI==0 ){
45392      for(i=1; i<WAL_NREADER; i++){
45393        rc = walLockExclusive(pWal, WAL_READ_LOCK(i), 1);
45394        if( rc==SQLITE_OK ){
45395          mxReadMark = pInfo->aReadMark[i] = pWal->hdr.mxFrame;
45396          mxI = i;
45397          walUnlockExclusive(pWal, WAL_READ_LOCK(i), 1);
45398          break;
45399        }else if( rc!=SQLITE_BUSY ){
45400          return rc;
45401        }
45402      }
45403    }
45404    if( mxI==0 ){
45405      assert( rc==SQLITE_BUSY );
45406      return WAL_RETRY;
45407    }
45408
45409    rc = walLockShared(pWal, WAL_READ_LOCK(mxI));
45410    if( rc ){
45411      return rc==SQLITE_BUSY ? WAL_RETRY : rc;
45412    }
45413    /* Now that the read-lock has been obtained, check that neither the
45414    ** value in the aReadMark[] array or the contents of the wal-index
45415    ** header have changed.
45416    **
45417    ** It is necessary to check that the wal-index header did not change
45418    ** between the time it was read and when the shared-lock was obtained
45419    ** on WAL_READ_LOCK(mxI) was obtained to account for the possibility
45420    ** that the log file may have been wrapped by a writer, or that frames
45421    ** that occur later in the log than pWal->hdr.mxFrame may have been
45422    ** copied into the database by a checkpointer. If either of these things
45423    ** happened, then reading the database with the current value of
45424    ** pWal->hdr.mxFrame risks reading a corrupted snapshot. So, retry
45425    ** instead.
45426    **
45427    ** This does not guarantee that the copy of the wal-index header is up to
45428    ** date before proceeding. That would not be possible without somehow
45429    ** blocking writers. It only guarantees that a dangerous checkpoint or
45430    ** log-wrap (either of which would require an exclusive lock on
45431    ** WAL_READ_LOCK(mxI)) has not occurred since the snapshot was valid.
45432    */
45433    walShmBarrier(pWal);
45434    if( pInfo->aReadMark[mxI]!=mxReadMark
45435     || memcmp((void *)walIndexHdr(pWal), &pWal->hdr, sizeof(WalIndexHdr))
45436    ){
45437      walUnlockShared(pWal, WAL_READ_LOCK(mxI));
45438      return WAL_RETRY;
45439    }else{
45440      assert( mxReadMark<=pWal->hdr.mxFrame );
45441      pWal->readLock = (i16)mxI;
45442    }
45443  }
45444  return rc;
45445}
45446
45447/*
45448** Begin a read transaction on the database.
45449**
45450** This routine used to be called sqlite3OpenSnapshot() and with good reason:
45451** it takes a snapshot of the state of the WAL and wal-index for the current
45452** instant in time.  The current thread will continue to use this snapshot.
45453** Other threads might append new content to the WAL and wal-index but
45454** that extra content is ignored by the current thread.
45455**
45456** If the database contents have changes since the previous read
45457** transaction, then *pChanged is set to 1 before returning.  The
45458** Pager layer will use this to know that is cache is stale and
45459** needs to be flushed.
45460*/
45461SQLITE_PRIVATE int sqlite3WalBeginReadTransaction(Wal *pWal, int *pChanged){
45462  int rc;                         /* Return code */
45463  int cnt = 0;                    /* Number of TryBeginRead attempts */
45464
45465  do{
45466    rc = walTryBeginRead(pWal, pChanged, 0, ++cnt);
45467  }while( rc==WAL_RETRY );
45468  testcase( (rc&0xff)==SQLITE_BUSY );
45469  testcase( (rc&0xff)==SQLITE_IOERR );
45470  testcase( rc==SQLITE_PROTOCOL );
45471  testcase( rc==SQLITE_OK );
45472  return rc;
45473}
45474
45475/*
45476** Finish with a read transaction.  All this does is release the
45477** read-lock.
45478*/
45479SQLITE_PRIVATE void sqlite3WalEndReadTransaction(Wal *pWal){
45480  sqlite3WalEndWriteTransaction(pWal);
45481  if( pWal->readLock>=0 ){
45482    walUnlockShared(pWal, WAL_READ_LOCK(pWal->readLock));
45483    pWal->readLock = -1;
45484  }
45485}
45486
45487/*
45488** Read a page from the WAL, if it is present in the WAL and if the
45489** current read transaction is configured to use the WAL.
45490**
45491** The *pInWal is set to 1 if the requested page is in the WAL and
45492** has been loaded.  Or *pInWal is set to 0 if the page was not in
45493** the WAL and needs to be read out of the database.
45494*/
45495SQLITE_PRIVATE int sqlite3WalRead(
45496  Wal *pWal,                      /* WAL handle */
45497  Pgno pgno,                      /* Database page number to read data for */
45498  int *pInWal,                    /* OUT: True if data is read from WAL */
45499  int nOut,                       /* Size of buffer pOut in bytes */
45500  u8 *pOut                        /* Buffer to write page data to */
45501){
45502  u32 iRead = 0;                  /* If !=0, WAL frame to return data from */
45503  u32 iLast = pWal->hdr.mxFrame;  /* Last page in WAL for this reader */
45504  int iHash;                      /* Used to loop through N hash tables */
45505
45506  /* This routine is only be called from within a read transaction. */
45507  assert( pWal->readLock>=0 || pWal->lockError );
45508
45509  /* If the "last page" field of the wal-index header snapshot is 0, then
45510  ** no data will be read from the wal under any circumstances. Return early
45511  ** in this case as an optimization.  Likewise, if pWal->readLock==0,
45512  ** then the WAL is ignored by the reader so return early, as if the
45513  ** WAL were empty.
45514  */
45515  if( iLast==0 || pWal->readLock==0 ){
45516    *pInWal = 0;
45517    return SQLITE_OK;
45518  }
45519
45520  /* Search the hash table or tables for an entry matching page number
45521  ** pgno. Each iteration of the following for() loop searches one
45522  ** hash table (each hash table indexes up to HASHTABLE_NPAGE frames).
45523  **
45524  ** This code might run concurrently to the code in walIndexAppend()
45525  ** that adds entries to the wal-index (and possibly to this hash
45526  ** table). This means the value just read from the hash
45527  ** slot (aHash[iKey]) may have been added before or after the
45528  ** current read transaction was opened. Values added after the
45529  ** read transaction was opened may have been written incorrectly -
45530  ** i.e. these slots may contain garbage data. However, we assume
45531  ** that any slots written before the current read transaction was
45532  ** opened remain unmodified.
45533  **
45534  ** For the reasons above, the if(...) condition featured in the inner
45535  ** loop of the following block is more stringent that would be required
45536  ** if we had exclusive access to the hash-table:
45537  **
45538  **   (aPgno[iFrame]==pgno):
45539  **     This condition filters out normal hash-table collisions.
45540  **
45541  **   (iFrame<=iLast):
45542  **     This condition filters out entries that were added to the hash
45543  **     table after the current read-transaction had started.
45544  */
45545  for(iHash=walFramePage(iLast); iHash>=0 && iRead==0; iHash--){
45546    volatile ht_slot *aHash;      /* Pointer to hash table */
45547    volatile u32 *aPgno;          /* Pointer to array of page numbers */
45548    u32 iZero;                    /* Frame number corresponding to aPgno[0] */
45549    int iKey;                     /* Hash slot index */
45550    int nCollide;                 /* Number of hash collisions remaining */
45551    int rc;                       /* Error code */
45552
45553    rc = walHashGet(pWal, iHash, &aHash, &aPgno, &iZero);
45554    if( rc!=SQLITE_OK ){
45555      return rc;
45556    }
45557    nCollide = HASHTABLE_NSLOT;
45558    for(iKey=walHash(pgno); aHash[iKey]; iKey=walNextHash(iKey)){
45559      u32 iFrame = aHash[iKey] + iZero;
45560      if( iFrame<=iLast && aPgno[aHash[iKey]]==pgno ){
45561        assert( iFrame>iRead );
45562        iRead = iFrame;
45563      }
45564      if( (nCollide--)==0 ){
45565        return SQLITE_CORRUPT_BKPT;
45566      }
45567    }
45568  }
45569
45570#ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
45571  /* If expensive assert() statements are available, do a linear search
45572  ** of the wal-index file content. Make sure the results agree with the
45573  ** result obtained using the hash indexes above.  */
45574  {
45575    u32 iRead2 = 0;
45576    u32 iTest;
45577    for(iTest=iLast; iTest>0; iTest--){
45578      if( walFramePgno(pWal, iTest)==pgno ){
45579        iRead2 = iTest;
45580        break;
45581      }
45582    }
45583    assert( iRead==iRead2 );
45584  }
45585#endif
45586
45587  /* If iRead is non-zero, then it is the log frame number that contains the
45588  ** required page. Read and return data from the log file.
45589  */
45590  if( iRead ){
45591    int sz;
45592    i64 iOffset;
45593    sz = pWal->hdr.szPage;
45594    sz = (pWal->hdr.szPage&0xfe00) + ((pWal->hdr.szPage&0x0001)<<16);
45595    testcase( sz<=32768 );
45596    testcase( sz>=65536 );
45597    iOffset = walFrameOffset(iRead, sz) + WAL_FRAME_HDRSIZE;
45598    *pInWal = 1;
45599    /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL */
45600    return sqlite3OsRead(pWal->pWalFd, pOut, nOut, iOffset);
45601  }
45602
45603  *pInWal = 0;
45604  return SQLITE_OK;
45605}
45606
45607
45608/*
45609** Return the size of the database in pages (or zero, if unknown).
45610*/
45611SQLITE_PRIVATE Pgno sqlite3WalDbsize(Wal *pWal){
45612  if( pWal && ALWAYS(pWal->readLock>=0) ){
45613    return pWal->hdr.nPage;
45614  }
45615  return 0;
45616}
45617
45618
45619/*
45620** This function starts a write transaction on the WAL.
45621**
45622** A read transaction must have already been started by a prior call
45623** to sqlite3WalBeginReadTransaction().
45624**
45625** If another thread or process has written into the database since
45626** the read transaction was started, then it is not possible for this
45627** thread to write as doing so would cause a fork.  So this routine
45628** returns SQLITE_BUSY in that case and no write transaction is started.
45629**
45630** There can only be a single writer active at a time.
45631*/
45632SQLITE_PRIVATE int sqlite3WalBeginWriteTransaction(Wal *pWal){
45633  int rc;
45634
45635  /* Cannot start a write transaction without first holding a read
45636  ** transaction. */
45637  assert( pWal->readLock>=0 );
45638
45639  if( pWal->readOnly ){
45640    return SQLITE_READONLY;
45641  }
45642
45643  /* Only one writer allowed at a time.  Get the write lock.  Return
45644  ** SQLITE_BUSY if unable.
45645  */
45646  rc = walLockExclusive(pWal, WAL_WRITE_LOCK, 1);
45647  if( rc ){
45648    return rc;
45649  }
45650  pWal->writeLock = 1;
45651
45652  /* If another connection has written to the database file since the
45653  ** time the read transaction on this connection was started, then
45654  ** the write is disallowed.
45655  */
45656  if( memcmp(&pWal->hdr, (void *)walIndexHdr(pWal), sizeof(WalIndexHdr))!=0 ){
45657    walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
45658    pWal->writeLock = 0;
45659    rc = SQLITE_BUSY;
45660  }
45661
45662  return rc;
45663}
45664
45665/*
45666** End a write transaction.  The commit has already been done.  This
45667** routine merely releases the lock.
45668*/
45669SQLITE_PRIVATE int sqlite3WalEndWriteTransaction(Wal *pWal){
45670  if( pWal->writeLock ){
45671    walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
45672    pWal->writeLock = 0;
45673  }
45674  return SQLITE_OK;
45675}
45676
45677/*
45678** If any data has been written (but not committed) to the log file, this
45679** function moves the write-pointer back to the start of the transaction.
45680**
45681** Additionally, the callback function is invoked for each frame written
45682** to the WAL since the start of the transaction. If the callback returns
45683** other than SQLITE_OK, it is not invoked again and the error code is
45684** returned to the caller.
45685**
45686** Otherwise, if the callback function does not return an error, this
45687** function returns SQLITE_OK.
45688*/
45689SQLITE_PRIVATE int sqlite3WalUndo(Wal *pWal, int (*xUndo)(void *, Pgno), void *pUndoCtx){
45690  int rc = SQLITE_OK;
45691  if( ALWAYS(pWal->writeLock) ){
45692    Pgno iMax = pWal->hdr.mxFrame;
45693    Pgno iFrame;
45694
45695    /* Restore the clients cache of the wal-index header to the state it
45696    ** was in before the client began writing to the database.
45697    */
45698    memcpy(&pWal->hdr, (void *)walIndexHdr(pWal), sizeof(WalIndexHdr));
45699
45700    for(iFrame=pWal->hdr.mxFrame+1;
45701        ALWAYS(rc==SQLITE_OK) && iFrame<=iMax;
45702        iFrame++
45703    ){
45704      /* This call cannot fail. Unless the page for which the page number
45705      ** is passed as the second argument is (a) in the cache and
45706      ** (b) has an outstanding reference, then xUndo is either a no-op
45707      ** (if (a) is false) or simply expels the page from the cache (if (b)
45708      ** is false).
45709      **
45710      ** If the upper layer is doing a rollback, it is guaranteed that there
45711      ** are no outstanding references to any page other than page 1. And
45712      ** page 1 is never written to the log until the transaction is
45713      ** committed. As a result, the call to xUndo may not fail.
45714      */
45715      assert( walFramePgno(pWal, iFrame)!=1 );
45716      rc = xUndo(pUndoCtx, walFramePgno(pWal, iFrame));
45717    }
45718    walCleanupHash(pWal);
45719  }
45720  assert( rc==SQLITE_OK );
45721  return rc;
45722}
45723
45724/*
45725** Argument aWalData must point to an array of WAL_SAVEPOINT_NDATA u32
45726** values. This function populates the array with values required to
45727** "rollback" the write position of the WAL handle back to the current
45728** point in the event of a savepoint rollback (via WalSavepointUndo()).
45729*/
45730SQLITE_PRIVATE void sqlite3WalSavepoint(Wal *pWal, u32 *aWalData){
45731  assert( pWal->writeLock );
45732  aWalData[0] = pWal->hdr.mxFrame;
45733  aWalData[1] = pWal->hdr.aFrameCksum[0];
45734  aWalData[2] = pWal->hdr.aFrameCksum[1];
45735  aWalData[3] = pWal->nCkpt;
45736}
45737
45738/*
45739** Move the write position of the WAL back to the point identified by
45740** the values in the aWalData[] array. aWalData must point to an array
45741** of WAL_SAVEPOINT_NDATA u32 values that has been previously populated
45742** by a call to WalSavepoint().
45743*/
45744SQLITE_PRIVATE int sqlite3WalSavepointUndo(Wal *pWal, u32 *aWalData){
45745  int rc = SQLITE_OK;
45746
45747  assert( pWal->writeLock );
45748  assert( aWalData[3]!=pWal->nCkpt || aWalData[0]<=pWal->hdr.mxFrame );
45749
45750  if( aWalData[3]!=pWal->nCkpt ){
45751    /* This savepoint was opened immediately after the write-transaction
45752    ** was started. Right after that, the writer decided to wrap around
45753    ** to the start of the log. Update the savepoint values to match.
45754    */
45755    aWalData[0] = 0;
45756    aWalData[3] = pWal->nCkpt;
45757  }
45758
45759  if( aWalData[0]<pWal->hdr.mxFrame ){
45760    pWal->hdr.mxFrame = aWalData[0];
45761    pWal->hdr.aFrameCksum[0] = aWalData[1];
45762    pWal->hdr.aFrameCksum[1] = aWalData[2];
45763    walCleanupHash(pWal);
45764  }
45765
45766  return rc;
45767}
45768
45769/*
45770** This function is called just before writing a set of frames to the log
45771** file (see sqlite3WalFrames()). It checks to see if, instead of appending
45772** to the current log file, it is possible to overwrite the start of the
45773** existing log file with the new frames (i.e. "reset" the log). If so,
45774** it sets pWal->hdr.mxFrame to 0. Otherwise, pWal->hdr.mxFrame is left
45775** unchanged.
45776**
45777** SQLITE_OK is returned if no error is encountered (regardless of whether
45778** or not pWal->hdr.mxFrame is modified). An SQLite error code is returned
45779** if an error occurs.
45780*/
45781static int walRestartLog(Wal *pWal){
45782  int rc = SQLITE_OK;
45783  int cnt;
45784
45785  if( pWal->readLock==0 ){
45786    volatile WalCkptInfo *pInfo = walCkptInfo(pWal);
45787    assert( pInfo->nBackfill==pWal->hdr.mxFrame );
45788    if( pInfo->nBackfill>0 ){
45789      u32 salt1;
45790      sqlite3_randomness(4, &salt1);
45791      rc = walLockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
45792      if( rc==SQLITE_OK ){
45793        /* If all readers are using WAL_READ_LOCK(0) (in other words if no
45794        ** readers are currently using the WAL), then the transactions
45795        ** frames will overwrite the start of the existing log. Update the
45796        ** wal-index header to reflect this.
45797        **
45798        ** In theory it would be Ok to update the cache of the header only
45799        ** at this point. But updating the actual wal-index header is also
45800        ** safe and means there is no special case for sqlite3WalUndo()
45801        ** to handle if this transaction is rolled back.
45802        */
45803        int i;                    /* Loop counter */
45804        u32 *aSalt = pWal->hdr.aSalt;       /* Big-endian salt values */
45805        pWal->nCkpt++;
45806        pWal->hdr.mxFrame = 0;
45807        sqlite3Put4byte((u8*)&aSalt[0], 1 + sqlite3Get4byte((u8*)&aSalt[0]));
45808        aSalt[1] = salt1;
45809        walIndexWriteHdr(pWal);
45810        pInfo->nBackfill = 0;
45811        for(i=1; i<WAL_NREADER; i++) pInfo->aReadMark[i] = READMARK_NOT_USED;
45812        assert( pInfo->aReadMark[0]==0 );
45813        walUnlockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
45814      }else if( rc!=SQLITE_BUSY ){
45815        return rc;
45816      }
45817    }
45818    walUnlockShared(pWal, WAL_READ_LOCK(0));
45819    pWal->readLock = -1;
45820    cnt = 0;
45821    do{
45822      int notUsed;
45823      rc = walTryBeginRead(pWal, &notUsed, 1, ++cnt);
45824    }while( rc==WAL_RETRY );
45825    assert( (rc&0xff)!=SQLITE_BUSY ); /* BUSY not possible when useWal==1 */
45826    testcase( (rc&0xff)==SQLITE_IOERR );
45827    testcase( rc==SQLITE_PROTOCOL );
45828    testcase( rc==SQLITE_OK );
45829  }
45830  return rc;
45831}
45832
45833/*
45834** Write a set of frames to the log. The caller must hold the write-lock
45835** on the log file (obtained using sqlite3WalBeginWriteTransaction()).
45836*/
45837SQLITE_PRIVATE int sqlite3WalFrames(
45838  Wal *pWal,                      /* Wal handle to write to */
45839  int szPage,                     /* Database page-size in bytes */
45840  PgHdr *pList,                   /* List of dirty pages to write */
45841  Pgno nTruncate,                 /* Database size after this commit */
45842  int isCommit,                   /* True if this is a commit */
45843  int sync_flags                  /* Flags to pass to OsSync() (or 0) */
45844){
45845  int rc;                         /* Used to catch return codes */
45846  u32 iFrame;                     /* Next frame address */
45847  u8 aFrame[WAL_FRAME_HDRSIZE];   /* Buffer to assemble frame-header in */
45848  PgHdr *p;                       /* Iterator to run through pList with. */
45849  PgHdr *pLast = 0;               /* Last frame in list */
45850  int nLast = 0;                  /* Number of extra copies of last page */
45851
45852  assert( pList );
45853  assert( pWal->writeLock );
45854
45855#if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
45856  { int cnt; for(cnt=0, p=pList; p; p=p->pDirty, cnt++){}
45857    WALTRACE(("WAL%p: frame write begin. %d frames. mxFrame=%d. %s\n",
45858              pWal, cnt, pWal->hdr.mxFrame, isCommit ? "Commit" : "Spill"));
45859  }
45860#endif
45861
45862  /* See if it is possible to write these frames into the start of the
45863  ** log file, instead of appending to it at pWal->hdr.mxFrame.
45864  */
45865  if( SQLITE_OK!=(rc = walRestartLog(pWal)) ){
45866    return rc;
45867  }
45868
45869  /* If this is the first frame written into the log, write the WAL
45870  ** header to the start of the WAL file. See comments at the top of
45871  ** this source file for a description of the WAL header format.
45872  */
45873  iFrame = pWal->hdr.mxFrame;
45874  if( iFrame==0 ){
45875    u8 aWalHdr[WAL_HDRSIZE];      /* Buffer to assemble wal-header in */
45876    u32 aCksum[2];                /* Checksum for wal-header */
45877
45878    sqlite3Put4byte(&aWalHdr[0], (WAL_MAGIC | SQLITE_BIGENDIAN));
45879    sqlite3Put4byte(&aWalHdr[4], WAL_MAX_VERSION);
45880    sqlite3Put4byte(&aWalHdr[8], szPage);
45881    sqlite3Put4byte(&aWalHdr[12], pWal->nCkpt);
45882    sqlite3_randomness(8, pWal->hdr.aSalt);
45883    memcpy(&aWalHdr[16], pWal->hdr.aSalt, 8);
45884    walChecksumBytes(1, aWalHdr, WAL_HDRSIZE-2*4, 0, aCksum);
45885    sqlite3Put4byte(&aWalHdr[24], aCksum[0]);
45886    sqlite3Put4byte(&aWalHdr[28], aCksum[1]);
45887
45888    pWal->szPage = szPage;
45889    pWal->hdr.bigEndCksum = SQLITE_BIGENDIAN;
45890    pWal->hdr.aFrameCksum[0] = aCksum[0];
45891    pWal->hdr.aFrameCksum[1] = aCksum[1];
45892
45893    rc = sqlite3OsWrite(pWal->pWalFd, aWalHdr, sizeof(aWalHdr), 0);
45894    WALTRACE(("WAL%p: wal-header write %s\n", pWal, rc ? "failed" : "ok"));
45895    if( rc!=SQLITE_OK ){
45896      return rc;
45897    }
45898  }
45899  assert( (int)pWal->szPage==szPage );
45900
45901  /* Write the log file. */
45902  for(p=pList; p; p=p->pDirty){
45903    u32 nDbsize;                  /* Db-size field for frame header */
45904    i64 iOffset;                  /* Write offset in log file */
45905    void *pData;
45906
45907    iOffset = walFrameOffset(++iFrame, szPage);
45908    /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL */
45909
45910    /* Populate and write the frame header */
45911    nDbsize = (isCommit && p->pDirty==0) ? nTruncate : 0;
45912#if defined(SQLITE_HAS_CODEC)
45913    if( (pData = sqlite3PagerCodec(p))==0 ) return SQLITE_NOMEM;
45914#else
45915    pData = p->pData;
45916#endif
45917    walEncodeFrame(pWal, p->pgno, nDbsize, pData, aFrame);
45918    rc = sqlite3OsWrite(pWal->pWalFd, aFrame, sizeof(aFrame), iOffset);
45919    if( rc!=SQLITE_OK ){
45920      return rc;
45921    }
45922
45923    /* Write the page data */
45924    rc = sqlite3OsWrite(pWal->pWalFd, pData, szPage, iOffset+sizeof(aFrame));
45925    if( rc!=SQLITE_OK ){
45926      return rc;
45927    }
45928    pLast = p;
45929  }
45930
45931  /* Sync the log file if the 'isSync' flag was specified. */
45932  if( sync_flags ){
45933    i64 iSegment = sqlite3OsSectorSize(pWal->pWalFd);
45934    i64 iOffset = walFrameOffset(iFrame+1, szPage);
45935
45936    assert( isCommit );
45937    assert( iSegment>0 );
45938
45939    iSegment = (((iOffset+iSegment-1)/iSegment) * iSegment);
45940    while( iOffset<iSegment ){
45941      void *pData;
45942#if defined(SQLITE_HAS_CODEC)
45943      if( (pData = sqlite3PagerCodec(pLast))==0 ) return SQLITE_NOMEM;
45944#else
45945      pData = pLast->pData;
45946#endif
45947      walEncodeFrame(pWal, pLast->pgno, nTruncate, pData, aFrame);
45948      /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL */
45949      rc = sqlite3OsWrite(pWal->pWalFd, aFrame, sizeof(aFrame), iOffset);
45950      if( rc!=SQLITE_OK ){
45951        return rc;
45952      }
45953      iOffset += WAL_FRAME_HDRSIZE;
45954      rc = sqlite3OsWrite(pWal->pWalFd, pData, szPage, iOffset);
45955      if( rc!=SQLITE_OK ){
45956        return rc;
45957      }
45958      nLast++;
45959      iOffset += szPage;
45960    }
45961
45962    rc = sqlite3OsSync(pWal->pWalFd, sync_flags);
45963  }
45964
45965  /* Append data to the wal-index. It is not necessary to lock the
45966  ** wal-index to do this as the SQLITE_SHM_WRITE lock held on the wal-index
45967  ** guarantees that there are no other writers, and no data that may
45968  ** be in use by existing readers is being overwritten.
45969  */
45970  iFrame = pWal->hdr.mxFrame;
45971  for(p=pList; p && rc==SQLITE_OK; p=p->pDirty){
45972    iFrame++;
45973    rc = walIndexAppend(pWal, iFrame, p->pgno);
45974  }
45975  while( nLast>0 && rc==SQLITE_OK ){
45976    iFrame++;
45977    nLast--;
45978    rc = walIndexAppend(pWal, iFrame, pLast->pgno);
45979  }
45980
45981  if( rc==SQLITE_OK ){
45982    /* Update the private copy of the header. */
45983    pWal->hdr.szPage = (u16)((szPage&0xff00) | (szPage>>16));
45984    testcase( szPage<=32768 );
45985    testcase( szPage>=65536 );
45986    pWal->hdr.mxFrame = iFrame;
45987    if( isCommit ){
45988      pWal->hdr.iChange++;
45989      pWal->hdr.nPage = nTruncate;
45990    }
45991    /* If this is a commit, update the wal-index header too. */
45992    if( isCommit ){
45993      walIndexWriteHdr(pWal);
45994      pWal->iCallback = iFrame;
45995    }
45996  }
45997
45998  WALTRACE(("WAL%p: frame write %s\n", pWal, rc ? "failed" : "ok"));
45999  return rc;
46000}
46001
46002/*
46003** This routine is called to implement sqlite3_wal_checkpoint() and
46004** related interfaces.
46005**
46006** Obtain a CHECKPOINT lock and then backfill as much information as
46007** we can from WAL into the database.
46008**
46009** If parameter xBusy is not NULL, it is a pointer to a busy-handler
46010** callback. In this case this function runs a blocking checkpoint.
46011*/
46012SQLITE_PRIVATE int sqlite3WalCheckpoint(
46013  Wal *pWal,                      /* Wal connection */
46014  int eMode,                      /* PASSIVE, FULL or RESTART */
46015  int (*xBusy)(void*),            /* Function to call when busy */
46016  void *pBusyArg,                 /* Context argument for xBusyHandler */
46017  int sync_flags,                 /* Flags to sync db file with (or 0) */
46018  int nBuf,                       /* Size of temporary buffer */
46019  u8 *zBuf,                       /* Temporary buffer to use */
46020  int *pnLog,                     /* OUT: Number of frames in WAL */
46021  int *pnCkpt                     /* OUT: Number of backfilled frames in WAL */
46022){
46023  int rc;                         /* Return code */
46024  int isChanged = 0;              /* True if a new wal-index header is loaded */
46025  int eMode2 = eMode;             /* Mode to pass to walCheckpoint() */
46026
46027  assert( pWal->ckptLock==0 );
46028  assert( pWal->writeLock==0 );
46029
46030  WALTRACE(("WAL%p: checkpoint begins\n", pWal));
46031  rc = walLockExclusive(pWal, WAL_CKPT_LOCK, 1);
46032  if( rc ){
46033    /* Usually this is SQLITE_BUSY meaning that another thread or process
46034    ** is already running a checkpoint, or maybe a recovery.  But it might
46035    ** also be SQLITE_IOERR. */
46036    return rc;
46037  }
46038  pWal->ckptLock = 1;
46039
46040  /* If this is a blocking-checkpoint, then obtain the write-lock as well
46041  ** to prevent any writers from running while the checkpoint is underway.
46042  ** This has to be done before the call to walIndexReadHdr() below.
46043  **
46044  ** If the writer lock cannot be obtained, then a passive checkpoint is
46045  ** run instead. Since the checkpointer is not holding the writer lock,
46046  ** there is no point in blocking waiting for any readers. Assuming no
46047  ** other error occurs, this function will return SQLITE_BUSY to the caller.
46048  */
46049  if( eMode!=SQLITE_CHECKPOINT_PASSIVE ){
46050    rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_WRITE_LOCK, 1);
46051    if( rc==SQLITE_OK ){
46052      pWal->writeLock = 1;
46053    }else if( rc==SQLITE_BUSY ){
46054      eMode2 = SQLITE_CHECKPOINT_PASSIVE;
46055      rc = SQLITE_OK;
46056    }
46057  }
46058
46059  /* Read the wal-index header. */
46060  if( rc==SQLITE_OK ){
46061    rc = walIndexReadHdr(pWal, &isChanged);
46062  }
46063
46064  /* Copy data from the log to the database file. */
46065  if( rc==SQLITE_OK ){
46066    if( pWal->hdr.mxFrame && walPagesize(pWal)!=nBuf ){
46067      rc = SQLITE_CORRUPT_BKPT;
46068    }else{
46069      rc = walCheckpoint(pWal, eMode2, xBusy, pBusyArg, sync_flags, zBuf);
46070    }
46071
46072    /* If no error occurred, set the output variables. */
46073    if( rc==SQLITE_OK || rc==SQLITE_BUSY ){
46074      if( pnLog ) *pnLog = (int)pWal->hdr.mxFrame;
46075      if( pnCkpt ) *pnCkpt = (int)(walCkptInfo(pWal)->nBackfill);
46076    }
46077  }
46078
46079  if( isChanged ){
46080    /* If a new wal-index header was loaded before the checkpoint was
46081    ** performed, then the pager-cache associated with pWal is now
46082    ** out of date. So zero the cached wal-index header to ensure that
46083    ** next time the pager opens a snapshot on this database it knows that
46084    ** the cache needs to be reset.
46085    */
46086    memset(&pWal->hdr, 0, sizeof(WalIndexHdr));
46087  }
46088
46089  /* Release the locks. */
46090  sqlite3WalEndWriteTransaction(pWal);
46091  walUnlockExclusive(pWal, WAL_CKPT_LOCK, 1);
46092  pWal->ckptLock = 0;
46093  WALTRACE(("WAL%p: checkpoint %s\n", pWal, rc ? "failed" : "ok"));
46094  return (rc==SQLITE_OK && eMode!=eMode2 ? SQLITE_BUSY : rc);
46095}
46096
46097/* Return the value to pass to a sqlite3_wal_hook callback, the
46098** number of frames in the WAL at the point of the last commit since
46099** sqlite3WalCallback() was called.  If no commits have occurred since
46100** the last call, then return 0.
46101*/
46102SQLITE_PRIVATE int sqlite3WalCallback(Wal *pWal){
46103  u32 ret = 0;
46104  if( pWal ){
46105    ret = pWal->iCallback;
46106    pWal->iCallback = 0;
46107  }
46108  return (int)ret;
46109}
46110
46111/*
46112** This function is called to change the WAL subsystem into or out
46113** of locking_mode=EXCLUSIVE.
46114**
46115** If op is zero, then attempt to change from locking_mode=EXCLUSIVE
46116** into locking_mode=NORMAL.  This means that we must acquire a lock
46117** on the pWal->readLock byte.  If the WAL is already in locking_mode=NORMAL
46118** or if the acquisition of the lock fails, then return 0.  If the
46119** transition out of exclusive-mode is successful, return 1.  This
46120** operation must occur while the pager is still holding the exclusive
46121** lock on the main database file.
46122**
46123** If op is one, then change from locking_mode=NORMAL into
46124** locking_mode=EXCLUSIVE.  This means that the pWal->readLock must
46125** be released.  Return 1 if the transition is made and 0 if the
46126** WAL is already in exclusive-locking mode - meaning that this
46127** routine is a no-op.  The pager must already hold the exclusive lock
46128** on the main database file before invoking this operation.
46129**
46130** If op is negative, then do a dry-run of the op==1 case but do
46131** not actually change anything. The pager uses this to see if it
46132** should acquire the database exclusive lock prior to invoking
46133** the op==1 case.
46134*/
46135SQLITE_PRIVATE int sqlite3WalExclusiveMode(Wal *pWal, int op){
46136  int rc;
46137  assert( pWal->writeLock==0 );
46138  assert( pWal->exclusiveMode!=WAL_HEAPMEMORY_MODE || op==-1 );
46139
46140  /* pWal->readLock is usually set, but might be -1 if there was a
46141  ** prior error while attempting to acquire are read-lock. This cannot
46142  ** happen if the connection is actually in exclusive mode (as no xShmLock
46143  ** locks are taken in this case). Nor should the pager attempt to
46144  ** upgrade to exclusive-mode following such an error.
46145  */
46146  assert( pWal->readLock>=0 || pWal->lockError );
46147  assert( pWal->readLock>=0 || (op<=0 && pWal->exclusiveMode==0) );
46148
46149  if( op==0 ){
46150    if( pWal->exclusiveMode ){
46151      pWal->exclusiveMode = 0;
46152      if( walLockShared(pWal, WAL_READ_LOCK(pWal->readLock))!=SQLITE_OK ){
46153        pWal->exclusiveMode = 1;
46154      }
46155      rc = pWal->exclusiveMode==0;
46156    }else{
46157      /* Already in locking_mode=NORMAL */
46158      rc = 0;
46159    }
46160  }else if( op>0 ){
46161    assert( pWal->exclusiveMode==0 );
46162    assert( pWal->readLock>=0 );
46163    walUnlockShared(pWal, WAL_READ_LOCK(pWal->readLock));
46164    pWal->exclusiveMode = 1;
46165    rc = 1;
46166  }else{
46167    rc = pWal->exclusiveMode==0;
46168  }
46169  return rc;
46170}
46171
46172/*
46173** Return true if the argument is non-NULL and the WAL module is using
46174** heap-memory for the wal-index. Otherwise, if the argument is NULL or the
46175** WAL module is using shared-memory, return false.
46176*/
46177SQLITE_PRIVATE int sqlite3WalHeapMemory(Wal *pWal){
46178  return (pWal && pWal->exclusiveMode==WAL_HEAPMEMORY_MODE );
46179}
46180
46181#endif /* #ifndef SQLITE_OMIT_WAL */
46182
46183/************** End of wal.c *************************************************/
46184/************** Begin file btmutex.c *****************************************/
46185/*
46186** 2007 August 27
46187**
46188** The author disclaims copyright to this source code.  In place of
46189** a legal notice, here is a blessing:
46190**
46191**    May you do good and not evil.
46192**    May you find forgiveness for yourself and forgive others.
46193**    May you share freely, never taking more than you give.
46194**
46195*************************************************************************
46196**
46197** This file contains code used to implement mutexes on Btree objects.
46198** This code really belongs in btree.c.  But btree.c is getting too
46199** big and we want to break it down some.  This packaged seemed like
46200** a good breakout.
46201*/
46202/************** Include btreeInt.h in the middle of btmutex.c ****************/
46203/************** Begin file btreeInt.h ****************************************/
46204/*
46205** 2004 April 6
46206**
46207** The author disclaims copyright to this source code.  In place of
46208** a legal notice, here is a blessing:
46209**
46210**    May you do good and not evil.
46211**    May you find forgiveness for yourself and forgive others.
46212**    May you share freely, never taking more than you give.
46213**
46214*************************************************************************
46215** This file implements a external (disk-based) database using BTrees.
46216** For a detailed discussion of BTrees, refer to
46217**
46218**     Donald E. Knuth, THE ART OF COMPUTER PROGRAMMING, Volume 3:
46219**     "Sorting And Searching", pages 473-480. Addison-Wesley
46220**     Publishing Company, Reading, Massachusetts.
46221**
46222** The basic idea is that each page of the file contains N database
46223** entries and N+1 pointers to subpages.
46224**
46225**   ----------------------------------------------------------------
46226**   |  Ptr(0) | Key(0) | Ptr(1) | Key(1) | ... | Key(N-1) | Ptr(N) |
46227**   ----------------------------------------------------------------
46228**
46229** All of the keys on the page that Ptr(0) points to have values less
46230** than Key(0).  All of the keys on page Ptr(1) and its subpages have
46231** values greater than Key(0) and less than Key(1).  All of the keys
46232** on Ptr(N) and its subpages have values greater than Key(N-1).  And
46233** so forth.
46234**
46235** Finding a particular key requires reading O(log(M)) pages from the
46236** disk where M is the number of entries in the tree.
46237**
46238** In this implementation, a single file can hold one or more separate
46239** BTrees.  Each BTree is identified by the index of its root page.  The
46240** key and data for any entry are combined to form the "payload".  A
46241** fixed amount of payload can be carried directly on the database
46242** page.  If the payload is larger than the preset amount then surplus
46243** bytes are stored on overflow pages.  The payload for an entry
46244** and the preceding pointer are combined to form a "Cell".  Each
46245** page has a small header which contains the Ptr(N) pointer and other
46246** information such as the size of key and data.
46247**
46248** FORMAT DETAILS
46249**
46250** The file is divided into pages.  The first page is called page 1,
46251** the second is page 2, and so forth.  A page number of zero indicates
46252** "no such page".  The page size can be any power of 2 between 512 and 65536.
46253** Each page can be either a btree page, a freelist page, an overflow
46254** page, or a pointer-map page.
46255**
46256** The first page is always a btree page.  The first 100 bytes of the first
46257** page contain a special header (the "file header") that describes the file.
46258** The format of the file header is as follows:
46259**
46260**   OFFSET   SIZE    DESCRIPTION
46261**      0      16     Header string: "SQLite format 3\000"
46262**     16       2     Page size in bytes.
46263**     18       1     File format write version
46264**     19       1     File format read version
46265**     20       1     Bytes of unused space at the end of each page
46266**     21       1     Max embedded payload fraction
46267**     22       1     Min embedded payload fraction
46268**     23       1     Min leaf payload fraction
46269**     24       4     File change counter
46270**     28       4     Reserved for future use
46271**     32       4     First freelist page
46272**     36       4     Number of freelist pages in the file
46273**     40      60     15 4-byte meta values passed to higher layers
46274**
46275**     40       4     Schema cookie
46276**     44       4     File format of schema layer
46277**     48       4     Size of page cache
46278**     52       4     Largest root-page (auto/incr_vacuum)
46279**     56       4     1=UTF-8 2=UTF16le 3=UTF16be
46280**     60       4     User version
46281**     64       4     Incremental vacuum mode
46282**     68       4     unused
46283**     72       4     unused
46284**     76       4     unused
46285**
46286** All of the integer values are big-endian (most significant byte first).
46287**
46288** The file change counter is incremented when the database is changed
46289** This counter allows other processes to know when the file has changed
46290** and thus when they need to flush their cache.
46291**
46292** The max embedded payload fraction is the amount of the total usable
46293** space in a page that can be consumed by a single cell for standard
46294** B-tree (non-LEAFDATA) tables.  A value of 255 means 100%.  The default
46295** is to limit the maximum cell size so that at least 4 cells will fit
46296** on one page.  Thus the default max embedded payload fraction is 64.
46297**
46298** If the payload for a cell is larger than the max payload, then extra
46299** payload is spilled to overflow pages.  Once an overflow page is allocated,
46300** as many bytes as possible are moved into the overflow pages without letting
46301** the cell size drop below the min embedded payload fraction.
46302**
46303** The min leaf payload fraction is like the min embedded payload fraction
46304** except that it applies to leaf nodes in a LEAFDATA tree.  The maximum
46305** payload fraction for a LEAFDATA tree is always 100% (or 255) and it
46306** not specified in the header.
46307**
46308** Each btree pages is divided into three sections:  The header, the
46309** cell pointer array, and the cell content area.  Page 1 also has a 100-byte
46310** file header that occurs before the page header.
46311**
46312**      |----------------|
46313**      | file header    |   100 bytes.  Page 1 only.
46314**      |----------------|
46315**      | page header    |   8 bytes for leaves.  12 bytes for interior nodes
46316**      |----------------|
46317**      | cell pointer   |   |  2 bytes per cell.  Sorted order.
46318**      | array          |   |  Grows downward
46319**      |                |   v
46320**      |----------------|
46321**      | unallocated    |
46322**      | space          |
46323**      |----------------|   ^  Grows upwards
46324**      | cell content   |   |  Arbitrary order interspersed with freeblocks.
46325**      | area           |   |  and free space fragments.
46326**      |----------------|
46327**
46328** The page headers looks like this:
46329**
46330**   OFFSET   SIZE     DESCRIPTION
46331**      0       1      Flags. 1: intkey, 2: zerodata, 4: leafdata, 8: leaf
46332**      1       2      byte offset to the first freeblock
46333**      3       2      number of cells on this page
46334**      5       2      first byte of the cell content area
46335**      7       1      number of fragmented free bytes
46336**      8       4      Right child (the Ptr(N) value).  Omitted on leaves.
46337**
46338** The flags define the format of this btree page.  The leaf flag means that
46339** this page has no children.  The zerodata flag means that this page carries
46340** only keys and no data.  The intkey flag means that the key is a integer
46341** which is stored in the key size entry of the cell header rather than in
46342** the payload area.
46343**
46344** The cell pointer array begins on the first byte after the page header.
46345** The cell pointer array contains zero or more 2-byte numbers which are
46346** offsets from the beginning of the page to the cell content in the cell
46347** content area.  The cell pointers occur in sorted order.  The system strives
46348** to keep free space after the last cell pointer so that new cells can
46349** be easily added without having to defragment the page.
46350**
46351** Cell content is stored at the very end of the page and grows toward the
46352** beginning of the page.
46353**
46354** Unused space within the cell content area is collected into a linked list of
46355** freeblocks.  Each freeblock is at least 4 bytes in size.  The byte offset
46356** to the first freeblock is given in the header.  Freeblocks occur in
46357** increasing order.  Because a freeblock must be at least 4 bytes in size,
46358** any group of 3 or fewer unused bytes in the cell content area cannot
46359** exist on the freeblock chain.  A group of 3 or fewer free bytes is called
46360** a fragment.  The total number of bytes in all fragments is recorded.
46361** in the page header at offset 7.
46362**
46363**    SIZE    DESCRIPTION
46364**      2     Byte offset of the next freeblock
46365**      2     Bytes in this freeblock
46366**
46367** Cells are of variable length.  Cells are stored in the cell content area at
46368** the end of the page.  Pointers to the cells are in the cell pointer array
46369** that immediately follows the page header.  Cells is not necessarily
46370** contiguous or in order, but cell pointers are contiguous and in order.
46371**
46372** Cell content makes use of variable length integers.  A variable
46373** length integer is 1 to 9 bytes where the lower 7 bits of each
46374** byte are used.  The integer consists of all bytes that have bit 8 set and
46375** the first byte with bit 8 clear.  The most significant byte of the integer
46376** appears first.  A variable-length integer may not be more than 9 bytes long.
46377** As a special case, all 8 bytes of the 9th byte are used as data.  This
46378** allows a 64-bit integer to be encoded in 9 bytes.
46379**
46380**    0x00                      becomes  0x00000000
46381**    0x7f                      becomes  0x0000007f
46382**    0x81 0x00                 becomes  0x00000080
46383**    0x82 0x00                 becomes  0x00000100
46384**    0x80 0x7f                 becomes  0x0000007f
46385**    0x8a 0x91 0xd1 0xac 0x78  becomes  0x12345678
46386**    0x81 0x81 0x81 0x81 0x01  becomes  0x10204081
46387**
46388** Variable length integers are used for rowids and to hold the number of
46389** bytes of key and data in a btree cell.
46390**
46391** The content of a cell looks like this:
46392**
46393**    SIZE    DESCRIPTION
46394**      4     Page number of the left child. Omitted if leaf flag is set.
46395**     var    Number of bytes of data. Omitted if the zerodata flag is set.
46396**     var    Number of bytes of key. Or the key itself if intkey flag is set.
46397**      *     Payload
46398**      4     First page of the overflow chain.  Omitted if no overflow
46399**
46400** Overflow pages form a linked list.  Each page except the last is completely
46401** filled with data (pagesize - 4 bytes).  The last page can have as little
46402** as 1 byte of data.
46403**
46404**    SIZE    DESCRIPTION
46405**      4     Page number of next overflow page
46406**      *     Data
46407**
46408** Freelist pages come in two subtypes: trunk pages and leaf pages.  The
46409** file header points to the first in a linked list of trunk page.  Each trunk
46410** page points to multiple leaf pages.  The content of a leaf page is
46411** unspecified.  A trunk page looks like this:
46412**
46413**    SIZE    DESCRIPTION
46414**      4     Page number of next trunk page
46415**      4     Number of leaf pointers on this page
46416**      *     zero or more pages numbers of leaves
46417*/
46418
46419
46420/* The following value is the maximum cell size assuming a maximum page
46421** size give above.
46422*/
46423#define MX_CELL_SIZE(pBt)  ((int)(pBt->pageSize-8))
46424
46425/* The maximum number of cells on a single page of the database.  This
46426** assumes a minimum cell size of 6 bytes  (4 bytes for the cell itself
46427** plus 2 bytes for the index to the cell in the page header).  Such
46428** small cells will be rare, but they are possible.
46429*/
46430#define MX_CELL(pBt) ((pBt->pageSize-8)/6)
46431
46432/* Forward declarations */
46433typedef struct MemPage MemPage;
46434typedef struct BtLock BtLock;
46435
46436/*
46437** This is a magic string that appears at the beginning of every
46438** SQLite database in order to identify the file as a real database.
46439**
46440** You can change this value at compile-time by specifying a
46441** -DSQLITE_FILE_HEADER="..." on the compiler command-line.  The
46442** header must be exactly 16 bytes including the zero-terminator so
46443** the string itself should be 15 characters long.  If you change
46444** the header, then your custom library will not be able to read
46445** databases generated by the standard tools and the standard tools
46446** will not be able to read databases created by your custom library.
46447*/
46448#ifndef SQLITE_FILE_HEADER /* 123456789 123456 */
46449#  define SQLITE_FILE_HEADER "SQLite format 3"
46450#endif
46451
46452/*
46453** Page type flags.  An ORed combination of these flags appear as the
46454** first byte of on-disk image of every BTree page.
46455*/
46456#define PTF_INTKEY    0x01
46457#define PTF_ZERODATA  0x02
46458#define PTF_LEAFDATA  0x04
46459#define PTF_LEAF      0x08
46460
46461/*
46462** As each page of the file is loaded into memory, an instance of the following
46463** structure is appended and initialized to zero.  This structure stores
46464** information about the page that is decoded from the raw file page.
46465**
46466** The pParent field points back to the parent page.  This allows us to
46467** walk up the BTree from any leaf to the root.  Care must be taken to
46468** unref() the parent page pointer when this page is no longer referenced.
46469** The pageDestructor() routine handles that chore.
46470**
46471** Access to all fields of this structure is controlled by the mutex
46472** stored in MemPage.pBt->mutex.
46473*/
46474struct MemPage {
46475  u8 isInit;           /* True if previously initialized. MUST BE FIRST! */
46476  u8 nOverflow;        /* Number of overflow cell bodies in aCell[] */
46477  u8 intKey;           /* True if intkey flag is set */
46478  u8 leaf;             /* True if leaf flag is set */
46479  u8 hasData;          /* True if this page stores data */
46480  u8 hdrOffset;        /* 100 for page 1.  0 otherwise */
46481  u8 childPtrSize;     /* 0 if leaf==1.  4 if leaf==0 */
46482  u16 maxLocal;        /* Copy of BtShared.maxLocal or BtShared.maxLeaf */
46483  u16 minLocal;        /* Copy of BtShared.minLocal or BtShared.minLeaf */
46484  u16 cellOffset;      /* Index in aData of first cell pointer */
46485  u16 nFree;           /* Number of free bytes on the page */
46486  u16 nCell;           /* Number of cells on this page, local and ovfl */
46487  u16 maskPage;        /* Mask for page offset */
46488  struct _OvflCell {   /* Cells that will not fit on aData[] */
46489    u8 *pCell;          /* Pointers to the body of the overflow cell */
46490    u16 idx;            /* Insert this cell before idx-th non-overflow cell */
46491  } aOvfl[5];
46492  BtShared *pBt;       /* Pointer to BtShared that this page is part of */
46493  u8 *aData;           /* Pointer to disk image of the page data */
46494  DbPage *pDbPage;     /* Pager page handle */
46495  Pgno pgno;           /* Page number for this page */
46496};
46497
46498/*
46499** The in-memory image of a disk page has the auxiliary information appended
46500** to the end.  EXTRA_SIZE is the number of bytes of space needed to hold
46501** that extra information.
46502*/
46503#define EXTRA_SIZE sizeof(MemPage)
46504
46505/*
46506** A linked list of the following structures is stored at BtShared.pLock.
46507** Locks are added (or upgraded from READ_LOCK to WRITE_LOCK) when a cursor
46508** is opened on the table with root page BtShared.iTable. Locks are removed
46509** from this list when a transaction is committed or rolled back, or when
46510** a btree handle is closed.
46511*/
46512struct BtLock {
46513  Btree *pBtree;        /* Btree handle holding this lock */
46514  Pgno iTable;          /* Root page of table */
46515  u8 eLock;             /* READ_LOCK or WRITE_LOCK */
46516  BtLock *pNext;        /* Next in BtShared.pLock list */
46517};
46518
46519/* Candidate values for BtLock.eLock */
46520#define READ_LOCK     1
46521#define WRITE_LOCK    2
46522
46523/* A Btree handle
46524**
46525** A database connection contains a pointer to an instance of
46526** this object for every database file that it has open.  This structure
46527** is opaque to the database connection.  The database connection cannot
46528** see the internals of this structure and only deals with pointers to
46529** this structure.
46530**
46531** For some database files, the same underlying database cache might be
46532** shared between multiple connections.  In that case, each connection
46533** has it own instance of this object.  But each instance of this object
46534** points to the same BtShared object.  The database cache and the
46535** schema associated with the database file are all contained within
46536** the BtShared object.
46537**
46538** All fields in this structure are accessed under sqlite3.mutex.
46539** The pBt pointer itself may not be changed while there exists cursors
46540** in the referenced BtShared that point back to this Btree since those
46541** cursors have to go through this Btree to find their BtShared and
46542** they often do so without holding sqlite3.mutex.
46543*/
46544struct Btree {
46545  sqlite3 *db;       /* The database connection holding this btree */
46546  BtShared *pBt;     /* Sharable content of this btree */
46547  u8 inTrans;        /* TRANS_NONE, TRANS_READ or TRANS_WRITE */
46548  u8 sharable;       /* True if we can share pBt with another db */
46549  u8 locked;         /* True if db currently has pBt locked */
46550  int wantToLock;    /* Number of nested calls to sqlite3BtreeEnter() */
46551  int nBackup;       /* Number of backup operations reading this btree */
46552  Btree *pNext;      /* List of other sharable Btrees from the same db */
46553  Btree *pPrev;      /* Back pointer of the same list */
46554#ifndef SQLITE_OMIT_SHARED_CACHE
46555  BtLock lock;       /* Object used to lock page 1 */
46556#endif
46557};
46558
46559/*
46560** Btree.inTrans may take one of the following values.
46561**
46562** If the shared-data extension is enabled, there may be multiple users
46563** of the Btree structure. At most one of these may open a write transaction,
46564** but any number may have active read transactions.
46565*/
46566#define TRANS_NONE  0
46567#define TRANS_READ  1
46568#define TRANS_WRITE 2
46569
46570/*
46571** An instance of this object represents a single database file.
46572**
46573** A single database file can be in use as the same time by two
46574** or more database connections.  When two or more connections are
46575** sharing the same database file, each connection has it own
46576** private Btree object for the file and each of those Btrees points
46577** to this one BtShared object.  BtShared.nRef is the number of
46578** connections currently sharing this database file.
46579**
46580** Fields in this structure are accessed under the BtShared.mutex
46581** mutex, except for nRef and pNext which are accessed under the
46582** global SQLITE_MUTEX_STATIC_MASTER mutex.  The pPager field
46583** may not be modified once it is initially set as long as nRef>0.
46584** The pSchema field may be set once under BtShared.mutex and
46585** thereafter is unchanged as long as nRef>0.
46586**
46587** isPending:
46588**
46589**   If a BtShared client fails to obtain a write-lock on a database
46590**   table (because there exists one or more read-locks on the table),
46591**   the shared-cache enters 'pending-lock' state and isPending is
46592**   set to true.
46593**
46594**   The shared-cache leaves the 'pending lock' state when either of
46595**   the following occur:
46596**
46597**     1) The current writer (BtShared.pWriter) concludes its transaction, OR
46598**     2) The number of locks held by other connections drops to zero.
46599**
46600**   while in the 'pending-lock' state, no connection may start a new
46601**   transaction.
46602**
46603**   This feature is included to help prevent writer-starvation.
46604*/
46605struct BtShared {
46606  Pager *pPager;        /* The page cache */
46607  sqlite3 *db;          /* Database connection currently using this Btree */
46608  BtCursor *pCursor;    /* A list of all open cursors */
46609  MemPage *pPage1;      /* First page of the database */
46610  u8 readOnly;          /* True if the underlying file is readonly */
46611  u8 pageSizeFixed;     /* True if the page size can no longer be changed */
46612  u8 secureDelete;      /* True if secure_delete is enabled */
46613  u8 initiallyEmpty;    /* Database is empty at start of transaction */
46614  u8 openFlags;         /* Flags to sqlite3BtreeOpen() */
46615#ifndef SQLITE_OMIT_AUTOVACUUM
46616  u8 autoVacuum;        /* True if auto-vacuum is enabled */
46617  u8 incrVacuum;        /* True if incr-vacuum is enabled */
46618#endif
46619  u8 inTransaction;     /* Transaction state */
46620  u8 doNotUseWAL;       /* If true, do not open write-ahead-log file */
46621  u16 maxLocal;         /* Maximum local payload in non-LEAFDATA tables */
46622  u16 minLocal;         /* Minimum local payload in non-LEAFDATA tables */
46623  u16 maxLeaf;          /* Maximum local payload in a LEAFDATA table */
46624  u16 minLeaf;          /* Minimum local payload in a LEAFDATA table */
46625  u32 pageSize;         /* Total number of bytes on a page */
46626  u32 usableSize;       /* Number of usable bytes on each page */
46627  int nTransaction;     /* Number of open transactions (read + write) */
46628  u32 nPage;            /* Number of pages in the database */
46629  void *pSchema;        /* Pointer to space allocated by sqlite3BtreeSchema() */
46630  void (*xFreeSchema)(void*);  /* Destructor for BtShared.pSchema */
46631  sqlite3_mutex *mutex; /* Non-recursive mutex required to access this object */
46632  Bitvec *pHasContent;  /* Set of pages moved to free-list this transaction */
46633#ifndef SQLITE_OMIT_SHARED_CACHE
46634  int nRef;             /* Number of references to this structure */
46635  BtShared *pNext;      /* Next on a list of sharable BtShared structs */
46636  BtLock *pLock;        /* List of locks held on this shared-btree struct */
46637  Btree *pWriter;       /* Btree with currently open write transaction */
46638  u8 isExclusive;       /* True if pWriter has an EXCLUSIVE lock on the db */
46639  u8 isPending;         /* If waiting for read-locks to clear */
46640#endif
46641  u8 *pTmpSpace;        /* BtShared.pageSize bytes of space for tmp use */
46642};
46643
46644/*
46645** An instance of the following structure is used to hold information
46646** about a cell.  The parseCellPtr() function fills in this structure
46647** based on information extract from the raw disk page.
46648*/
46649typedef struct CellInfo CellInfo;
46650struct CellInfo {
46651  i64 nKey;      /* The key for INTKEY tables, or number of bytes in key */
46652  u8 *pCell;     /* Pointer to the start of cell content */
46653  u32 nData;     /* Number of bytes of data */
46654  u32 nPayload;  /* Total amount of payload */
46655  u16 nHeader;   /* Size of the cell content header in bytes */
46656  u16 nLocal;    /* Amount of payload held locally */
46657  u16 iOverflow; /* Offset to overflow page number.  Zero if no overflow */
46658  u16 nSize;     /* Size of the cell content on the main b-tree page */
46659};
46660
46661/*
46662** Maximum depth of an SQLite B-Tree structure. Any B-Tree deeper than
46663** this will be declared corrupt. This value is calculated based on a
46664** maximum database size of 2^31 pages a minimum fanout of 2 for a
46665** root-node and 3 for all other internal nodes.
46666**
46667** If a tree that appears to be taller than this is encountered, it is
46668** assumed that the database is corrupt.
46669*/
46670#define BTCURSOR_MAX_DEPTH 20
46671
46672/*
46673** A cursor is a pointer to a particular entry within a particular
46674** b-tree within a database file.
46675**
46676** The entry is identified by its MemPage and the index in
46677** MemPage.aCell[] of the entry.
46678**
46679** A single database file can shared by two more database connections,
46680** but cursors cannot be shared.  Each cursor is associated with a
46681** particular database connection identified BtCursor.pBtree.db.
46682**
46683** Fields in this structure are accessed under the BtShared.mutex
46684** found at self->pBt->mutex.
46685*/
46686struct BtCursor {
46687  Btree *pBtree;            /* The Btree to which this cursor belongs */
46688  BtShared *pBt;            /* The BtShared this cursor points to */
46689  BtCursor *pNext, *pPrev;  /* Forms a linked list of all cursors */
46690  struct KeyInfo *pKeyInfo; /* Argument passed to comparison function */
46691  Pgno pgnoRoot;            /* The root page of this tree */
46692  sqlite3_int64 cachedRowid; /* Next rowid cache.  0 means not valid */
46693  CellInfo info;            /* A parse of the cell we are pointing at */
46694  i64 nKey;        /* Size of pKey, or last integer key */
46695  void *pKey;      /* Saved key that was cursor's last known position */
46696  int skipNext;    /* Prev() is noop if negative. Next() is noop if positive */
46697  u8 wrFlag;                /* True if writable */
46698  u8 atLast;                /* Cursor pointing to the last entry */
46699  u8 validNKey;             /* True if info.nKey is valid */
46700  u8 eState;                /* One of the CURSOR_XXX constants (see below) */
46701#ifndef SQLITE_OMIT_INCRBLOB
46702  Pgno *aOverflow;          /* Cache of overflow page locations */
46703  u8 isIncrblobHandle;      /* True if this cursor is an incr. io handle */
46704#endif
46705  i16 iPage;                            /* Index of current page in apPage */
46706  u16 aiIdx[BTCURSOR_MAX_DEPTH];        /* Current index in apPage[i] */
46707  MemPage *apPage[BTCURSOR_MAX_DEPTH];  /* Pages from root to current page */
46708};
46709
46710/*
46711** Potential values for BtCursor.eState.
46712**
46713** CURSOR_VALID:
46714**   Cursor points to a valid entry. getPayload() etc. may be called.
46715**
46716** CURSOR_INVALID:
46717**   Cursor does not point to a valid entry. This can happen (for example)
46718**   because the table is empty or because BtreeCursorFirst() has not been
46719**   called.
46720**
46721** CURSOR_REQUIRESEEK:
46722**   The table that this cursor was opened on still exists, but has been
46723**   modified since the cursor was last used. The cursor position is saved
46724**   in variables BtCursor.pKey and BtCursor.nKey. When a cursor is in
46725**   this state, restoreCursorPosition() can be called to attempt to
46726**   seek the cursor to the saved position.
46727**
46728** CURSOR_FAULT:
46729**   A unrecoverable error (an I/O error or a malloc failure) has occurred
46730**   on a different connection that shares the BtShared cache with this
46731**   cursor.  The error has left the cache in an inconsistent state.
46732**   Do nothing else with this cursor.  Any attempt to use the cursor
46733**   should return the error code stored in BtCursor.skip
46734*/
46735#define CURSOR_INVALID           0
46736#define CURSOR_VALID             1
46737#define CURSOR_REQUIRESEEK       2
46738#define CURSOR_FAULT             3
46739
46740/*
46741** The database page the PENDING_BYTE occupies. This page is never used.
46742*/
46743# define PENDING_BYTE_PAGE(pBt) PAGER_MJ_PGNO(pBt)
46744
46745/*
46746** These macros define the location of the pointer-map entry for a
46747** database page. The first argument to each is the number of usable
46748** bytes on each page of the database (often 1024). The second is the
46749** page number to look up in the pointer map.
46750**
46751** PTRMAP_PAGENO returns the database page number of the pointer-map
46752** page that stores the required pointer. PTRMAP_PTROFFSET returns
46753** the offset of the requested map entry.
46754**
46755** If the pgno argument passed to PTRMAP_PAGENO is a pointer-map page,
46756** then pgno is returned. So (pgno==PTRMAP_PAGENO(pgsz, pgno)) can be
46757** used to test if pgno is a pointer-map page. PTRMAP_ISPAGE implements
46758** this test.
46759*/
46760#define PTRMAP_PAGENO(pBt, pgno) ptrmapPageno(pBt, pgno)
46761#define PTRMAP_PTROFFSET(pgptrmap, pgno) (5*(pgno-pgptrmap-1))
46762#define PTRMAP_ISPAGE(pBt, pgno) (PTRMAP_PAGENO((pBt),(pgno))==(pgno))
46763
46764/*
46765** The pointer map is a lookup table that identifies the parent page for
46766** each child page in the database file.  The parent page is the page that
46767** contains a pointer to the child.  Every page in the database contains
46768** 0 or 1 parent pages.  (In this context 'database page' refers
46769** to any page that is not part of the pointer map itself.)  Each pointer map
46770** entry consists of a single byte 'type' and a 4 byte parent page number.
46771** The PTRMAP_XXX identifiers below are the valid types.
46772**
46773** The purpose of the pointer map is to facility moving pages from one
46774** position in the file to another as part of autovacuum.  When a page
46775** is moved, the pointer in its parent must be updated to point to the
46776** new location.  The pointer map is used to locate the parent page quickly.
46777**
46778** PTRMAP_ROOTPAGE: The database page is a root-page. The page-number is not
46779**                  used in this case.
46780**
46781** PTRMAP_FREEPAGE: The database page is an unused (free) page. The page-number
46782**                  is not used in this case.
46783**
46784** PTRMAP_OVERFLOW1: The database page is the first page in a list of
46785**                   overflow pages. The page number identifies the page that
46786**                   contains the cell with a pointer to this overflow page.
46787**
46788** PTRMAP_OVERFLOW2: The database page is the second or later page in a list of
46789**                   overflow pages. The page-number identifies the previous
46790**                   page in the overflow page list.
46791**
46792** PTRMAP_BTREE: The database page is a non-root btree page. The page number
46793**               identifies the parent page in the btree.
46794*/
46795#define PTRMAP_ROOTPAGE 1
46796#define PTRMAP_FREEPAGE 2
46797#define PTRMAP_OVERFLOW1 3
46798#define PTRMAP_OVERFLOW2 4
46799#define PTRMAP_BTREE 5
46800
46801/* A bunch of assert() statements to check the transaction state variables
46802** of handle p (type Btree*) are internally consistent.
46803*/
46804#define btreeIntegrity(p) \
46805  assert( p->pBt->inTransaction!=TRANS_NONE || p->pBt->nTransaction==0 ); \
46806  assert( p->pBt->inTransaction>=p->inTrans );
46807
46808
46809/*
46810** The ISAUTOVACUUM macro is used within balance_nonroot() to determine
46811** if the database supports auto-vacuum or not. Because it is used
46812** within an expression that is an argument to another macro
46813** (sqliteMallocRaw), it is not possible to use conditional compilation.
46814** So, this macro is defined instead.
46815*/
46816#ifndef SQLITE_OMIT_AUTOVACUUM
46817#define ISAUTOVACUUM (pBt->autoVacuum)
46818#else
46819#define ISAUTOVACUUM 0
46820#endif
46821
46822
46823/*
46824** This structure is passed around through all the sanity checking routines
46825** in order to keep track of some global state information.
46826*/
46827typedef struct IntegrityCk IntegrityCk;
46828struct IntegrityCk {
46829  BtShared *pBt;    /* The tree being checked out */
46830  Pager *pPager;    /* The associated pager.  Also accessible by pBt->pPager */
46831  Pgno nPage;       /* Number of pages in the database */
46832  int *anRef;       /* Number of times each page is referenced */
46833  int mxErr;        /* Stop accumulating errors when this reaches zero */
46834  int nErr;         /* Number of messages written to zErrMsg so far */
46835  int mallocFailed; /* A memory allocation error has occurred */
46836  StrAccum errMsg;  /* Accumulate the error message text here */
46837};
46838
46839/*
46840** Read or write a two- and four-byte big-endian integer values.
46841*/
46842#define get2byte(x)   ((x)[0]<<8 | (x)[1])
46843#define put2byte(p,v) ((p)[0] = (u8)((v)>>8), (p)[1] = (u8)(v))
46844#define get4byte sqlite3Get4byte
46845#define put4byte sqlite3Put4byte
46846
46847/************** End of btreeInt.h ********************************************/
46848/************** Continuing where we left off in btmutex.c ********************/
46849#ifndef SQLITE_OMIT_SHARED_CACHE
46850#if SQLITE_THREADSAFE
46851
46852/*
46853** Obtain the BtShared mutex associated with B-Tree handle p. Also,
46854** set BtShared.db to the database handle associated with p and the
46855** p->locked boolean to true.
46856*/
46857static void lockBtreeMutex(Btree *p){
46858  assert( p->locked==0 );
46859  assert( sqlite3_mutex_notheld(p->pBt->mutex) );
46860  assert( sqlite3_mutex_held(p->db->mutex) );
46861
46862  sqlite3_mutex_enter(p->pBt->mutex);
46863  p->pBt->db = p->db;
46864  p->locked = 1;
46865}
46866
46867/*
46868** Release the BtShared mutex associated with B-Tree handle p and
46869** clear the p->locked boolean.
46870*/
46871static void unlockBtreeMutex(Btree *p){
46872  BtShared *pBt = p->pBt;
46873  assert( p->locked==1 );
46874  assert( sqlite3_mutex_held(pBt->mutex) );
46875  assert( sqlite3_mutex_held(p->db->mutex) );
46876  assert( p->db==pBt->db );
46877
46878  sqlite3_mutex_leave(pBt->mutex);
46879  p->locked = 0;
46880}
46881
46882/*
46883** Enter a mutex on the given BTree object.
46884**
46885** If the object is not sharable, then no mutex is ever required
46886** and this routine is a no-op.  The underlying mutex is non-recursive.
46887** But we keep a reference count in Btree.wantToLock so the behavior
46888** of this interface is recursive.
46889**
46890** To avoid deadlocks, multiple Btrees are locked in the same order
46891** by all database connections.  The p->pNext is a list of other
46892** Btrees belonging to the same database connection as the p Btree
46893** which need to be locked after p.  If we cannot get a lock on
46894** p, then first unlock all of the others on p->pNext, then wait
46895** for the lock to become available on p, then relock all of the
46896** subsequent Btrees that desire a lock.
46897*/
46898SQLITE_PRIVATE void sqlite3BtreeEnter(Btree *p){
46899  Btree *pLater;
46900
46901  /* Some basic sanity checking on the Btree.  The list of Btrees
46902  ** connected by pNext and pPrev should be in sorted order by
46903  ** Btree.pBt value. All elements of the list should belong to
46904  ** the same connection. Only shared Btrees are on the list. */
46905  assert( p->pNext==0 || p->pNext->pBt>p->pBt );
46906  assert( p->pPrev==0 || p->pPrev->pBt<p->pBt );
46907  assert( p->pNext==0 || p->pNext->db==p->db );
46908  assert( p->pPrev==0 || p->pPrev->db==p->db );
46909  assert( p->sharable || (p->pNext==0 && p->pPrev==0) );
46910
46911  /* Check for locking consistency */
46912  assert( !p->locked || p->wantToLock>0 );
46913  assert( p->sharable || p->wantToLock==0 );
46914
46915  /* We should already hold a lock on the database connection */
46916  assert( sqlite3_mutex_held(p->db->mutex) );
46917
46918  /* Unless the database is sharable and unlocked, then BtShared.db
46919  ** should already be set correctly. */
46920  assert( (p->locked==0 && p->sharable) || p->pBt->db==p->db );
46921
46922  if( !p->sharable ) return;
46923  p->wantToLock++;
46924  if( p->locked ) return;
46925
46926  /* In most cases, we should be able to acquire the lock we
46927  ** want without having to go throught the ascending lock
46928  ** procedure that follows.  Just be sure not to block.
46929  */
46930  if( sqlite3_mutex_try(p->pBt->mutex)==SQLITE_OK ){
46931    p->pBt->db = p->db;
46932    p->locked = 1;
46933    return;
46934  }
46935
46936  /* To avoid deadlock, first release all locks with a larger
46937  ** BtShared address.  Then acquire our lock.  Then reacquire
46938  ** the other BtShared locks that we used to hold in ascending
46939  ** order.
46940  */
46941  for(pLater=p->pNext; pLater; pLater=pLater->pNext){
46942    assert( pLater->sharable );
46943    assert( pLater->pNext==0 || pLater->pNext->pBt>pLater->pBt );
46944    assert( !pLater->locked || pLater->wantToLock>0 );
46945    if( pLater->locked ){
46946      unlockBtreeMutex(pLater);
46947    }
46948  }
46949  lockBtreeMutex(p);
46950  for(pLater=p->pNext; pLater; pLater=pLater->pNext){
46951    if( pLater->wantToLock ){
46952      lockBtreeMutex(pLater);
46953    }
46954  }
46955}
46956
46957/*
46958** Exit the recursive mutex on a Btree.
46959*/
46960SQLITE_PRIVATE void sqlite3BtreeLeave(Btree *p){
46961  if( p->sharable ){
46962    assert( p->wantToLock>0 );
46963    p->wantToLock--;
46964    if( p->wantToLock==0 ){
46965      unlockBtreeMutex(p);
46966    }
46967  }
46968}
46969
46970#ifndef NDEBUG
46971/*
46972** Return true if the BtShared mutex is held on the btree, or if the
46973** B-Tree is not marked as sharable.
46974**
46975** This routine is used only from within assert() statements.
46976*/
46977SQLITE_PRIVATE int sqlite3BtreeHoldsMutex(Btree *p){
46978  assert( p->sharable==0 || p->locked==0 || p->wantToLock>0 );
46979  assert( p->sharable==0 || p->locked==0 || p->db==p->pBt->db );
46980  assert( p->sharable==0 || p->locked==0 || sqlite3_mutex_held(p->pBt->mutex) );
46981  assert( p->sharable==0 || p->locked==0 || sqlite3_mutex_held(p->db->mutex) );
46982
46983  return (p->sharable==0 || p->locked);
46984}
46985#endif
46986
46987
46988#ifndef SQLITE_OMIT_INCRBLOB
46989/*
46990** Enter and leave a mutex on a Btree given a cursor owned by that
46991** Btree.  These entry points are used by incremental I/O and can be
46992** omitted if that module is not used.
46993*/
46994SQLITE_PRIVATE void sqlite3BtreeEnterCursor(BtCursor *pCur){
46995  sqlite3BtreeEnter(pCur->pBtree);
46996}
46997SQLITE_PRIVATE void sqlite3BtreeLeaveCursor(BtCursor *pCur){
46998  sqlite3BtreeLeave(pCur->pBtree);
46999}
47000#endif /* SQLITE_OMIT_INCRBLOB */
47001
47002
47003/*
47004** Enter the mutex on every Btree associated with a database
47005** connection.  This is needed (for example) prior to parsing
47006** a statement since we will be comparing table and column names
47007** against all schemas and we do not want those schemas being
47008** reset out from under us.
47009**
47010** There is a corresponding leave-all procedures.
47011**
47012** Enter the mutexes in accending order by BtShared pointer address
47013** to avoid the possibility of deadlock when two threads with
47014** two or more btrees in common both try to lock all their btrees
47015** at the same instant.
47016*/
47017SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3 *db){
47018  int i;
47019  Btree *p;
47020  assert( sqlite3_mutex_held(db->mutex) );
47021  for(i=0; i<db->nDb; i++){
47022    p = db->aDb[i].pBt;
47023    if( p ) sqlite3BtreeEnter(p);
47024  }
47025}
47026SQLITE_PRIVATE void sqlite3BtreeLeaveAll(sqlite3 *db){
47027  int i;
47028  Btree *p;
47029  assert( sqlite3_mutex_held(db->mutex) );
47030  for(i=0; i<db->nDb; i++){
47031    p = db->aDb[i].pBt;
47032    if( p ) sqlite3BtreeLeave(p);
47033  }
47034}
47035
47036/*
47037** Return true if a particular Btree requires a lock.  Return FALSE if
47038** no lock is ever required since it is not sharable.
47039*/
47040SQLITE_PRIVATE int sqlite3BtreeSharable(Btree *p){
47041  return p->sharable;
47042}
47043
47044#ifndef NDEBUG
47045/*
47046** Return true if the current thread holds the database connection
47047** mutex and all required BtShared mutexes.
47048**
47049** This routine is used inside assert() statements only.
47050*/
47051SQLITE_PRIVATE int sqlite3BtreeHoldsAllMutexes(sqlite3 *db){
47052  int i;
47053  if( !sqlite3_mutex_held(db->mutex) ){
47054    return 0;
47055  }
47056  for(i=0; i<db->nDb; i++){
47057    Btree *p;
47058    p = db->aDb[i].pBt;
47059    if( p && p->sharable &&
47060         (p->wantToLock==0 || !sqlite3_mutex_held(p->pBt->mutex)) ){
47061      return 0;
47062    }
47063  }
47064  return 1;
47065}
47066#endif /* NDEBUG */
47067
47068#ifndef NDEBUG
47069/*
47070** Return true if the correct mutexes are held for accessing the
47071** db->aDb[iDb].pSchema structure.  The mutexes required for schema
47072** access are:
47073**
47074**   (1) The mutex on db
47075**   (2) if iDb!=1, then the mutex on db->aDb[iDb].pBt.
47076**
47077** If pSchema is not NULL, then iDb is computed from pSchema and
47078** db using sqlite3SchemaToIndex().
47079*/
47080SQLITE_PRIVATE int sqlite3SchemaMutexHeld(sqlite3 *db, int iDb, Schema *pSchema){
47081  Btree *p;
47082  assert( db!=0 );
47083  if( pSchema ) iDb = sqlite3SchemaToIndex(db, pSchema);
47084  assert( iDb>=0 && iDb<db->nDb );
47085  if( !sqlite3_mutex_held(db->mutex) ) return 0;
47086  if( iDb==1 ) return 1;
47087  p = db->aDb[iDb].pBt;
47088  assert( p!=0 );
47089  return p->sharable==0 || p->locked==1;
47090}
47091#endif /* NDEBUG */
47092
47093#else /* SQLITE_THREADSAFE>0 above.  SQLITE_THREADSAFE==0 below */
47094/*
47095** The following are special cases for mutex enter routines for use
47096** in single threaded applications that use shared cache.  Except for
47097** these two routines, all mutex operations are no-ops in that case and
47098** are null #defines in btree.h.
47099**
47100** If shared cache is disabled, then all btree mutex routines, including
47101** the ones below, are no-ops and are null #defines in btree.h.
47102*/
47103
47104SQLITE_PRIVATE void sqlite3BtreeEnter(Btree *p){
47105  p->pBt->db = p->db;
47106}
47107SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3 *db){
47108  int i;
47109  for(i=0; i<db->nDb; i++){
47110    Btree *p = db->aDb[i].pBt;
47111    if( p ){
47112      p->pBt->db = p->db;
47113    }
47114  }
47115}
47116#endif /* if SQLITE_THREADSAFE */
47117#endif /* ifndef SQLITE_OMIT_SHARED_CACHE */
47118
47119/************** End of btmutex.c *********************************************/
47120/************** Begin file btree.c *******************************************/
47121/*
47122** 2004 April 6
47123**
47124** The author disclaims copyright to this source code.  In place of
47125** a legal notice, here is a blessing:
47126**
47127**    May you do good and not evil.
47128**    May you find forgiveness for yourself and forgive others.
47129**    May you share freely, never taking more than you give.
47130**
47131*************************************************************************
47132** This file implements a external (disk-based) database using BTrees.
47133** See the header comment on "btreeInt.h" for additional information.
47134** Including a description of file format and an overview of operation.
47135*/
47136
47137/*
47138** The header string that appears at the beginning of every
47139** SQLite database.
47140*/
47141static const char zMagicHeader[] = SQLITE_FILE_HEADER;
47142
47143/*
47144** Set this global variable to 1 to enable tracing using the TRACE
47145** macro.
47146*/
47147#if 0
47148int sqlite3BtreeTrace=1;  /* True to enable tracing */
47149# define TRACE(X)  if(sqlite3BtreeTrace){printf X;fflush(stdout);}
47150#else
47151# define TRACE(X)
47152#endif
47153
47154/*
47155** Extract a 2-byte big-endian integer from an array of unsigned bytes.
47156** But if the value is zero, make it 65536.
47157**
47158** This routine is used to extract the "offset to cell content area" value
47159** from the header of a btree page.  If the page size is 65536 and the page
47160** is empty, the offset should be 65536, but the 2-byte value stores zero.
47161** This routine makes the necessary adjustment to 65536.
47162*/
47163#define get2byteNotZero(X)  (((((int)get2byte(X))-1)&0xffff)+1)
47164
47165#ifndef SQLITE_OMIT_SHARED_CACHE
47166/*
47167** A list of BtShared objects that are eligible for participation
47168** in shared cache.  This variable has file scope during normal builds,
47169** but the test harness needs to access it so we make it global for
47170** test builds.
47171**
47172** Access to this variable is protected by SQLITE_MUTEX_STATIC_MASTER.
47173*/
47174#ifdef SQLITE_TEST
47175SQLITE_PRIVATE BtShared *SQLITE_WSD sqlite3SharedCacheList = 0;
47176#else
47177static BtShared *SQLITE_WSD sqlite3SharedCacheList = 0;
47178#endif
47179#endif /* SQLITE_OMIT_SHARED_CACHE */
47180
47181#ifndef SQLITE_OMIT_SHARED_CACHE
47182/*
47183** Enable or disable the shared pager and schema features.
47184**
47185** This routine has no effect on existing database connections.
47186** The shared cache setting effects only future calls to
47187** sqlite3_open(), sqlite3_open16(), or sqlite3_open_v2().
47188*/
47189SQLITE_API int sqlite3_enable_shared_cache(int enable){
47190  sqlite3GlobalConfig.sharedCacheEnabled = enable;
47191  return SQLITE_OK;
47192}
47193#endif
47194
47195
47196
47197#ifdef SQLITE_OMIT_SHARED_CACHE
47198  /*
47199  ** The functions querySharedCacheTableLock(), setSharedCacheTableLock(),
47200  ** and clearAllSharedCacheTableLocks()
47201  ** manipulate entries in the BtShared.pLock linked list used to store
47202  ** shared-cache table level locks. If the library is compiled with the
47203  ** shared-cache feature disabled, then there is only ever one user
47204  ** of each BtShared structure and so this locking is not necessary.
47205  ** So define the lock related functions as no-ops.
47206  */
47207  #define querySharedCacheTableLock(a,b,c) SQLITE_OK
47208  #define setSharedCacheTableLock(a,b,c) SQLITE_OK
47209  #define clearAllSharedCacheTableLocks(a)
47210  #define downgradeAllSharedCacheTableLocks(a)
47211  #define hasSharedCacheTableLock(a,b,c,d) 1
47212  #define hasReadConflicts(a, b) 0
47213#endif
47214
47215#ifndef SQLITE_OMIT_SHARED_CACHE
47216
47217#ifdef SQLITE_DEBUG
47218/*
47219**** This function is only used as part of an assert() statement. ***
47220**
47221** Check to see if pBtree holds the required locks to read or write to the
47222** table with root page iRoot.   Return 1 if it does and 0 if not.
47223**
47224** For example, when writing to a table with root-page iRoot via
47225** Btree connection pBtree:
47226**
47227**    assert( hasSharedCacheTableLock(pBtree, iRoot, 0, WRITE_LOCK) );
47228**
47229** When writing to an index that resides in a sharable database, the
47230** caller should have first obtained a lock specifying the root page of
47231** the corresponding table. This makes things a bit more complicated,
47232** as this module treats each table as a separate structure. To determine
47233** the table corresponding to the index being written, this
47234** function has to search through the database schema.
47235**
47236** Instead of a lock on the table/index rooted at page iRoot, the caller may
47237** hold a write-lock on the schema table (root page 1). This is also
47238** acceptable.
47239*/
47240static int hasSharedCacheTableLock(
47241  Btree *pBtree,         /* Handle that must hold lock */
47242  Pgno iRoot,            /* Root page of b-tree */
47243  int isIndex,           /* True if iRoot is the root of an index b-tree */
47244  int eLockType          /* Required lock type (READ_LOCK or WRITE_LOCK) */
47245){
47246  Schema *pSchema = (Schema *)pBtree->pBt->pSchema;
47247  Pgno iTab = 0;
47248  BtLock *pLock;
47249
47250  /* If this database is not shareable, or if the client is reading
47251  ** and has the read-uncommitted flag set, then no lock is required.
47252  ** Return true immediately.
47253  */
47254  if( (pBtree->sharable==0)
47255   || (eLockType==READ_LOCK && (pBtree->db->flags & SQLITE_ReadUncommitted))
47256  ){
47257    return 1;
47258  }
47259
47260  /* If the client is reading  or writing an index and the schema is
47261  ** not loaded, then it is too difficult to actually check to see if
47262  ** the correct locks are held.  So do not bother - just return true.
47263  ** This case does not come up very often anyhow.
47264  */
47265  if( isIndex && (!pSchema || (pSchema->flags&DB_SchemaLoaded)==0) ){
47266    return 1;
47267  }
47268
47269  /* Figure out the root-page that the lock should be held on. For table
47270  ** b-trees, this is just the root page of the b-tree being read or
47271  ** written. For index b-trees, it is the root page of the associated
47272  ** table.  */
47273  if( isIndex ){
47274    HashElem *p;
47275    for(p=sqliteHashFirst(&pSchema->idxHash); p; p=sqliteHashNext(p)){
47276      Index *pIdx = (Index *)sqliteHashData(p);
47277      if( pIdx->tnum==(int)iRoot ){
47278        iTab = pIdx->pTable->tnum;
47279      }
47280    }
47281  }else{
47282    iTab = iRoot;
47283  }
47284
47285  /* Search for the required lock. Either a write-lock on root-page iTab, a
47286  ** write-lock on the schema table, or (if the client is reading) a
47287  ** read-lock on iTab will suffice. Return 1 if any of these are found.  */
47288  for(pLock=pBtree->pBt->pLock; pLock; pLock=pLock->pNext){
47289    if( pLock->pBtree==pBtree
47290     && (pLock->iTable==iTab || (pLock->eLock==WRITE_LOCK && pLock->iTable==1))
47291     && pLock->eLock>=eLockType
47292    ){
47293      return 1;
47294    }
47295  }
47296
47297  /* Failed to find the required lock. */
47298  return 0;
47299}
47300#endif /* SQLITE_DEBUG */
47301
47302#ifdef SQLITE_DEBUG
47303/*
47304**** This function may be used as part of assert() statements only. ****
47305**
47306** Return true if it would be illegal for pBtree to write into the
47307** table or index rooted at iRoot because other shared connections are
47308** simultaneously reading that same table or index.
47309**
47310** It is illegal for pBtree to write if some other Btree object that
47311** shares the same BtShared object is currently reading or writing
47312** the iRoot table.  Except, if the other Btree object has the
47313** read-uncommitted flag set, then it is OK for the other object to
47314** have a read cursor.
47315**
47316** For example, before writing to any part of the table or index
47317** rooted at page iRoot, one should call:
47318**
47319**    assert( !hasReadConflicts(pBtree, iRoot) );
47320*/
47321static int hasReadConflicts(Btree *pBtree, Pgno iRoot){
47322  BtCursor *p;
47323  for(p=pBtree->pBt->pCursor; p; p=p->pNext){
47324    if( p->pgnoRoot==iRoot
47325     && p->pBtree!=pBtree
47326     && 0==(p->pBtree->db->flags & SQLITE_ReadUncommitted)
47327    ){
47328      return 1;
47329    }
47330  }
47331  return 0;
47332}
47333#endif    /* #ifdef SQLITE_DEBUG */
47334
47335/*
47336** Query to see if Btree handle p may obtain a lock of type eLock
47337** (READ_LOCK or WRITE_LOCK) on the table with root-page iTab. Return
47338** SQLITE_OK if the lock may be obtained (by calling
47339** setSharedCacheTableLock()), or SQLITE_LOCKED if not.
47340*/
47341static int querySharedCacheTableLock(Btree *p, Pgno iTab, u8 eLock){
47342  BtShared *pBt = p->pBt;
47343  BtLock *pIter;
47344
47345  assert( sqlite3BtreeHoldsMutex(p) );
47346  assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
47347  assert( p->db!=0 );
47348  assert( !(p->db->flags&SQLITE_ReadUncommitted)||eLock==WRITE_LOCK||iTab==1 );
47349
47350  /* If requesting a write-lock, then the Btree must have an open write
47351  ** transaction on this file. And, obviously, for this to be so there
47352  ** must be an open write transaction on the file itself.
47353  */
47354  assert( eLock==READ_LOCK || (p==pBt->pWriter && p->inTrans==TRANS_WRITE) );
47355  assert( eLock==READ_LOCK || pBt->inTransaction==TRANS_WRITE );
47356
47357  /* This routine is a no-op if the shared-cache is not enabled */
47358  if( !p->sharable ){
47359    return SQLITE_OK;
47360  }
47361
47362  /* If some other connection is holding an exclusive lock, the
47363  ** requested lock may not be obtained.
47364  */
47365  if( pBt->pWriter!=p && pBt->isExclusive ){
47366    sqlite3ConnectionBlocked(p->db, pBt->pWriter->db);
47367    return SQLITE_LOCKED_SHAREDCACHE;
47368  }
47369
47370  for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
47371    /* The condition (pIter->eLock!=eLock) in the following if(...)
47372    ** statement is a simplification of:
47373    **
47374    **   (eLock==WRITE_LOCK || pIter->eLock==WRITE_LOCK)
47375    **
47376    ** since we know that if eLock==WRITE_LOCK, then no other connection
47377    ** may hold a WRITE_LOCK on any table in this file (since there can
47378    ** only be a single writer).
47379    */
47380    assert( pIter->eLock==READ_LOCK || pIter->eLock==WRITE_LOCK );
47381    assert( eLock==READ_LOCK || pIter->pBtree==p || pIter->eLock==READ_LOCK);
47382    if( pIter->pBtree!=p && pIter->iTable==iTab && pIter->eLock!=eLock ){
47383      sqlite3ConnectionBlocked(p->db, pIter->pBtree->db);
47384      if( eLock==WRITE_LOCK ){
47385        assert( p==pBt->pWriter );
47386        pBt->isPending = 1;
47387      }
47388      return SQLITE_LOCKED_SHAREDCACHE;
47389    }
47390  }
47391  return SQLITE_OK;
47392}
47393#endif /* !SQLITE_OMIT_SHARED_CACHE */
47394
47395#ifndef SQLITE_OMIT_SHARED_CACHE
47396/*
47397** Add a lock on the table with root-page iTable to the shared-btree used
47398** by Btree handle p. Parameter eLock must be either READ_LOCK or
47399** WRITE_LOCK.
47400**
47401** This function assumes the following:
47402**
47403**   (a) The specified Btree object p is connected to a sharable
47404**       database (one with the BtShared.sharable flag set), and
47405**
47406**   (b) No other Btree objects hold a lock that conflicts
47407**       with the requested lock (i.e. querySharedCacheTableLock() has
47408**       already been called and returned SQLITE_OK).
47409**
47410** SQLITE_OK is returned if the lock is added successfully. SQLITE_NOMEM
47411** is returned if a malloc attempt fails.
47412*/
47413static int setSharedCacheTableLock(Btree *p, Pgno iTable, u8 eLock){
47414  BtShared *pBt = p->pBt;
47415  BtLock *pLock = 0;
47416  BtLock *pIter;
47417
47418  assert( sqlite3BtreeHoldsMutex(p) );
47419  assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
47420  assert( p->db!=0 );
47421
47422  /* A connection with the read-uncommitted flag set will never try to
47423  ** obtain a read-lock using this function. The only read-lock obtained
47424  ** by a connection in read-uncommitted mode is on the sqlite_master
47425  ** table, and that lock is obtained in BtreeBeginTrans().  */
47426  assert( 0==(p->db->flags&SQLITE_ReadUncommitted) || eLock==WRITE_LOCK );
47427
47428  /* This function should only be called on a sharable b-tree after it
47429  ** has been determined that no other b-tree holds a conflicting lock.  */
47430  assert( p->sharable );
47431  assert( SQLITE_OK==querySharedCacheTableLock(p, iTable, eLock) );
47432
47433  /* First search the list for an existing lock on this table. */
47434  for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
47435    if( pIter->iTable==iTable && pIter->pBtree==p ){
47436      pLock = pIter;
47437      break;
47438    }
47439  }
47440
47441  /* If the above search did not find a BtLock struct associating Btree p
47442  ** with table iTable, allocate one and link it into the list.
47443  */
47444  if( !pLock ){
47445    pLock = (BtLock *)sqlite3MallocZero(sizeof(BtLock));
47446    if( !pLock ){
47447      return SQLITE_NOMEM;
47448    }
47449    pLock->iTable = iTable;
47450    pLock->pBtree = p;
47451    pLock->pNext = pBt->pLock;
47452    pBt->pLock = pLock;
47453  }
47454
47455  /* Set the BtLock.eLock variable to the maximum of the current lock
47456  ** and the requested lock. This means if a write-lock was already held
47457  ** and a read-lock requested, we don't incorrectly downgrade the lock.
47458  */
47459  assert( WRITE_LOCK>READ_LOCK );
47460  if( eLock>pLock->eLock ){
47461    pLock->eLock = eLock;
47462  }
47463
47464  return SQLITE_OK;
47465}
47466#endif /* !SQLITE_OMIT_SHARED_CACHE */
47467
47468#ifndef SQLITE_OMIT_SHARED_CACHE
47469/*
47470** Release all the table locks (locks obtained via calls to
47471** the setSharedCacheTableLock() procedure) held by Btree object p.
47472**
47473** This function assumes that Btree p has an open read or write
47474** transaction. If it does not, then the BtShared.isPending variable
47475** may be incorrectly cleared.
47476*/
47477static void clearAllSharedCacheTableLocks(Btree *p){
47478  BtShared *pBt = p->pBt;
47479  BtLock **ppIter = &pBt->pLock;
47480
47481  assert( sqlite3BtreeHoldsMutex(p) );
47482  assert( p->sharable || 0==*ppIter );
47483  assert( p->inTrans>0 );
47484
47485  while( *ppIter ){
47486    BtLock *pLock = *ppIter;
47487    assert( pBt->isExclusive==0 || pBt->pWriter==pLock->pBtree );
47488    assert( pLock->pBtree->inTrans>=pLock->eLock );
47489    if( pLock->pBtree==p ){
47490      *ppIter = pLock->pNext;
47491      assert( pLock->iTable!=1 || pLock==&p->lock );
47492      if( pLock->iTable!=1 ){
47493        sqlite3_free(pLock);
47494      }
47495    }else{
47496      ppIter = &pLock->pNext;
47497    }
47498  }
47499
47500  assert( pBt->isPending==0 || pBt->pWriter );
47501  if( pBt->pWriter==p ){
47502    pBt->pWriter = 0;
47503    pBt->isExclusive = 0;
47504    pBt->isPending = 0;
47505  }else if( pBt->nTransaction==2 ){
47506    /* This function is called when Btree p is concluding its
47507    ** transaction. If there currently exists a writer, and p is not
47508    ** that writer, then the number of locks held by connections other
47509    ** than the writer must be about to drop to zero. In this case
47510    ** set the isPending flag to 0.
47511    **
47512    ** If there is not currently a writer, then BtShared.isPending must
47513    ** be zero already. So this next line is harmless in that case.
47514    */
47515    pBt->isPending = 0;
47516  }
47517}
47518
47519/*
47520** This function changes all write-locks held by Btree p into read-locks.
47521*/
47522static void downgradeAllSharedCacheTableLocks(Btree *p){
47523  BtShared *pBt = p->pBt;
47524  if( pBt->pWriter==p ){
47525    BtLock *pLock;
47526    pBt->pWriter = 0;
47527    pBt->isExclusive = 0;
47528    pBt->isPending = 0;
47529    for(pLock=pBt->pLock; pLock; pLock=pLock->pNext){
47530      assert( pLock->eLock==READ_LOCK || pLock->pBtree==p );
47531      pLock->eLock = READ_LOCK;
47532    }
47533  }
47534}
47535
47536#endif /* SQLITE_OMIT_SHARED_CACHE */
47537
47538static void releasePage(MemPage *pPage);  /* Forward reference */
47539
47540/*
47541***** This routine is used inside of assert() only ****
47542**
47543** Verify that the cursor holds the mutex on its BtShared
47544*/
47545#ifdef SQLITE_DEBUG
47546static int cursorHoldsMutex(BtCursor *p){
47547  return sqlite3_mutex_held(p->pBt->mutex);
47548}
47549#endif
47550
47551
47552#ifndef SQLITE_OMIT_INCRBLOB
47553/*
47554** Invalidate the overflow page-list cache for cursor pCur, if any.
47555*/
47556static void invalidateOverflowCache(BtCursor *pCur){
47557  assert( cursorHoldsMutex(pCur) );
47558  sqlite3_free(pCur->aOverflow);
47559  pCur->aOverflow = 0;
47560}
47561
47562/*
47563** Invalidate the overflow page-list cache for all cursors opened
47564** on the shared btree structure pBt.
47565*/
47566static void invalidateAllOverflowCache(BtShared *pBt){
47567  BtCursor *p;
47568  assert( sqlite3_mutex_held(pBt->mutex) );
47569  for(p=pBt->pCursor; p; p=p->pNext){
47570    invalidateOverflowCache(p);
47571  }
47572}
47573
47574/*
47575** This function is called before modifying the contents of a table
47576** to invalidate any incrblob cursors that are open on the
47577** row or one of the rows being modified.
47578**
47579** If argument isClearTable is true, then the entire contents of the
47580** table is about to be deleted. In this case invalidate all incrblob
47581** cursors open on any row within the table with root-page pgnoRoot.
47582**
47583** Otherwise, if argument isClearTable is false, then the row with
47584** rowid iRow is being replaced or deleted. In this case invalidate
47585** only those incrblob cursors open on that specific row.
47586*/
47587static void invalidateIncrblobCursors(
47588  Btree *pBtree,          /* The database file to check */
47589  i64 iRow,               /* The rowid that might be changing */
47590  int isClearTable        /* True if all rows are being deleted */
47591){
47592  BtCursor *p;
47593  BtShared *pBt = pBtree->pBt;
47594  assert( sqlite3BtreeHoldsMutex(pBtree) );
47595  for(p=pBt->pCursor; p; p=p->pNext){
47596    if( p->isIncrblobHandle && (isClearTable || p->info.nKey==iRow) ){
47597      p->eState = CURSOR_INVALID;
47598    }
47599  }
47600}
47601
47602#else
47603  /* Stub functions when INCRBLOB is omitted */
47604  #define invalidateOverflowCache(x)
47605  #define invalidateAllOverflowCache(x)
47606  #define invalidateIncrblobCursors(x,y,z)
47607#endif /* SQLITE_OMIT_INCRBLOB */
47608
47609/*
47610** Set bit pgno of the BtShared.pHasContent bitvec. This is called
47611** when a page that previously contained data becomes a free-list leaf
47612** page.
47613**
47614** The BtShared.pHasContent bitvec exists to work around an obscure
47615** bug caused by the interaction of two useful IO optimizations surrounding
47616** free-list leaf pages:
47617**
47618**   1) When all data is deleted from a page and the page becomes
47619**      a free-list leaf page, the page is not written to the database
47620**      (as free-list leaf pages contain no meaningful data). Sometimes
47621**      such a page is not even journalled (as it will not be modified,
47622**      why bother journalling it?).
47623**
47624**   2) When a free-list leaf page is reused, its content is not read
47625**      from the database or written to the journal file (why should it
47626**      be, if it is not at all meaningful?).
47627**
47628** By themselves, these optimizations work fine and provide a handy
47629** performance boost to bulk delete or insert operations. However, if
47630** a page is moved to the free-list and then reused within the same
47631** transaction, a problem comes up. If the page is not journalled when
47632** it is moved to the free-list and it is also not journalled when it
47633** is extracted from the free-list and reused, then the original data
47634** may be lost. In the event of a rollback, it may not be possible
47635** to restore the database to its original configuration.
47636**
47637** The solution is the BtShared.pHasContent bitvec. Whenever a page is
47638** moved to become a free-list leaf page, the corresponding bit is
47639** set in the bitvec. Whenever a leaf page is extracted from the free-list,
47640** optimization 2 above is omitted if the corresponding bit is already
47641** set in BtShared.pHasContent. The contents of the bitvec are cleared
47642** at the end of every transaction.
47643*/
47644static int btreeSetHasContent(BtShared *pBt, Pgno pgno){
47645  int rc = SQLITE_OK;
47646  if( !pBt->pHasContent ){
47647    assert( pgno<=pBt->nPage );
47648    pBt->pHasContent = sqlite3BitvecCreate(pBt->nPage);
47649    if( !pBt->pHasContent ){
47650      rc = SQLITE_NOMEM;
47651    }
47652  }
47653  if( rc==SQLITE_OK && pgno<=sqlite3BitvecSize(pBt->pHasContent) ){
47654    rc = sqlite3BitvecSet(pBt->pHasContent, pgno);
47655  }
47656  return rc;
47657}
47658
47659/*
47660** Query the BtShared.pHasContent vector.
47661**
47662** This function is called when a free-list leaf page is removed from the
47663** free-list for reuse. It returns false if it is safe to retrieve the
47664** page from the pager layer with the 'no-content' flag set. True otherwise.
47665*/
47666static int btreeGetHasContent(BtShared *pBt, Pgno pgno){
47667  Bitvec *p = pBt->pHasContent;
47668  return (p && (pgno>sqlite3BitvecSize(p) || sqlite3BitvecTest(p, pgno)));
47669}
47670
47671/*
47672** Clear (destroy) the BtShared.pHasContent bitvec. This should be
47673** invoked at the conclusion of each write-transaction.
47674*/
47675static void btreeClearHasContent(BtShared *pBt){
47676  sqlite3BitvecDestroy(pBt->pHasContent);
47677  pBt->pHasContent = 0;
47678}
47679
47680/*
47681** Save the current cursor position in the variables BtCursor.nKey
47682** and BtCursor.pKey. The cursor's state is set to CURSOR_REQUIRESEEK.
47683**
47684** The caller must ensure that the cursor is valid (has eState==CURSOR_VALID)
47685** prior to calling this routine.
47686*/
47687static int saveCursorPosition(BtCursor *pCur){
47688  int rc;
47689
47690  assert( CURSOR_VALID==pCur->eState );
47691  assert( 0==pCur->pKey );
47692  assert( cursorHoldsMutex(pCur) );
47693
47694  rc = sqlite3BtreeKeySize(pCur, &pCur->nKey);
47695  assert( rc==SQLITE_OK );  /* KeySize() cannot fail */
47696
47697  /* If this is an intKey table, then the above call to BtreeKeySize()
47698  ** stores the integer key in pCur->nKey. In this case this value is
47699  ** all that is required. Otherwise, if pCur is not open on an intKey
47700  ** table, then malloc space for and store the pCur->nKey bytes of key
47701  ** data.
47702  */
47703  if( 0==pCur->apPage[0]->intKey ){
47704    void *pKey = sqlite3Malloc( (int)pCur->nKey );
47705    if( pKey ){
47706      rc = sqlite3BtreeKey(pCur, 0, (int)pCur->nKey, pKey);
47707      if( rc==SQLITE_OK ){
47708        pCur->pKey = pKey;
47709      }else{
47710        sqlite3_free(pKey);
47711      }
47712    }else{
47713      rc = SQLITE_NOMEM;
47714    }
47715  }
47716  assert( !pCur->apPage[0]->intKey || !pCur->pKey );
47717
47718  if( rc==SQLITE_OK ){
47719    int i;
47720    for(i=0; i<=pCur->iPage; i++){
47721      releasePage(pCur->apPage[i]);
47722      pCur->apPage[i] = 0;
47723    }
47724    pCur->iPage = -1;
47725    pCur->eState = CURSOR_REQUIRESEEK;
47726  }
47727
47728  invalidateOverflowCache(pCur);
47729  return rc;
47730}
47731
47732/*
47733** Save the positions of all cursors (except pExcept) that are open on
47734** the table  with root-page iRoot. Usually, this is called just before cursor
47735** pExcept is used to modify the table (BtreeDelete() or BtreeInsert()).
47736*/
47737static int saveAllCursors(BtShared *pBt, Pgno iRoot, BtCursor *pExcept){
47738  BtCursor *p;
47739  assert( sqlite3_mutex_held(pBt->mutex) );
47740  assert( pExcept==0 || pExcept->pBt==pBt );
47741  for(p=pBt->pCursor; p; p=p->pNext){
47742    if( p!=pExcept && (0==iRoot || p->pgnoRoot==iRoot) &&
47743        p->eState==CURSOR_VALID ){
47744      int rc = saveCursorPosition(p);
47745      if( SQLITE_OK!=rc ){
47746        return rc;
47747      }
47748    }
47749  }
47750  return SQLITE_OK;
47751}
47752
47753/*
47754** Clear the current cursor position.
47755*/
47756SQLITE_PRIVATE void sqlite3BtreeClearCursor(BtCursor *pCur){
47757  assert( cursorHoldsMutex(pCur) );
47758  sqlite3_free(pCur->pKey);
47759  pCur->pKey = 0;
47760  pCur->eState = CURSOR_INVALID;
47761}
47762
47763/*
47764** In this version of BtreeMoveto, pKey is a packed index record
47765** such as is generated by the OP_MakeRecord opcode.  Unpack the
47766** record and then call BtreeMovetoUnpacked() to do the work.
47767*/
47768static int btreeMoveto(
47769  BtCursor *pCur,     /* Cursor open on the btree to be searched */
47770  const void *pKey,   /* Packed key if the btree is an index */
47771  i64 nKey,           /* Integer key for tables.  Size of pKey for indices */
47772  int bias,           /* Bias search to the high end */
47773  int *pRes           /* Write search results here */
47774){
47775  int rc;                    /* Status code */
47776  UnpackedRecord *pIdxKey;   /* Unpacked index key */
47777  char aSpace[150];          /* Temp space for pIdxKey - to avoid a malloc */
47778
47779  if( pKey ){
47780    assert( nKey==(i64)(int)nKey );
47781    pIdxKey = sqlite3VdbeRecordUnpack(pCur->pKeyInfo, (int)nKey, pKey,
47782                                      aSpace, sizeof(aSpace));
47783    if( pIdxKey==0 ) return SQLITE_NOMEM;
47784  }else{
47785    pIdxKey = 0;
47786  }
47787  rc = sqlite3BtreeMovetoUnpacked(pCur, pIdxKey, nKey, bias, pRes);
47788  if( pKey ){
47789    sqlite3VdbeDeleteUnpackedRecord(pIdxKey);
47790  }
47791  return rc;
47792}
47793
47794/*
47795** Restore the cursor to the position it was in (or as close to as possible)
47796** when saveCursorPosition() was called. Note that this call deletes the
47797** saved position info stored by saveCursorPosition(), so there can be
47798** at most one effective restoreCursorPosition() call after each
47799** saveCursorPosition().
47800*/
47801static int btreeRestoreCursorPosition(BtCursor *pCur){
47802  int rc;
47803  assert( cursorHoldsMutex(pCur) );
47804  assert( pCur->eState>=CURSOR_REQUIRESEEK );
47805  if( pCur->eState==CURSOR_FAULT ){
47806    return pCur->skipNext;
47807  }
47808  pCur->eState = CURSOR_INVALID;
47809  rc = btreeMoveto(pCur, pCur->pKey, pCur->nKey, 0, &pCur->skipNext);
47810  if( rc==SQLITE_OK ){
47811    sqlite3_free(pCur->pKey);
47812    pCur->pKey = 0;
47813    assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_INVALID );
47814  }
47815  return rc;
47816}
47817
47818#define restoreCursorPosition(p) \
47819  (p->eState>=CURSOR_REQUIRESEEK ? \
47820         btreeRestoreCursorPosition(p) : \
47821         SQLITE_OK)
47822
47823/*
47824** Determine whether or not a cursor has moved from the position it
47825** was last placed at.  Cursors can move when the row they are pointing
47826** at is deleted out from under them.
47827**
47828** This routine returns an error code if something goes wrong.  The
47829** integer *pHasMoved is set to one if the cursor has moved and 0 if not.
47830*/
47831SQLITE_PRIVATE int sqlite3BtreeCursorHasMoved(BtCursor *pCur, int *pHasMoved){
47832  int rc;
47833
47834  rc = restoreCursorPosition(pCur);
47835  if( rc ){
47836    *pHasMoved = 1;
47837    return rc;
47838  }
47839  if( pCur->eState!=CURSOR_VALID || pCur->skipNext!=0 ){
47840    *pHasMoved = 1;
47841  }else{
47842    *pHasMoved = 0;
47843  }
47844  return SQLITE_OK;
47845}
47846
47847#ifndef SQLITE_OMIT_AUTOVACUUM
47848/*
47849** Given a page number of a regular database page, return the page
47850** number for the pointer-map page that contains the entry for the
47851** input page number.
47852**
47853** Return 0 (not a valid page) for pgno==1 since there is
47854** no pointer map associated with page 1.  The integrity_check logic
47855** requires that ptrmapPageno(*,1)!=1.
47856*/
47857static Pgno ptrmapPageno(BtShared *pBt, Pgno pgno){
47858  int nPagesPerMapPage;
47859  Pgno iPtrMap, ret;
47860  assert( sqlite3_mutex_held(pBt->mutex) );
47861  if( pgno<2 ) return 0;
47862  nPagesPerMapPage = (pBt->usableSize/5)+1;
47863  iPtrMap = (pgno-2)/nPagesPerMapPage;
47864  ret = (iPtrMap*nPagesPerMapPage) + 2;
47865  if( ret==PENDING_BYTE_PAGE(pBt) ){
47866    ret++;
47867  }
47868  return ret;
47869}
47870
47871/*
47872** Write an entry into the pointer map.
47873**
47874** This routine updates the pointer map entry for page number 'key'
47875** so that it maps to type 'eType' and parent page number 'pgno'.
47876**
47877** If *pRC is initially non-zero (non-SQLITE_OK) then this routine is
47878** a no-op.  If an error occurs, the appropriate error code is written
47879** into *pRC.
47880*/
47881static void ptrmapPut(BtShared *pBt, Pgno key, u8 eType, Pgno parent, int *pRC){
47882  DbPage *pDbPage;  /* The pointer map page */
47883  u8 *pPtrmap;      /* The pointer map data */
47884  Pgno iPtrmap;     /* The pointer map page number */
47885  int offset;       /* Offset in pointer map page */
47886  int rc;           /* Return code from subfunctions */
47887
47888  if( *pRC ) return;
47889
47890  assert( sqlite3_mutex_held(pBt->mutex) );
47891  /* The master-journal page number must never be used as a pointer map page */
47892  assert( 0==PTRMAP_ISPAGE(pBt, PENDING_BYTE_PAGE(pBt)) );
47893
47894  assert( pBt->autoVacuum );
47895  if( key==0 ){
47896    *pRC = SQLITE_CORRUPT_BKPT;
47897    return;
47898  }
47899  iPtrmap = PTRMAP_PAGENO(pBt, key);
47900  rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage);
47901  if( rc!=SQLITE_OK ){
47902    *pRC = rc;
47903    return;
47904  }
47905  offset = PTRMAP_PTROFFSET(iPtrmap, key);
47906  if( offset<0 ){
47907    *pRC = SQLITE_CORRUPT_BKPT;
47908    goto ptrmap_exit;
47909  }
47910  pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
47911
47912  if( eType!=pPtrmap[offset] || get4byte(&pPtrmap[offset+1])!=parent ){
47913    TRACE(("PTRMAP_UPDATE: %d->(%d,%d)\n", key, eType, parent));
47914    *pRC= rc = sqlite3PagerWrite(pDbPage);
47915    if( rc==SQLITE_OK ){
47916      pPtrmap[offset] = eType;
47917      put4byte(&pPtrmap[offset+1], parent);
47918    }
47919  }
47920
47921ptrmap_exit:
47922  sqlite3PagerUnref(pDbPage);
47923}
47924
47925/*
47926** Read an entry from the pointer map.
47927**
47928** This routine retrieves the pointer map entry for page 'key', writing
47929** the type and parent page number to *pEType and *pPgno respectively.
47930** An error code is returned if something goes wrong, otherwise SQLITE_OK.
47931*/
47932static int ptrmapGet(BtShared *pBt, Pgno key, u8 *pEType, Pgno *pPgno){
47933  DbPage *pDbPage;   /* The pointer map page */
47934  int iPtrmap;       /* Pointer map page index */
47935  u8 *pPtrmap;       /* Pointer map page data */
47936  int offset;        /* Offset of entry in pointer map */
47937  int rc;
47938
47939  assert( sqlite3_mutex_held(pBt->mutex) );
47940
47941  iPtrmap = PTRMAP_PAGENO(pBt, key);
47942  rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage);
47943  if( rc!=0 ){
47944    return rc;
47945  }
47946  pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
47947
47948  offset = PTRMAP_PTROFFSET(iPtrmap, key);
47949  assert( pEType!=0 );
47950  *pEType = pPtrmap[offset];
47951  if( pPgno ) *pPgno = get4byte(&pPtrmap[offset+1]);
47952
47953  sqlite3PagerUnref(pDbPage);
47954  if( *pEType<1 || *pEType>5 ) return SQLITE_CORRUPT_BKPT;
47955  return SQLITE_OK;
47956}
47957
47958#else /* if defined SQLITE_OMIT_AUTOVACUUM */
47959  #define ptrmapPut(w,x,y,z,rc)
47960  #define ptrmapGet(w,x,y,z) SQLITE_OK
47961  #define ptrmapPutOvflPtr(x, y, rc)
47962#endif
47963
47964/*
47965** Given a btree page and a cell index (0 means the first cell on
47966** the page, 1 means the second cell, and so forth) return a pointer
47967** to the cell content.
47968**
47969** This routine works only for pages that do not contain overflow cells.
47970*/
47971#define findCell(P,I) \
47972  ((P)->aData + ((P)->maskPage & get2byte(&(P)->aData[(P)->cellOffset+2*(I)])))
47973
47974/*
47975** This a more complex version of findCell() that works for
47976** pages that do contain overflow cells.
47977*/
47978static u8 *findOverflowCell(MemPage *pPage, int iCell){
47979  int i;
47980  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
47981  for(i=pPage->nOverflow-1; i>=0; i--){
47982    int k;
47983    struct _OvflCell *pOvfl;
47984    pOvfl = &pPage->aOvfl[i];
47985    k = pOvfl->idx;
47986    if( k<=iCell ){
47987      if( k==iCell ){
47988        return pOvfl->pCell;
47989      }
47990      iCell--;
47991    }
47992  }
47993  return findCell(pPage, iCell);
47994}
47995
47996/*
47997** Parse a cell content block and fill in the CellInfo structure.  There
47998** are two versions of this function.  btreeParseCell() takes a
47999** cell index as the second argument and btreeParseCellPtr()
48000** takes a pointer to the body of the cell as its second argument.
48001**
48002** Within this file, the parseCell() macro can be called instead of
48003** btreeParseCellPtr(). Using some compilers, this will be faster.
48004*/
48005static void btreeParseCellPtr(
48006  MemPage *pPage,         /* Page containing the cell */
48007  u8 *pCell,              /* Pointer to the cell text. */
48008  CellInfo *pInfo         /* Fill in this structure */
48009){
48010  u16 n;                  /* Number bytes in cell content header */
48011  u32 nPayload;           /* Number of bytes of cell payload */
48012
48013  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
48014
48015  pInfo->pCell = pCell;
48016  assert( pPage->leaf==0 || pPage->leaf==1 );
48017  n = pPage->childPtrSize;
48018  assert( n==4-4*pPage->leaf );
48019  if( pPage->intKey ){
48020    if( pPage->hasData ){
48021      n += getVarint32(&pCell[n], nPayload);
48022    }else{
48023      nPayload = 0;
48024    }
48025    n += getVarint(&pCell[n], (u64*)&pInfo->nKey);
48026    pInfo->nData = nPayload;
48027  }else{
48028    pInfo->nData = 0;
48029    n += getVarint32(&pCell[n], nPayload);
48030    pInfo->nKey = nPayload;
48031  }
48032  pInfo->nPayload = nPayload;
48033  pInfo->nHeader = n;
48034  testcase( nPayload==pPage->maxLocal );
48035  testcase( nPayload==pPage->maxLocal+1 );
48036  if( likely(nPayload<=pPage->maxLocal) ){
48037    /* This is the (easy) common case where the entire payload fits
48038    ** on the local page.  No overflow is required.
48039    */
48040    if( (pInfo->nSize = (u16)(n+nPayload))<4 ) pInfo->nSize = 4;
48041    pInfo->nLocal = (u16)nPayload;
48042    pInfo->iOverflow = 0;
48043  }else{
48044    /* If the payload will not fit completely on the local page, we have
48045    ** to decide how much to store locally and how much to spill onto
48046    ** overflow pages.  The strategy is to minimize the amount of unused
48047    ** space on overflow pages while keeping the amount of local storage
48048    ** in between minLocal and maxLocal.
48049    **
48050    ** Warning:  changing the way overflow payload is distributed in any
48051    ** way will result in an incompatible file format.
48052    */
48053    int minLocal;  /* Minimum amount of payload held locally */
48054    int maxLocal;  /* Maximum amount of payload held locally */
48055    int surplus;   /* Overflow payload available for local storage */
48056
48057    minLocal = pPage->minLocal;
48058    maxLocal = pPage->maxLocal;
48059    surplus = minLocal + (nPayload - minLocal)%(pPage->pBt->usableSize - 4);
48060    testcase( surplus==maxLocal );
48061    testcase( surplus==maxLocal+1 );
48062    if( surplus <= maxLocal ){
48063      pInfo->nLocal = (u16)surplus;
48064    }else{
48065      pInfo->nLocal = (u16)minLocal;
48066    }
48067    pInfo->iOverflow = (u16)(pInfo->nLocal + n);
48068    pInfo->nSize = pInfo->iOverflow + 4;
48069  }
48070}
48071#define parseCell(pPage, iCell, pInfo) \
48072  btreeParseCellPtr((pPage), findCell((pPage), (iCell)), (pInfo))
48073static void btreeParseCell(
48074  MemPage *pPage,         /* Page containing the cell */
48075  int iCell,              /* The cell index.  First cell is 0 */
48076  CellInfo *pInfo         /* Fill in this structure */
48077){
48078  parseCell(pPage, iCell, pInfo);
48079}
48080
48081/*
48082** Compute the total number of bytes that a Cell needs in the cell
48083** data area of the btree-page.  The return number includes the cell
48084** data header and the local payload, but not any overflow page or
48085** the space used by the cell pointer.
48086*/
48087static u16 cellSizePtr(MemPage *pPage, u8 *pCell){
48088  u8 *pIter = &pCell[pPage->childPtrSize];
48089  u32 nSize;
48090
48091#ifdef SQLITE_DEBUG
48092  /* The value returned by this function should always be the same as
48093  ** the (CellInfo.nSize) value found by doing a full parse of the
48094  ** cell. If SQLITE_DEBUG is defined, an assert() at the bottom of
48095  ** this function verifies that this invariant is not violated. */
48096  CellInfo debuginfo;
48097  btreeParseCellPtr(pPage, pCell, &debuginfo);
48098#endif
48099
48100  if( pPage->intKey ){
48101    u8 *pEnd;
48102    if( pPage->hasData ){
48103      pIter += getVarint32(pIter, nSize);
48104    }else{
48105      nSize = 0;
48106    }
48107
48108    /* pIter now points at the 64-bit integer key value, a variable length
48109    ** integer. The following block moves pIter to point at the first byte
48110    ** past the end of the key value. */
48111    pEnd = &pIter[9];
48112    while( (*pIter++)&0x80 && pIter<pEnd );
48113  }else{
48114    pIter += getVarint32(pIter, nSize);
48115  }
48116
48117  testcase( nSize==pPage->maxLocal );
48118  testcase( nSize==pPage->maxLocal+1 );
48119  if( nSize>pPage->maxLocal ){
48120    int minLocal = pPage->minLocal;
48121    nSize = minLocal + (nSize - minLocal) % (pPage->pBt->usableSize - 4);
48122    testcase( nSize==pPage->maxLocal );
48123    testcase( nSize==pPage->maxLocal+1 );
48124    if( nSize>pPage->maxLocal ){
48125      nSize = minLocal;
48126    }
48127    nSize += 4;
48128  }
48129  nSize += (u32)(pIter - pCell);
48130
48131  /* The minimum size of any cell is 4 bytes. */
48132  if( nSize<4 ){
48133    nSize = 4;
48134  }
48135
48136  assert( nSize==debuginfo.nSize );
48137  return (u16)nSize;
48138}
48139
48140#ifdef SQLITE_DEBUG
48141/* This variation on cellSizePtr() is used inside of assert() statements
48142** only. */
48143static u16 cellSize(MemPage *pPage, int iCell){
48144  return cellSizePtr(pPage, findCell(pPage, iCell));
48145}
48146#endif
48147
48148#ifndef SQLITE_OMIT_AUTOVACUUM
48149/*
48150** If the cell pCell, part of page pPage contains a pointer
48151** to an overflow page, insert an entry into the pointer-map
48152** for the overflow page.
48153*/
48154static void ptrmapPutOvflPtr(MemPage *pPage, u8 *pCell, int *pRC){
48155  CellInfo info;
48156  if( *pRC ) return;
48157  assert( pCell!=0 );
48158  btreeParseCellPtr(pPage, pCell, &info);
48159  assert( (info.nData+(pPage->intKey?0:info.nKey))==info.nPayload );
48160  if( info.iOverflow ){
48161    Pgno ovfl = get4byte(&pCell[info.iOverflow]);
48162    ptrmapPut(pPage->pBt, ovfl, PTRMAP_OVERFLOW1, pPage->pgno, pRC);
48163  }
48164}
48165#endif
48166
48167
48168/*
48169** Defragment the page given.  All Cells are moved to the
48170** end of the page and all free space is collected into one
48171** big FreeBlk that occurs in between the header and cell
48172** pointer array and the cell content area.
48173*/
48174static int defragmentPage(MemPage *pPage){
48175  int i;                     /* Loop counter */
48176  int pc;                    /* Address of a i-th cell */
48177  int hdr;                   /* Offset to the page header */
48178  int size;                  /* Size of a cell */
48179  int usableSize;            /* Number of usable bytes on a page */
48180  int cellOffset;            /* Offset to the cell pointer array */
48181  int cbrk;                  /* Offset to the cell content area */
48182  int nCell;                 /* Number of cells on the page */
48183  unsigned char *data;       /* The page data */
48184  unsigned char *temp;       /* Temp area for cell content */
48185  int iCellFirst;            /* First allowable cell index */
48186  int iCellLast;             /* Last possible cell index */
48187
48188
48189  assert( sqlite3PagerIswriteable(pPage->pDbPage) );
48190  assert( pPage->pBt!=0 );
48191  assert( pPage->pBt->usableSize <= SQLITE_MAX_PAGE_SIZE );
48192  assert( pPage->nOverflow==0 );
48193  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
48194  temp = sqlite3PagerTempSpace(pPage->pBt->pPager);
48195  data = pPage->aData;
48196  hdr = pPage->hdrOffset;
48197  cellOffset = pPage->cellOffset;
48198  nCell = pPage->nCell;
48199  assert( nCell==get2byte(&data[hdr+3]) );
48200  usableSize = pPage->pBt->usableSize;
48201  cbrk = get2byte(&data[hdr+5]);
48202  memcpy(&temp[cbrk], &data[cbrk], usableSize - cbrk);
48203  cbrk = usableSize;
48204  iCellFirst = cellOffset + 2*nCell;
48205  iCellLast = usableSize - 4;
48206  for(i=0; i<nCell; i++){
48207    u8 *pAddr;     /* The i-th cell pointer */
48208    pAddr = &data[cellOffset + i*2];
48209    pc = get2byte(pAddr);
48210    testcase( pc==iCellFirst );
48211    testcase( pc==iCellLast );
48212#if !defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
48213    /* These conditions have already been verified in btreeInitPage()
48214    ** if SQLITE_ENABLE_OVERSIZE_CELL_CHECK is defined
48215    */
48216    if( pc<iCellFirst || pc>iCellLast ){
48217      return SQLITE_CORRUPT_BKPT;
48218    }
48219#endif
48220    assert( pc>=iCellFirst && pc<=iCellLast );
48221    size = cellSizePtr(pPage, &temp[pc]);
48222    cbrk -= size;
48223#if defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
48224    if( cbrk<iCellFirst ){
48225      return SQLITE_CORRUPT_BKPT;
48226    }
48227#else
48228    if( cbrk<iCellFirst || pc+size>usableSize ){
48229      return SQLITE_CORRUPT_BKPT;
48230    }
48231#endif
48232    assert( cbrk+size<=usableSize && cbrk>=iCellFirst );
48233    testcase( cbrk+size==usableSize );
48234    testcase( pc+size==usableSize );
48235    memcpy(&data[cbrk], &temp[pc], size);
48236    put2byte(pAddr, cbrk);
48237  }
48238  assert( cbrk>=iCellFirst );
48239  put2byte(&data[hdr+5], cbrk);
48240  data[hdr+1] = 0;
48241  data[hdr+2] = 0;
48242  data[hdr+7] = 0;
48243  memset(&data[iCellFirst], 0, cbrk-iCellFirst);
48244  assert( sqlite3PagerIswriteable(pPage->pDbPage) );
48245  if( cbrk-iCellFirst!=pPage->nFree ){
48246    return SQLITE_CORRUPT_BKPT;
48247  }
48248  return SQLITE_OK;
48249}
48250
48251/*
48252** Allocate nByte bytes of space from within the B-Tree page passed
48253** as the first argument. Write into *pIdx the index into pPage->aData[]
48254** of the first byte of allocated space. Return either SQLITE_OK or
48255** an error code (usually SQLITE_CORRUPT).
48256**
48257** The caller guarantees that there is sufficient space to make the
48258** allocation.  This routine might need to defragment in order to bring
48259** all the space together, however.  This routine will avoid using
48260** the first two bytes past the cell pointer area since presumably this
48261** allocation is being made in order to insert a new cell, so we will
48262** also end up needing a new cell pointer.
48263*/
48264static int allocateSpace(MemPage *pPage, int nByte, int *pIdx){
48265  const int hdr = pPage->hdrOffset;    /* Local cache of pPage->hdrOffset */
48266  u8 * const data = pPage->aData;      /* Local cache of pPage->aData */
48267  int nFrag;                           /* Number of fragmented bytes on pPage */
48268  int top;                             /* First byte of cell content area */
48269  int gap;        /* First byte of gap between cell pointers and cell content */
48270  int rc;         /* Integer return code */
48271  int usableSize; /* Usable size of the page */
48272
48273  assert( sqlite3PagerIswriteable(pPage->pDbPage) );
48274  assert( pPage->pBt );
48275  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
48276  assert( nByte>=0 );  /* Minimum cell size is 4 */
48277  assert( pPage->nFree>=nByte );
48278  assert( pPage->nOverflow==0 );
48279  usableSize = pPage->pBt->usableSize;
48280  assert( nByte < usableSize-8 );
48281
48282  nFrag = data[hdr+7];
48283  assert( pPage->cellOffset == hdr + 12 - 4*pPage->leaf );
48284  gap = pPage->cellOffset + 2*pPage->nCell;
48285  top = get2byteNotZero(&data[hdr+5]);
48286  if( gap>top ) return SQLITE_CORRUPT_BKPT;
48287  testcase( gap+2==top );
48288  testcase( gap+1==top );
48289  testcase( gap==top );
48290
48291  if( nFrag>=60 ){
48292    /* Always defragment highly fragmented pages */
48293    rc = defragmentPage(pPage);
48294    if( rc ) return rc;
48295    top = get2byteNotZero(&data[hdr+5]);
48296  }else if( gap+2<=top ){
48297    /* Search the freelist looking for a free slot big enough to satisfy
48298    ** the request. The allocation is made from the first free slot in
48299    ** the list that is large enough to accomadate it.
48300    */
48301    int pc, addr;
48302    for(addr=hdr+1; (pc = get2byte(&data[addr]))>0; addr=pc){
48303      int size;            /* Size of the free slot */
48304      if( pc>usableSize-4 || pc<addr+4 ){
48305        return SQLITE_CORRUPT_BKPT;
48306      }
48307      size = get2byte(&data[pc+2]);
48308      if( size>=nByte ){
48309        int x = size - nByte;
48310        testcase( x==4 );
48311        testcase( x==3 );
48312        if( x<4 ){
48313          /* Remove the slot from the free-list. Update the number of
48314          ** fragmented bytes within the page. */
48315          memcpy(&data[addr], &data[pc], 2);
48316          data[hdr+7] = (u8)(nFrag + x);
48317        }else if( size+pc > usableSize ){
48318          return SQLITE_CORRUPT_BKPT;
48319        }else{
48320          /* The slot remains on the free-list. Reduce its size to account
48321          ** for the portion used by the new allocation. */
48322          put2byte(&data[pc+2], x);
48323        }
48324        *pIdx = pc + x;
48325        return SQLITE_OK;
48326      }
48327    }
48328  }
48329
48330  /* Check to make sure there is enough space in the gap to satisfy
48331  ** the allocation.  If not, defragment.
48332  */
48333  testcase( gap+2+nByte==top );
48334  if( gap+2+nByte>top ){
48335    rc = defragmentPage(pPage);
48336    if( rc ) return rc;
48337    top = get2byteNotZero(&data[hdr+5]);
48338    assert( gap+nByte<=top );
48339  }
48340
48341
48342  /* Allocate memory from the gap in between the cell pointer array
48343  ** and the cell content area.  The btreeInitPage() call has already
48344  ** validated the freelist.  Given that the freelist is valid, there
48345  ** is no way that the allocation can extend off the end of the page.
48346  ** The assert() below verifies the previous sentence.
48347  */
48348  top -= nByte;
48349  put2byte(&data[hdr+5], top);
48350  assert( top+nByte <= (int)pPage->pBt->usableSize );
48351  *pIdx = top;
48352  return SQLITE_OK;
48353}
48354
48355/*
48356** Return a section of the pPage->aData to the freelist.
48357** The first byte of the new free block is pPage->aDisk[start]
48358** and the size of the block is "size" bytes.
48359**
48360** Most of the effort here is involved in coalesing adjacent
48361** free blocks into a single big free block.
48362*/
48363static int freeSpace(MemPage *pPage, int start, int size){
48364  int addr, pbegin, hdr;
48365  int iLast;                        /* Largest possible freeblock offset */
48366  unsigned char *data = pPage->aData;
48367
48368  assert( pPage->pBt!=0 );
48369  assert( sqlite3PagerIswriteable(pPage->pDbPage) );
48370  assert( start>=pPage->hdrOffset+6+pPage->childPtrSize );
48371  assert( (start + size) <= (int)pPage->pBt->usableSize );
48372  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
48373  assert( size>=0 );   /* Minimum cell size is 4 */
48374
48375  if( pPage->pBt->secureDelete ){
48376    /* Overwrite deleted information with zeros when the secure_delete
48377    ** option is enabled */
48378    memset(&data[start], 0, size);
48379  }
48380
48381  /* Add the space back into the linked list of freeblocks.  Note that
48382  ** even though the freeblock list was checked by btreeInitPage(),
48383  ** btreeInitPage() did not detect overlapping cells or
48384  ** freeblocks that overlapped cells.   Nor does it detect when the
48385  ** cell content area exceeds the value in the page header.  If these
48386  ** situations arise, then subsequent insert operations might corrupt
48387  ** the freelist.  So we do need to check for corruption while scanning
48388  ** the freelist.
48389  */
48390  hdr = pPage->hdrOffset;
48391  addr = hdr + 1;
48392  iLast = pPage->pBt->usableSize - 4;
48393  assert( start<=iLast );
48394  while( (pbegin = get2byte(&data[addr]))<start && pbegin>0 ){
48395    if( pbegin<addr+4 ){
48396      return SQLITE_CORRUPT_BKPT;
48397    }
48398    addr = pbegin;
48399  }
48400  if( pbegin>iLast ){
48401    return SQLITE_CORRUPT_BKPT;
48402  }
48403  assert( pbegin>addr || pbegin==0 );
48404  put2byte(&data[addr], start);
48405  put2byte(&data[start], pbegin);
48406  put2byte(&data[start+2], size);
48407  pPage->nFree = pPage->nFree + (u16)size;
48408
48409  /* Coalesce adjacent free blocks */
48410  addr = hdr + 1;
48411  while( (pbegin = get2byte(&data[addr]))>0 ){
48412    int pnext, psize, x;
48413    assert( pbegin>addr );
48414    assert( pbegin <= (int)pPage->pBt->usableSize-4 );
48415    pnext = get2byte(&data[pbegin]);
48416    psize = get2byte(&data[pbegin+2]);
48417    if( pbegin + psize + 3 >= pnext && pnext>0 ){
48418      int frag = pnext - (pbegin+psize);
48419      if( (frag<0) || (frag>(int)data[hdr+7]) ){
48420        return SQLITE_CORRUPT_BKPT;
48421      }
48422      data[hdr+7] -= (u8)frag;
48423      x = get2byte(&data[pnext]);
48424      put2byte(&data[pbegin], x);
48425      x = pnext + get2byte(&data[pnext+2]) - pbegin;
48426      put2byte(&data[pbegin+2], x);
48427    }else{
48428      addr = pbegin;
48429    }
48430  }
48431
48432  /* If the cell content area begins with a freeblock, remove it. */
48433  if( data[hdr+1]==data[hdr+5] && data[hdr+2]==data[hdr+6] ){
48434    int top;
48435    pbegin = get2byte(&data[hdr+1]);
48436    memcpy(&data[hdr+1], &data[pbegin], 2);
48437    top = get2byte(&data[hdr+5]) + get2byte(&data[pbegin+2]);
48438    put2byte(&data[hdr+5], top);
48439  }
48440  assert( sqlite3PagerIswriteable(pPage->pDbPage) );
48441  return SQLITE_OK;
48442}
48443
48444/*
48445** Decode the flags byte (the first byte of the header) for a page
48446** and initialize fields of the MemPage structure accordingly.
48447**
48448** Only the following combinations are supported.  Anything different
48449** indicates a corrupt database files:
48450**
48451**         PTF_ZERODATA
48452**         PTF_ZERODATA | PTF_LEAF
48453**         PTF_LEAFDATA | PTF_INTKEY
48454**         PTF_LEAFDATA | PTF_INTKEY | PTF_LEAF
48455*/
48456static int decodeFlags(MemPage *pPage, int flagByte){
48457  BtShared *pBt;     /* A copy of pPage->pBt */
48458
48459  assert( pPage->hdrOffset==(pPage->pgno==1 ? 100 : 0) );
48460  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
48461  pPage->leaf = (u8)(flagByte>>3);  assert( PTF_LEAF == 1<<3 );
48462  flagByte &= ~PTF_LEAF;
48463  pPage->childPtrSize = 4-4*pPage->leaf;
48464  pBt = pPage->pBt;
48465  if( flagByte==(PTF_LEAFDATA | PTF_INTKEY) ){
48466    pPage->intKey = 1;
48467    pPage->hasData = pPage->leaf;
48468    pPage->maxLocal = pBt->maxLeaf;
48469    pPage->minLocal = pBt->minLeaf;
48470  }else if( flagByte==PTF_ZERODATA ){
48471    pPage->intKey = 0;
48472    pPage->hasData = 0;
48473    pPage->maxLocal = pBt->maxLocal;
48474    pPage->minLocal = pBt->minLocal;
48475  }else{
48476    return SQLITE_CORRUPT_BKPT;
48477  }
48478  return SQLITE_OK;
48479}
48480
48481/*
48482** Initialize the auxiliary information for a disk block.
48483**
48484** Return SQLITE_OK on success.  If we see that the page does
48485** not contain a well-formed database page, then return
48486** SQLITE_CORRUPT.  Note that a return of SQLITE_OK does not
48487** guarantee that the page is well-formed.  It only shows that
48488** we failed to detect any corruption.
48489*/
48490static int btreeInitPage(MemPage *pPage){
48491
48492  assert( pPage->pBt!=0 );
48493  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
48494  assert( pPage->pgno==sqlite3PagerPagenumber(pPage->pDbPage) );
48495  assert( pPage == sqlite3PagerGetExtra(pPage->pDbPage) );
48496  assert( pPage->aData == sqlite3PagerGetData(pPage->pDbPage) );
48497
48498  if( !pPage->isInit ){
48499    u16 pc;            /* Address of a freeblock within pPage->aData[] */
48500    u8 hdr;            /* Offset to beginning of page header */
48501    u8 *data;          /* Equal to pPage->aData */
48502    BtShared *pBt;        /* The main btree structure */
48503    int usableSize;    /* Amount of usable space on each page */
48504    u16 cellOffset;    /* Offset from start of page to first cell pointer */
48505    int nFree;         /* Number of unused bytes on the page */
48506    int top;           /* First byte of the cell content area */
48507    int iCellFirst;    /* First allowable cell or freeblock offset */
48508    int iCellLast;     /* Last possible cell or freeblock offset */
48509
48510    pBt = pPage->pBt;
48511
48512    hdr = pPage->hdrOffset;
48513    data = pPage->aData;
48514    if( decodeFlags(pPage, data[hdr]) ) return SQLITE_CORRUPT_BKPT;
48515    assert( pBt->pageSize>=512 && pBt->pageSize<=65536 );
48516    pPage->maskPage = (u16)(pBt->pageSize - 1);
48517    pPage->nOverflow = 0;
48518    usableSize = pBt->usableSize;
48519    pPage->cellOffset = cellOffset = hdr + 12 - 4*pPage->leaf;
48520    top = get2byteNotZero(&data[hdr+5]);
48521    pPage->nCell = get2byte(&data[hdr+3]);
48522    if( pPage->nCell>MX_CELL(pBt) ){
48523      /* To many cells for a single page.  The page must be corrupt */
48524      return SQLITE_CORRUPT_BKPT;
48525    }
48526    testcase( pPage->nCell==MX_CELL(pBt) );
48527
48528    /* A malformed database page might cause us to read past the end
48529    ** of page when parsing a cell.
48530    **
48531    ** The following block of code checks early to see if a cell extends
48532    ** past the end of a page boundary and causes SQLITE_CORRUPT to be
48533    ** returned if it does.
48534    */
48535    iCellFirst = cellOffset + 2*pPage->nCell;
48536    iCellLast = usableSize - 4;
48537#if defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
48538    {
48539      int i;            /* Index into the cell pointer array */
48540      int sz;           /* Size of a cell */
48541
48542      if( !pPage->leaf ) iCellLast--;
48543      for(i=0; i<pPage->nCell; i++){
48544        pc = get2byte(&data[cellOffset+i*2]);
48545        testcase( pc==iCellFirst );
48546        testcase( pc==iCellLast );
48547        if( pc<iCellFirst || pc>iCellLast ){
48548          return SQLITE_CORRUPT_BKPT;
48549        }
48550        sz = cellSizePtr(pPage, &data[pc]);
48551        testcase( pc+sz==usableSize );
48552        if( pc+sz>usableSize ){
48553          return SQLITE_CORRUPT_BKPT;
48554        }
48555      }
48556      if( !pPage->leaf ) iCellLast++;
48557    }
48558#endif
48559
48560    /* Compute the total free space on the page */
48561    pc = get2byte(&data[hdr+1]);
48562    nFree = data[hdr+7] + top;
48563    while( pc>0 ){
48564      u16 next, size;
48565      if( pc<iCellFirst || pc>iCellLast ){
48566        /* Start of free block is off the page */
48567        return SQLITE_CORRUPT_BKPT;
48568      }
48569      next = get2byte(&data[pc]);
48570      size = get2byte(&data[pc+2]);
48571      if( (next>0 && next<=pc+size+3) || pc+size>usableSize ){
48572        /* Free blocks must be in ascending order. And the last byte of
48573	** the free-block must lie on the database page.  */
48574        return SQLITE_CORRUPT_BKPT;
48575      }
48576      nFree = nFree + size;
48577      pc = next;
48578    }
48579
48580    /* At this point, nFree contains the sum of the offset to the start
48581    ** of the cell-content area plus the number of free bytes within
48582    ** the cell-content area. If this is greater than the usable-size
48583    ** of the page, then the page must be corrupted. This check also
48584    ** serves to verify that the offset to the start of the cell-content
48585    ** area, according to the page header, lies within the page.
48586    */
48587    if( nFree>usableSize ){
48588      return SQLITE_CORRUPT_BKPT;
48589    }
48590    pPage->nFree = (u16)(nFree - iCellFirst);
48591    pPage->isInit = 1;
48592  }
48593  return SQLITE_OK;
48594}
48595
48596/*
48597** Set up a raw page so that it looks like a database page holding
48598** no entries.
48599*/
48600static void zeroPage(MemPage *pPage, int flags){
48601  unsigned char *data = pPage->aData;
48602  BtShared *pBt = pPage->pBt;
48603  u8 hdr = pPage->hdrOffset;
48604  u16 first;
48605
48606  assert( sqlite3PagerPagenumber(pPage->pDbPage)==pPage->pgno );
48607  assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
48608  assert( sqlite3PagerGetData(pPage->pDbPage) == data );
48609  assert( sqlite3PagerIswriteable(pPage->pDbPage) );
48610  assert( sqlite3_mutex_held(pBt->mutex) );
48611  if( pBt->secureDelete ){
48612    memset(&data[hdr], 0, pBt->usableSize - hdr);
48613  }
48614  data[hdr] = (char)flags;
48615  first = hdr + 8 + 4*((flags&PTF_LEAF)==0 ?1:0);
48616  memset(&data[hdr+1], 0, 4);
48617  data[hdr+7] = 0;
48618  put2byte(&data[hdr+5], pBt->usableSize);
48619  pPage->nFree = (u16)(pBt->usableSize - first);
48620  decodeFlags(pPage, flags);
48621  pPage->hdrOffset = hdr;
48622  pPage->cellOffset = first;
48623  pPage->nOverflow = 0;
48624  assert( pBt->pageSize>=512 && pBt->pageSize<=65536 );
48625  pPage->maskPage = (u16)(pBt->pageSize - 1);
48626  pPage->nCell = 0;
48627  pPage->isInit = 1;
48628}
48629
48630
48631/*
48632** Convert a DbPage obtained from the pager into a MemPage used by
48633** the btree layer.
48634*/
48635static MemPage *btreePageFromDbPage(DbPage *pDbPage, Pgno pgno, BtShared *pBt){
48636  MemPage *pPage = (MemPage*)sqlite3PagerGetExtra(pDbPage);
48637  pPage->aData = sqlite3PagerGetData(pDbPage);
48638  pPage->pDbPage = pDbPage;
48639  pPage->pBt = pBt;
48640  pPage->pgno = pgno;
48641  pPage->hdrOffset = pPage->pgno==1 ? 100 : 0;
48642  return pPage;
48643}
48644
48645/*
48646** Get a page from the pager.  Initialize the MemPage.pBt and
48647** MemPage.aData elements if needed.
48648**
48649** If the noContent flag is set, it means that we do not care about
48650** the content of the page at this time.  So do not go to the disk
48651** to fetch the content.  Just fill in the content with zeros for now.
48652** If in the future we call sqlite3PagerWrite() on this page, that
48653** means we have started to be concerned about content and the disk
48654** read should occur at that point.
48655*/
48656static int btreeGetPage(
48657  BtShared *pBt,       /* The btree */
48658  Pgno pgno,           /* Number of the page to fetch */
48659  MemPage **ppPage,    /* Return the page in this parameter */
48660  int noContent        /* Do not load page content if true */
48661){
48662  int rc;
48663  DbPage *pDbPage;
48664
48665  assert( sqlite3_mutex_held(pBt->mutex) );
48666  rc = sqlite3PagerAcquire(pBt->pPager, pgno, (DbPage**)&pDbPage, noContent);
48667  if( rc ) return rc;
48668  *ppPage = btreePageFromDbPage(pDbPage, pgno, pBt);
48669  return SQLITE_OK;
48670}
48671
48672/*
48673** Retrieve a page from the pager cache. If the requested page is not
48674** already in the pager cache return NULL. Initialize the MemPage.pBt and
48675** MemPage.aData elements if needed.
48676*/
48677static MemPage *btreePageLookup(BtShared *pBt, Pgno pgno){
48678  DbPage *pDbPage;
48679  assert( sqlite3_mutex_held(pBt->mutex) );
48680  pDbPage = sqlite3PagerLookup(pBt->pPager, pgno);
48681  if( pDbPage ){
48682    return btreePageFromDbPage(pDbPage, pgno, pBt);
48683  }
48684  return 0;
48685}
48686
48687/*
48688** Return the size of the database file in pages. If there is any kind of
48689** error, return ((unsigned int)-1).
48690*/
48691static Pgno btreePagecount(BtShared *pBt){
48692  return pBt->nPage;
48693}
48694SQLITE_PRIVATE u32 sqlite3BtreeLastPage(Btree *p){
48695  assert( sqlite3BtreeHoldsMutex(p) );
48696  assert( ((p->pBt->nPage)&0x8000000)==0 );
48697  return (int)btreePagecount(p->pBt);
48698}
48699
48700/*
48701** Get a page from the pager and initialize it.  This routine is just a
48702** convenience wrapper around separate calls to btreeGetPage() and
48703** btreeInitPage().
48704**
48705** If an error occurs, then the value *ppPage is set to is undefined. It
48706** may remain unchanged, or it may be set to an invalid value.
48707*/
48708static int getAndInitPage(
48709  BtShared *pBt,          /* The database file */
48710  Pgno pgno,           /* Number of the page to get */
48711  MemPage **ppPage     /* Write the page pointer here */
48712){
48713  int rc;
48714  assert( sqlite3_mutex_held(pBt->mutex) );
48715
48716  if( pgno>btreePagecount(pBt) ){
48717    rc = SQLITE_CORRUPT_BKPT;
48718  }else{
48719    rc = btreeGetPage(pBt, pgno, ppPage, 0);
48720    if( rc==SQLITE_OK ){
48721      rc = btreeInitPage(*ppPage);
48722      if( rc!=SQLITE_OK ){
48723        releasePage(*ppPage);
48724      }
48725    }
48726  }
48727
48728  testcase( pgno==0 );
48729  assert( pgno!=0 || rc==SQLITE_CORRUPT );
48730  return rc;
48731}
48732
48733/*
48734** Release a MemPage.  This should be called once for each prior
48735** call to btreeGetPage.
48736*/
48737static void releasePage(MemPage *pPage){
48738  if( pPage ){
48739    assert( pPage->aData );
48740    assert( pPage->pBt );
48741    assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
48742    assert( sqlite3PagerGetData(pPage->pDbPage)==pPage->aData );
48743    assert( sqlite3_mutex_held(pPage->pBt->mutex) );
48744    sqlite3PagerUnref(pPage->pDbPage);
48745  }
48746}
48747
48748/*
48749** During a rollback, when the pager reloads information into the cache
48750** so that the cache is restored to its original state at the start of
48751** the transaction, for each page restored this routine is called.
48752**
48753** This routine needs to reset the extra data section at the end of the
48754** page to agree with the restored data.
48755*/
48756static void pageReinit(DbPage *pData){
48757  MemPage *pPage;
48758  pPage = (MemPage *)sqlite3PagerGetExtra(pData);
48759  assert( sqlite3PagerPageRefcount(pData)>0 );
48760  if( pPage->isInit ){
48761    assert( sqlite3_mutex_held(pPage->pBt->mutex) );
48762    pPage->isInit = 0;
48763    if( sqlite3PagerPageRefcount(pData)>1 ){
48764      /* pPage might not be a btree page;  it might be an overflow page
48765      ** or ptrmap page or a free page.  In those cases, the following
48766      ** call to btreeInitPage() will likely return SQLITE_CORRUPT.
48767      ** But no harm is done by this.  And it is very important that
48768      ** btreeInitPage() be called on every btree page so we make
48769      ** the call for every page that comes in for re-initing. */
48770      btreeInitPage(pPage);
48771    }
48772  }
48773}
48774
48775/*
48776** Invoke the busy handler for a btree.
48777*/
48778static int btreeInvokeBusyHandler(void *pArg){
48779  BtShared *pBt = (BtShared*)pArg;
48780  assert( pBt->db );
48781  assert( sqlite3_mutex_held(pBt->db->mutex) );
48782  return sqlite3InvokeBusyHandler(&pBt->db->busyHandler);
48783}
48784
48785/*
48786** Open a database file.
48787**
48788** zFilename is the name of the database file.  If zFilename is NULL
48789** then an ephemeral database is created.  The ephemeral database might
48790** be exclusively in memory, or it might use a disk-based memory cache.
48791** Either way, the ephemeral database will be automatically deleted
48792** when sqlite3BtreeClose() is called.
48793**
48794** If zFilename is ":memory:" then an in-memory database is created
48795** that is automatically destroyed when it is closed.
48796**
48797** The "flags" parameter is a bitmask that might contain bits
48798** BTREE_OMIT_JOURNAL and/or BTREE_NO_READLOCK.  The BTREE_NO_READLOCK
48799** bit is also set if the SQLITE_NoReadlock flags is set in db->flags.
48800** These flags are passed through into sqlite3PagerOpen() and must
48801** be the same values as PAGER_OMIT_JOURNAL and PAGER_NO_READLOCK.
48802**
48803** If the database is already opened in the same database connection
48804** and we are in shared cache mode, then the open will fail with an
48805** SQLITE_CONSTRAINT error.  We cannot allow two or more BtShared
48806** objects in the same database connection since doing so will lead
48807** to problems with locking.
48808*/
48809SQLITE_PRIVATE int sqlite3BtreeOpen(
48810  const char *zFilename,  /* Name of the file containing the BTree database */
48811  sqlite3 *db,            /* Associated database handle */
48812  Btree **ppBtree,        /* Pointer to new Btree object written here */
48813  int flags,              /* Options */
48814  int vfsFlags            /* Flags passed through to sqlite3_vfs.xOpen() */
48815){
48816  sqlite3_vfs *pVfs;             /* The VFS to use for this btree */
48817  BtShared *pBt = 0;             /* Shared part of btree structure */
48818  Btree *p;                      /* Handle to return */
48819  sqlite3_mutex *mutexOpen = 0;  /* Prevents a race condition. Ticket #3537 */
48820  int rc = SQLITE_OK;            /* Result code from this function */
48821  u8 nReserve;                   /* Byte of unused space on each page */
48822  unsigned char zDbHeader[100];  /* Database header content */
48823
48824  /* True if opening an ephemeral, temporary database */
48825  const int isTempDb = zFilename==0 || zFilename[0]==0;
48826
48827  /* Set the variable isMemdb to true for an in-memory database, or
48828  ** false for a file-based database.
48829  */
48830#ifdef SQLITE_OMIT_MEMORYDB
48831  const int isMemdb = 0;
48832#else
48833  const int isMemdb = (zFilename && strcmp(zFilename, ":memory:")==0)
48834                       || (isTempDb && sqlite3TempInMemory(db));
48835#endif
48836
48837  assert( db!=0 );
48838  assert( sqlite3_mutex_held(db->mutex) );
48839  assert( (flags&0xff)==flags );   /* flags fit in 8 bits */
48840
48841  /* Only a BTREE_SINGLE database can be BTREE_UNORDERED */
48842  assert( (flags & BTREE_UNORDERED)==0 || (flags & BTREE_SINGLE)!=0 );
48843
48844  /* A BTREE_SINGLE database is always a temporary and/or ephemeral */
48845  assert( (flags & BTREE_SINGLE)==0 || isTempDb );
48846
48847  if( db->flags & SQLITE_NoReadlock ){
48848    flags |= BTREE_NO_READLOCK;
48849  }
48850  if( isMemdb ){
48851    flags |= BTREE_MEMORY;
48852  }
48853  if( (vfsFlags & SQLITE_OPEN_MAIN_DB)!=0 && (isMemdb || isTempDb) ){
48854    vfsFlags = (vfsFlags & ~SQLITE_OPEN_MAIN_DB) | SQLITE_OPEN_TEMP_DB;
48855  }
48856  pVfs = db->pVfs;
48857  p = sqlite3MallocZero(sizeof(Btree));
48858  if( !p ){
48859    return SQLITE_NOMEM;
48860  }
48861  p->inTrans = TRANS_NONE;
48862  p->db = db;
48863#ifndef SQLITE_OMIT_SHARED_CACHE
48864  p->lock.pBtree = p;
48865  p->lock.iTable = 1;
48866#endif
48867
48868#if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
48869  /*
48870  ** If this Btree is a candidate for shared cache, try to find an
48871  ** existing BtShared object that we can share with
48872  */
48873  if( isMemdb==0 && isTempDb==0 ){
48874    if( vfsFlags & SQLITE_OPEN_SHAREDCACHE ){
48875      int nFullPathname = pVfs->mxPathname+1;
48876      char *zFullPathname = sqlite3Malloc(nFullPathname);
48877      sqlite3_mutex *mutexShared;
48878      p->sharable = 1;
48879      if( !zFullPathname ){
48880        sqlite3_free(p);
48881        return SQLITE_NOMEM;
48882      }
48883      sqlite3OsFullPathname(pVfs, zFilename, nFullPathname, zFullPathname);
48884      mutexOpen = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_OPEN);
48885      sqlite3_mutex_enter(mutexOpen);
48886      mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
48887      sqlite3_mutex_enter(mutexShared);
48888      for(pBt=GLOBAL(BtShared*,sqlite3SharedCacheList); pBt; pBt=pBt->pNext){
48889        assert( pBt->nRef>0 );
48890        if( 0==strcmp(zFullPathname, sqlite3PagerFilename(pBt->pPager))
48891                 && sqlite3PagerVfs(pBt->pPager)==pVfs ){
48892          int iDb;
48893          for(iDb=db->nDb-1; iDb>=0; iDb--){
48894            Btree *pExisting = db->aDb[iDb].pBt;
48895            if( pExisting && pExisting->pBt==pBt ){
48896              sqlite3_mutex_leave(mutexShared);
48897              sqlite3_mutex_leave(mutexOpen);
48898              sqlite3_free(zFullPathname);
48899              sqlite3_free(p);
48900              return SQLITE_CONSTRAINT;
48901            }
48902          }
48903          p->pBt = pBt;
48904          pBt->nRef++;
48905          break;
48906        }
48907      }
48908      sqlite3_mutex_leave(mutexShared);
48909      sqlite3_free(zFullPathname);
48910    }
48911#ifdef SQLITE_DEBUG
48912    else{
48913      /* In debug mode, we mark all persistent databases as sharable
48914      ** even when they are not.  This exercises the locking code and
48915      ** gives more opportunity for asserts(sqlite3_mutex_held())
48916      ** statements to find locking problems.
48917      */
48918      p->sharable = 1;
48919    }
48920#endif
48921  }
48922#endif
48923  if( pBt==0 ){
48924    /*
48925    ** The following asserts make sure that structures used by the btree are
48926    ** the right size.  This is to guard against size changes that result
48927    ** when compiling on a different architecture.
48928    */
48929    assert( sizeof(i64)==8 || sizeof(i64)==4 );
48930    assert( sizeof(u64)==8 || sizeof(u64)==4 );
48931    assert( sizeof(u32)==4 );
48932    assert( sizeof(u16)==2 );
48933    assert( sizeof(Pgno)==4 );
48934
48935    pBt = sqlite3MallocZero( sizeof(*pBt) );
48936    if( pBt==0 ){
48937      rc = SQLITE_NOMEM;
48938      goto btree_open_out;
48939    }
48940    rc = sqlite3PagerOpen(pVfs, &pBt->pPager, zFilename,
48941                          EXTRA_SIZE, flags, vfsFlags, pageReinit);
48942    if( rc==SQLITE_OK ){
48943      rc = sqlite3PagerReadFileheader(pBt->pPager,sizeof(zDbHeader),zDbHeader);
48944    }
48945    if( rc!=SQLITE_OK ){
48946      goto btree_open_out;
48947    }
48948    pBt->openFlags = (u8)flags;
48949    pBt->db = db;
48950    sqlite3PagerSetBusyhandler(pBt->pPager, btreeInvokeBusyHandler, pBt);
48951    p->pBt = pBt;
48952
48953    pBt->pCursor = 0;
48954    pBt->pPage1 = 0;
48955    pBt->readOnly = sqlite3PagerIsreadonly(pBt->pPager);
48956#ifdef SQLITE_SECURE_DELETE
48957    pBt->secureDelete = 1;
48958#endif
48959    pBt->pageSize = (zDbHeader[16]<<8) | (zDbHeader[17]<<16);
48960    if( pBt->pageSize<512 || pBt->pageSize>SQLITE_MAX_PAGE_SIZE
48961         || ((pBt->pageSize-1)&pBt->pageSize)!=0 ){
48962      pBt->pageSize = 0;
48963#ifndef SQLITE_OMIT_AUTOVACUUM
48964      /* If the magic name ":memory:" will create an in-memory database, then
48965      ** leave the autoVacuum mode at 0 (do not auto-vacuum), even if
48966      ** SQLITE_DEFAULT_AUTOVACUUM is true. On the other hand, if
48967      ** SQLITE_OMIT_MEMORYDB has been defined, then ":memory:" is just a
48968      ** regular file-name. In this case the auto-vacuum applies as per normal.
48969      */
48970      if( zFilename && !isMemdb ){
48971        pBt->autoVacuum = (SQLITE_DEFAULT_AUTOVACUUM ? 1 : 0);
48972        pBt->incrVacuum = (SQLITE_DEFAULT_AUTOVACUUM==2 ? 1 : 0);
48973      }
48974#endif
48975      nReserve = 0;
48976    }else{
48977      nReserve = zDbHeader[20];
48978      pBt->pageSizeFixed = 1;
48979#ifndef SQLITE_OMIT_AUTOVACUUM
48980      pBt->autoVacuum = (get4byte(&zDbHeader[36 + 4*4])?1:0);
48981      pBt->incrVacuum = (get4byte(&zDbHeader[36 + 7*4])?1:0);
48982#endif
48983    }
48984    rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
48985    if( rc ) goto btree_open_out;
48986    pBt->usableSize = pBt->pageSize - nReserve;
48987    assert( (pBt->pageSize & 7)==0 );  /* 8-byte alignment of pageSize */
48988
48989#if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
48990    /* Add the new BtShared object to the linked list sharable BtShareds.
48991    */
48992    if( p->sharable ){
48993      sqlite3_mutex *mutexShared;
48994      pBt->nRef = 1;
48995      mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
48996      if( SQLITE_THREADSAFE && sqlite3GlobalConfig.bCoreMutex ){
48997        pBt->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_FAST);
48998        if( pBt->mutex==0 ){
48999          rc = SQLITE_NOMEM;
49000          db->mallocFailed = 0;
49001          goto btree_open_out;
49002        }
49003      }
49004      sqlite3_mutex_enter(mutexShared);
49005      pBt->pNext = GLOBAL(BtShared*,sqlite3SharedCacheList);
49006      GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt;
49007      sqlite3_mutex_leave(mutexShared);
49008    }
49009#endif
49010  }
49011
49012#if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
49013  /* If the new Btree uses a sharable pBtShared, then link the new
49014  ** Btree into the list of all sharable Btrees for the same connection.
49015  ** The list is kept in ascending order by pBt address.
49016  */
49017  if( p->sharable ){
49018    int i;
49019    Btree *pSib;
49020    for(i=0; i<db->nDb; i++){
49021      if( (pSib = db->aDb[i].pBt)!=0 && pSib->sharable ){
49022        while( pSib->pPrev ){ pSib = pSib->pPrev; }
49023        if( p->pBt<pSib->pBt ){
49024          p->pNext = pSib;
49025          p->pPrev = 0;
49026          pSib->pPrev = p;
49027        }else{
49028          while( pSib->pNext && pSib->pNext->pBt<p->pBt ){
49029            pSib = pSib->pNext;
49030          }
49031          p->pNext = pSib->pNext;
49032          p->pPrev = pSib;
49033          if( p->pNext ){
49034            p->pNext->pPrev = p;
49035          }
49036          pSib->pNext = p;
49037        }
49038        break;
49039      }
49040    }
49041  }
49042#endif
49043  *ppBtree = p;
49044
49045btree_open_out:
49046  if( rc!=SQLITE_OK ){
49047    if( pBt && pBt->pPager ){
49048      sqlite3PagerClose(pBt->pPager);
49049    }
49050    sqlite3_free(pBt);
49051    sqlite3_free(p);
49052    *ppBtree = 0;
49053  }else{
49054    /* If the B-Tree was successfully opened, set the pager-cache size to the
49055    ** default value. Except, when opening on an existing shared pager-cache,
49056    ** do not change the pager-cache size.
49057    */
49058    if( sqlite3BtreeSchema(p, 0, 0)==0 ){
49059      sqlite3PagerSetCachesize(p->pBt->pPager, SQLITE_DEFAULT_CACHE_SIZE);
49060    }
49061  }
49062  if( mutexOpen ){
49063    assert( sqlite3_mutex_held(mutexOpen) );
49064    sqlite3_mutex_leave(mutexOpen);
49065  }
49066  return rc;
49067}
49068
49069/*
49070** Decrement the BtShared.nRef counter.  When it reaches zero,
49071** remove the BtShared structure from the sharing list.  Return
49072** true if the BtShared.nRef counter reaches zero and return
49073** false if it is still positive.
49074*/
49075static int removeFromSharingList(BtShared *pBt){
49076#ifndef SQLITE_OMIT_SHARED_CACHE
49077  sqlite3_mutex *pMaster;
49078  BtShared *pList;
49079  int removed = 0;
49080
49081  assert( sqlite3_mutex_notheld(pBt->mutex) );
49082  pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
49083  sqlite3_mutex_enter(pMaster);
49084  pBt->nRef--;
49085  if( pBt->nRef<=0 ){
49086    if( GLOBAL(BtShared*,sqlite3SharedCacheList)==pBt ){
49087      GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt->pNext;
49088    }else{
49089      pList = GLOBAL(BtShared*,sqlite3SharedCacheList);
49090      while( ALWAYS(pList) && pList->pNext!=pBt ){
49091        pList=pList->pNext;
49092      }
49093      if( ALWAYS(pList) ){
49094        pList->pNext = pBt->pNext;
49095      }
49096    }
49097    if( SQLITE_THREADSAFE ){
49098      sqlite3_mutex_free(pBt->mutex);
49099    }
49100    removed = 1;
49101  }
49102  sqlite3_mutex_leave(pMaster);
49103  return removed;
49104#else
49105  return 1;
49106#endif
49107}
49108
49109/*
49110** Make sure pBt->pTmpSpace points to an allocation of
49111** MX_CELL_SIZE(pBt) bytes.
49112*/
49113static void allocateTempSpace(BtShared *pBt){
49114  if( !pBt->pTmpSpace ){
49115    pBt->pTmpSpace = sqlite3PageMalloc( pBt->pageSize );
49116  }
49117}
49118
49119/*
49120** Free the pBt->pTmpSpace allocation
49121*/
49122static void freeTempSpace(BtShared *pBt){
49123  sqlite3PageFree( pBt->pTmpSpace);
49124  pBt->pTmpSpace = 0;
49125}
49126
49127/*
49128** Close an open database and invalidate all cursors.
49129*/
49130SQLITE_PRIVATE int sqlite3BtreeClose(Btree *p){
49131  BtShared *pBt = p->pBt;
49132  BtCursor *pCur;
49133
49134  /* Close all cursors opened via this handle.  */
49135  assert( sqlite3_mutex_held(p->db->mutex) );
49136  sqlite3BtreeEnter(p);
49137  pCur = pBt->pCursor;
49138  while( pCur ){
49139    BtCursor *pTmp = pCur;
49140    pCur = pCur->pNext;
49141    if( pTmp->pBtree==p ){
49142      sqlite3BtreeCloseCursor(pTmp);
49143    }
49144  }
49145
49146  /* Rollback any active transaction and free the handle structure.
49147  ** The call to sqlite3BtreeRollback() drops any table-locks held by
49148  ** this handle.
49149  */
49150  sqlite3BtreeRollback(p);
49151  sqlite3BtreeLeave(p);
49152
49153  /* If there are still other outstanding references to the shared-btree
49154  ** structure, return now. The remainder of this procedure cleans
49155  ** up the shared-btree.
49156  */
49157  assert( p->wantToLock==0 && p->locked==0 );
49158  if( !p->sharable || removeFromSharingList(pBt) ){
49159    /* The pBt is no longer on the sharing list, so we can access
49160    ** it without having to hold the mutex.
49161    **
49162    ** Clean out and delete the BtShared object.
49163    */
49164    assert( !pBt->pCursor );
49165    sqlite3PagerClose(pBt->pPager);
49166    if( pBt->xFreeSchema && pBt->pSchema ){
49167      pBt->xFreeSchema(pBt->pSchema);
49168    }
49169    sqlite3DbFree(0, pBt->pSchema);
49170    freeTempSpace(pBt);
49171    sqlite3_free(pBt);
49172  }
49173
49174#ifndef SQLITE_OMIT_SHARED_CACHE
49175  assert( p->wantToLock==0 );
49176  assert( p->locked==0 );
49177  if( p->pPrev ) p->pPrev->pNext = p->pNext;
49178  if( p->pNext ) p->pNext->pPrev = p->pPrev;
49179#endif
49180
49181  sqlite3_free(p);
49182  return SQLITE_OK;
49183}
49184
49185/*
49186** Change the limit on the number of pages allowed in the cache.
49187**
49188** The maximum number of cache pages is set to the absolute
49189** value of mxPage.  If mxPage is negative, the pager will
49190** operate asynchronously - it will not stop to do fsync()s
49191** to insure data is written to the disk surface before
49192** continuing.  Transactions still work if synchronous is off,
49193** and the database cannot be corrupted if this program
49194** crashes.  But if the operating system crashes or there is
49195** an abrupt power failure when synchronous is off, the database
49196** could be left in an inconsistent and unrecoverable state.
49197** Synchronous is on by default so database corruption is not
49198** normally a worry.
49199*/
49200SQLITE_PRIVATE int sqlite3BtreeSetCacheSize(Btree *p, int mxPage){
49201  BtShared *pBt = p->pBt;
49202  assert( sqlite3_mutex_held(p->db->mutex) );
49203  sqlite3BtreeEnter(p);
49204  sqlite3PagerSetCachesize(pBt->pPager, mxPage);
49205  sqlite3BtreeLeave(p);
49206  return SQLITE_OK;
49207}
49208
49209/*
49210** Change the way data is synced to disk in order to increase or decrease
49211** how well the database resists damage due to OS crashes and power
49212** failures.  Level 1 is the same as asynchronous (no syncs() occur and
49213** there is a high probability of damage)  Level 2 is the default.  There
49214** is a very low but non-zero probability of damage.  Level 3 reduces the
49215** probability of damage to near zero but with a write performance reduction.
49216*/
49217#ifndef SQLITE_OMIT_PAGER_PRAGMAS
49218SQLITE_PRIVATE int sqlite3BtreeSetSafetyLevel(
49219  Btree *p,              /* The btree to set the safety level on */
49220  int level,             /* PRAGMA synchronous.  1=OFF, 2=NORMAL, 3=FULL */
49221  int fullSync,          /* PRAGMA fullfsync. */
49222  int ckptFullSync       /* PRAGMA checkpoint_fullfync */
49223){
49224  BtShared *pBt = p->pBt;
49225  assert( sqlite3_mutex_held(p->db->mutex) );
49226  assert( level>=1 && level<=3 );
49227  sqlite3BtreeEnter(p);
49228  sqlite3PagerSetSafetyLevel(pBt->pPager, level, fullSync, ckptFullSync);
49229  sqlite3BtreeLeave(p);
49230  return SQLITE_OK;
49231}
49232#endif
49233
49234/*
49235** Return TRUE if the given btree is set to safety level 1.  In other
49236** words, return TRUE if no sync() occurs on the disk files.
49237*/
49238SQLITE_PRIVATE int sqlite3BtreeSyncDisabled(Btree *p){
49239  BtShared *pBt = p->pBt;
49240  int rc;
49241  assert( sqlite3_mutex_held(p->db->mutex) );
49242  sqlite3BtreeEnter(p);
49243  assert( pBt && pBt->pPager );
49244  rc = sqlite3PagerNosync(pBt->pPager);
49245  sqlite3BtreeLeave(p);
49246  return rc;
49247}
49248
49249/*
49250** Change the default pages size and the number of reserved bytes per page.
49251** Or, if the page size has already been fixed, return SQLITE_READONLY
49252** without changing anything.
49253**
49254** The page size must be a power of 2 between 512 and 65536.  If the page
49255** size supplied does not meet this constraint then the page size is not
49256** changed.
49257**
49258** Page sizes are constrained to be a power of two so that the region
49259** of the database file used for locking (beginning at PENDING_BYTE,
49260** the first byte past the 1GB boundary, 0x40000000) needs to occur
49261** at the beginning of a page.
49262**
49263** If parameter nReserve is less than zero, then the number of reserved
49264** bytes per page is left unchanged.
49265**
49266** If the iFix!=0 then the pageSizeFixed flag is set so that the page size
49267** and autovacuum mode can no longer be changed.
49268*/
49269SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree *p, int pageSize, int nReserve, int iFix){
49270  int rc = SQLITE_OK;
49271  BtShared *pBt = p->pBt;
49272  assert( nReserve>=-1 && nReserve<=255 );
49273  sqlite3BtreeEnter(p);
49274  if( pBt->pageSizeFixed ){
49275    sqlite3BtreeLeave(p);
49276    return SQLITE_READONLY;
49277  }
49278  if( nReserve<0 ){
49279    nReserve = pBt->pageSize - pBt->usableSize;
49280  }
49281  assert( nReserve>=0 && nReserve<=255 );
49282  if( pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE &&
49283        ((pageSize-1)&pageSize)==0 ){
49284    assert( (pageSize & 7)==0 );
49285    assert( !pBt->pPage1 && !pBt->pCursor );
49286    pBt->pageSize = (u32)pageSize;
49287    freeTempSpace(pBt);
49288  }
49289  rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
49290  pBt->usableSize = pBt->pageSize - (u16)nReserve;
49291  if( iFix ) pBt->pageSizeFixed = 1;
49292  sqlite3BtreeLeave(p);
49293  return rc;
49294}
49295
49296/*
49297** Return the currently defined page size
49298*/
49299SQLITE_PRIVATE int sqlite3BtreeGetPageSize(Btree *p){
49300  return p->pBt->pageSize;
49301}
49302
49303#if !defined(SQLITE_OMIT_PAGER_PRAGMAS) || !defined(SQLITE_OMIT_VACUUM)
49304/*
49305** Return the number of bytes of space at the end of every page that
49306** are intentually left unused.  This is the "reserved" space that is
49307** sometimes used by extensions.
49308*/
49309SQLITE_PRIVATE int sqlite3BtreeGetReserve(Btree *p){
49310  int n;
49311  sqlite3BtreeEnter(p);
49312  n = p->pBt->pageSize - p->pBt->usableSize;
49313  sqlite3BtreeLeave(p);
49314  return n;
49315}
49316
49317/*
49318** Set the maximum page count for a database if mxPage is positive.
49319** No changes are made if mxPage is 0 or negative.
49320** Regardless of the value of mxPage, return the maximum page count.
49321*/
49322SQLITE_PRIVATE int sqlite3BtreeMaxPageCount(Btree *p, int mxPage){
49323  int n;
49324  sqlite3BtreeEnter(p);
49325  n = sqlite3PagerMaxPageCount(p->pBt->pPager, mxPage);
49326  sqlite3BtreeLeave(p);
49327  return n;
49328}
49329
49330/*
49331** Set the secureDelete flag if newFlag is 0 or 1.  If newFlag is -1,
49332** then make no changes.  Always return the value of the secureDelete
49333** setting after the change.
49334*/
49335SQLITE_PRIVATE int sqlite3BtreeSecureDelete(Btree *p, int newFlag){
49336  int b;
49337  if( p==0 ) return 0;
49338  sqlite3BtreeEnter(p);
49339  if( newFlag>=0 ){
49340    p->pBt->secureDelete = (newFlag!=0) ? 1 : 0;
49341  }
49342  b = p->pBt->secureDelete;
49343  sqlite3BtreeLeave(p);
49344  return b;
49345}
49346#endif /* !defined(SQLITE_OMIT_PAGER_PRAGMAS) || !defined(SQLITE_OMIT_VACUUM) */
49347
49348/*
49349** Change the 'auto-vacuum' property of the database. If the 'autoVacuum'
49350** parameter is non-zero, then auto-vacuum mode is enabled. If zero, it
49351** is disabled. The default value for the auto-vacuum property is
49352** determined by the SQLITE_DEFAULT_AUTOVACUUM macro.
49353*/
49354SQLITE_PRIVATE int sqlite3BtreeSetAutoVacuum(Btree *p, int autoVacuum){
49355#ifdef SQLITE_OMIT_AUTOVACUUM
49356  return SQLITE_READONLY;
49357#else
49358  BtShared *pBt = p->pBt;
49359  int rc = SQLITE_OK;
49360  u8 av = (u8)autoVacuum;
49361
49362  sqlite3BtreeEnter(p);
49363  if( pBt->pageSizeFixed && (av ?1:0)!=pBt->autoVacuum ){
49364    rc = SQLITE_READONLY;
49365  }else{
49366    pBt->autoVacuum = av ?1:0;
49367    pBt->incrVacuum = av==2 ?1:0;
49368  }
49369  sqlite3BtreeLeave(p);
49370  return rc;
49371#endif
49372}
49373
49374/*
49375** Return the value of the 'auto-vacuum' property. If auto-vacuum is
49376** enabled 1 is returned. Otherwise 0.
49377*/
49378SQLITE_PRIVATE int sqlite3BtreeGetAutoVacuum(Btree *p){
49379#ifdef SQLITE_OMIT_AUTOVACUUM
49380  return BTREE_AUTOVACUUM_NONE;
49381#else
49382  int rc;
49383  sqlite3BtreeEnter(p);
49384  rc = (
49385    (!p->pBt->autoVacuum)?BTREE_AUTOVACUUM_NONE:
49386    (!p->pBt->incrVacuum)?BTREE_AUTOVACUUM_FULL:
49387    BTREE_AUTOVACUUM_INCR
49388  );
49389  sqlite3BtreeLeave(p);
49390  return rc;
49391#endif
49392}
49393
49394
49395/*
49396** Get a reference to pPage1 of the database file.  This will
49397** also acquire a readlock on that file.
49398**
49399** SQLITE_OK is returned on success.  If the file is not a
49400** well-formed database file, then SQLITE_CORRUPT is returned.
49401** SQLITE_BUSY is returned if the database is locked.  SQLITE_NOMEM
49402** is returned if we run out of memory.
49403*/
49404static int lockBtree(BtShared *pBt){
49405  int rc;              /* Result code from subfunctions */
49406  MemPage *pPage1;     /* Page 1 of the database file */
49407  int nPage;           /* Number of pages in the database */
49408  int nPageFile = 0;   /* Number of pages in the database file */
49409  int nPageHeader;     /* Number of pages in the database according to hdr */
49410
49411  assert( sqlite3_mutex_held(pBt->mutex) );
49412  assert( pBt->pPage1==0 );
49413  rc = sqlite3PagerSharedLock(pBt->pPager);
49414  if( rc!=SQLITE_OK ) return rc;
49415  rc = btreeGetPage(pBt, 1, &pPage1, 0);
49416  if( rc!=SQLITE_OK ) return rc;
49417
49418  /* Do some checking to help insure the file we opened really is
49419  ** a valid database file.
49420  */
49421  nPage = nPageHeader = get4byte(28+(u8*)pPage1->aData);
49422  sqlite3PagerPagecount(pBt->pPager, &nPageFile);
49423  if( nPage==0 || memcmp(24+(u8*)pPage1->aData, 92+(u8*)pPage1->aData,4)!=0 ){
49424    nPage = nPageFile;
49425  }
49426  if( nPage>0 ){
49427    u32 pageSize;
49428    u32 usableSize;
49429    u8 *page1 = pPage1->aData;
49430    rc = SQLITE_NOTADB;
49431    if( memcmp(page1, zMagicHeader, 16)!=0 ){
49432      goto page1_init_failed;
49433    }
49434
49435#ifdef SQLITE_OMIT_WAL
49436    if( page1[18]>1 ){
49437      pBt->readOnly = 1;
49438    }
49439    if( page1[19]>1 ){
49440      goto page1_init_failed;
49441    }
49442#else
49443    if( page1[18]>2 ){
49444      pBt->readOnly = 1;
49445    }
49446    if( page1[19]>2 ){
49447      goto page1_init_failed;
49448    }
49449
49450    /* If the write version is set to 2, this database should be accessed
49451    ** in WAL mode. If the log is not already open, open it now. Then
49452    ** return SQLITE_OK and return without populating BtShared.pPage1.
49453    ** The caller detects this and calls this function again. This is
49454    ** required as the version of page 1 currently in the page1 buffer
49455    ** may not be the latest version - there may be a newer one in the log
49456    ** file.
49457    */
49458    if( page1[19]==2 && pBt->doNotUseWAL==0 ){
49459      int isOpen = 0;
49460      rc = sqlite3PagerOpenWal(pBt->pPager, &isOpen);
49461      if( rc!=SQLITE_OK ){
49462        goto page1_init_failed;
49463      }else if( isOpen==0 ){
49464        releasePage(pPage1);
49465        return SQLITE_OK;
49466      }
49467      rc = SQLITE_NOTADB;
49468    }
49469#endif
49470
49471    /* The maximum embedded fraction must be exactly 25%.  And the minimum
49472    ** embedded fraction must be 12.5% for both leaf-data and non-leaf-data.
49473    ** The original design allowed these amounts to vary, but as of
49474    ** version 3.6.0, we require them to be fixed.
49475    */
49476    if( memcmp(&page1[21], "\100\040\040",3)!=0 ){
49477      goto page1_init_failed;
49478    }
49479    pageSize = (page1[16]<<8) | (page1[17]<<16);
49480    if( ((pageSize-1)&pageSize)!=0
49481     || pageSize>SQLITE_MAX_PAGE_SIZE
49482     || pageSize<=256
49483    ){
49484      goto page1_init_failed;
49485    }
49486    assert( (pageSize & 7)==0 );
49487    usableSize = pageSize - page1[20];
49488    if( (u32)pageSize!=pBt->pageSize ){
49489      /* After reading the first page of the database assuming a page size
49490      ** of BtShared.pageSize, we have discovered that the page-size is
49491      ** actually pageSize. Unlock the database, leave pBt->pPage1 at
49492      ** zero and return SQLITE_OK. The caller will call this function
49493      ** again with the correct page-size.
49494      */
49495      releasePage(pPage1);
49496      pBt->usableSize = usableSize;
49497      pBt->pageSize = pageSize;
49498      freeTempSpace(pBt);
49499      rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize,
49500                                   pageSize-usableSize);
49501      return rc;
49502    }
49503    if( (pBt->db->flags & SQLITE_RecoveryMode)==0 && nPage>nPageFile ){
49504      rc = SQLITE_CORRUPT_BKPT;
49505      goto page1_init_failed;
49506    }
49507    if( usableSize<480 ){
49508      goto page1_init_failed;
49509    }
49510    pBt->pageSize = pageSize;
49511    pBt->usableSize = usableSize;
49512#ifndef SQLITE_OMIT_AUTOVACUUM
49513    pBt->autoVacuum = (get4byte(&page1[36 + 4*4])?1:0);
49514    pBt->incrVacuum = (get4byte(&page1[36 + 7*4])?1:0);
49515#endif
49516  }
49517
49518  /* maxLocal is the maximum amount of payload to store locally for
49519  ** a cell.  Make sure it is small enough so that at least minFanout
49520  ** cells can will fit on one page.  We assume a 10-byte page header.
49521  ** Besides the payload, the cell must store:
49522  **     2-byte pointer to the cell
49523  **     4-byte child pointer
49524  **     9-byte nKey value
49525  **     4-byte nData value
49526  **     4-byte overflow page pointer
49527  ** So a cell consists of a 2-byte pointer, a header which is as much as
49528  ** 17 bytes long, 0 to N bytes of payload, and an optional 4 byte overflow
49529  ** page pointer.
49530  */
49531  pBt->maxLocal = (u16)((pBt->usableSize-12)*64/255 - 23);
49532  pBt->minLocal = (u16)((pBt->usableSize-12)*32/255 - 23);
49533  pBt->maxLeaf = (u16)(pBt->usableSize - 35);
49534  pBt->minLeaf = (u16)((pBt->usableSize-12)*32/255 - 23);
49535  assert( pBt->maxLeaf + 23 <= MX_CELL_SIZE(pBt) );
49536  pBt->pPage1 = pPage1;
49537  pBt->nPage = nPage;
49538  return SQLITE_OK;
49539
49540page1_init_failed:
49541  releasePage(pPage1);
49542  pBt->pPage1 = 0;
49543  return rc;
49544}
49545
49546/*
49547** If there are no outstanding cursors and we are not in the middle
49548** of a transaction but there is a read lock on the database, then
49549** this routine unrefs the first page of the database file which
49550** has the effect of releasing the read lock.
49551**
49552** If there is a transaction in progress, this routine is a no-op.
49553*/
49554static void unlockBtreeIfUnused(BtShared *pBt){
49555  assert( sqlite3_mutex_held(pBt->mutex) );
49556  assert( pBt->pCursor==0 || pBt->inTransaction>TRANS_NONE );
49557  if( pBt->inTransaction==TRANS_NONE && pBt->pPage1!=0 ){
49558    assert( pBt->pPage1->aData );
49559    assert( sqlite3PagerRefcount(pBt->pPager)==1 );
49560    assert( pBt->pPage1->aData );
49561    releasePage(pBt->pPage1);
49562    pBt->pPage1 = 0;
49563  }
49564}
49565
49566/*
49567** If pBt points to an empty file then convert that empty file
49568** into a new empty database by initializing the first page of
49569** the database.
49570*/
49571static int newDatabase(BtShared *pBt){
49572  MemPage *pP1;
49573  unsigned char *data;
49574  int rc;
49575
49576  assert( sqlite3_mutex_held(pBt->mutex) );
49577  if( pBt->nPage>0 ){
49578    return SQLITE_OK;
49579  }
49580  pP1 = pBt->pPage1;
49581  assert( pP1!=0 );
49582  data = pP1->aData;
49583  rc = sqlite3PagerWrite(pP1->pDbPage);
49584  if( rc ) return rc;
49585  memcpy(data, zMagicHeader, sizeof(zMagicHeader));
49586  assert( sizeof(zMagicHeader)==16 );
49587  data[16] = (u8)((pBt->pageSize>>8)&0xff);
49588  data[17] = (u8)((pBt->pageSize>>16)&0xff);
49589  data[18] = 1;
49590  data[19] = 1;
49591  assert( pBt->usableSize<=pBt->pageSize && pBt->usableSize+255>=pBt->pageSize);
49592  data[20] = (u8)(pBt->pageSize - pBt->usableSize);
49593  data[21] = 64;
49594  data[22] = 32;
49595  data[23] = 32;
49596  memset(&data[24], 0, 100-24);
49597  zeroPage(pP1, PTF_INTKEY|PTF_LEAF|PTF_LEAFDATA );
49598  pBt->pageSizeFixed = 1;
49599#ifndef SQLITE_OMIT_AUTOVACUUM
49600  assert( pBt->autoVacuum==1 || pBt->autoVacuum==0 );
49601  assert( pBt->incrVacuum==1 || pBt->incrVacuum==0 );
49602  put4byte(&data[36 + 4*4], pBt->autoVacuum);
49603  put4byte(&data[36 + 7*4], pBt->incrVacuum);
49604#endif
49605  pBt->nPage = 1;
49606  data[31] = 1;
49607  return SQLITE_OK;
49608}
49609
49610/*
49611** Attempt to start a new transaction. A write-transaction
49612** is started if the second argument is nonzero, otherwise a read-
49613** transaction.  If the second argument is 2 or more and exclusive
49614** transaction is started, meaning that no other process is allowed
49615** to access the database.  A preexisting transaction may not be
49616** upgraded to exclusive by calling this routine a second time - the
49617** exclusivity flag only works for a new transaction.
49618**
49619** A write-transaction must be started before attempting any
49620** changes to the database.  None of the following routines
49621** will work unless a transaction is started first:
49622**
49623**      sqlite3BtreeCreateTable()
49624**      sqlite3BtreeCreateIndex()
49625**      sqlite3BtreeClearTable()
49626**      sqlite3BtreeDropTable()
49627**      sqlite3BtreeInsert()
49628**      sqlite3BtreeDelete()
49629**      sqlite3BtreeUpdateMeta()
49630**
49631** If an initial attempt to acquire the lock fails because of lock contention
49632** and the database was previously unlocked, then invoke the busy handler
49633** if there is one.  But if there was previously a read-lock, do not
49634** invoke the busy handler - just return SQLITE_BUSY.  SQLITE_BUSY is
49635** returned when there is already a read-lock in order to avoid a deadlock.
49636**
49637** Suppose there are two processes A and B.  A has a read lock and B has
49638** a reserved lock.  B tries to promote to exclusive but is blocked because
49639** of A's read lock.  A tries to promote to reserved but is blocked by B.
49640** One or the other of the two processes must give way or there can be
49641** no progress.  By returning SQLITE_BUSY and not invoking the busy callback
49642** when A already has a read lock, we encourage A to give up and let B
49643** proceed.
49644*/
49645SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree *p, int wrflag){
49646  sqlite3 *pBlock = 0;
49647  BtShared *pBt = p->pBt;
49648  int rc = SQLITE_OK;
49649
49650  sqlite3BtreeEnter(p);
49651  btreeIntegrity(p);
49652
49653  /* If the btree is already in a write-transaction, or it
49654  ** is already in a read-transaction and a read-transaction
49655  ** is requested, this is a no-op.
49656  */
49657  if( p->inTrans==TRANS_WRITE || (p->inTrans==TRANS_READ && !wrflag) ){
49658    goto trans_begun;
49659  }
49660
49661  /* Write transactions are not possible on a read-only database */
49662  if( pBt->readOnly && wrflag ){
49663    rc = SQLITE_READONLY;
49664    goto trans_begun;
49665  }
49666
49667#ifndef SQLITE_OMIT_SHARED_CACHE
49668  /* If another database handle has already opened a write transaction
49669  ** on this shared-btree structure and a second write transaction is
49670  ** requested, return SQLITE_LOCKED.
49671  */
49672  if( (wrflag && pBt->inTransaction==TRANS_WRITE) || pBt->isPending ){
49673    pBlock = pBt->pWriter->db;
49674  }else if( wrflag>1 ){
49675    BtLock *pIter;
49676    for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
49677      if( pIter->pBtree!=p ){
49678        pBlock = pIter->pBtree->db;
49679        break;
49680      }
49681    }
49682  }
49683  if( pBlock ){
49684    sqlite3ConnectionBlocked(p->db, pBlock);
49685    rc = SQLITE_LOCKED_SHAREDCACHE;
49686    goto trans_begun;
49687  }
49688#endif
49689
49690  /* Any read-only or read-write transaction implies a read-lock on
49691  ** page 1. So if some other shared-cache client already has a write-lock
49692  ** on page 1, the transaction cannot be opened. */
49693  rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK);
49694  if( SQLITE_OK!=rc ) goto trans_begun;
49695
49696  pBt->initiallyEmpty = (u8)(pBt->nPage==0);
49697  do {
49698    /* Call lockBtree() until either pBt->pPage1 is populated or
49699    ** lockBtree() returns something other than SQLITE_OK. lockBtree()
49700    ** may return SQLITE_OK but leave pBt->pPage1 set to 0 if after
49701    ** reading page 1 it discovers that the page-size of the database
49702    ** file is not pBt->pageSize. In this case lockBtree() will update
49703    ** pBt->pageSize to the page-size of the file on disk.
49704    */
49705    while( pBt->pPage1==0 && SQLITE_OK==(rc = lockBtree(pBt)) );
49706
49707    if( rc==SQLITE_OK && wrflag ){
49708      if( pBt->readOnly ){
49709        rc = SQLITE_READONLY;
49710      }else{
49711        rc = sqlite3PagerBegin(pBt->pPager,wrflag>1,sqlite3TempInMemory(p->db));
49712        if( rc==SQLITE_OK ){
49713          rc = newDatabase(pBt);
49714        }
49715      }
49716    }
49717
49718    if( rc!=SQLITE_OK ){
49719      unlockBtreeIfUnused(pBt);
49720    }
49721  }while( (rc&0xFF)==SQLITE_BUSY && pBt->inTransaction==TRANS_NONE &&
49722          btreeInvokeBusyHandler(pBt) );
49723
49724  if( rc==SQLITE_OK ){
49725    if( p->inTrans==TRANS_NONE ){
49726      pBt->nTransaction++;
49727#ifndef SQLITE_OMIT_SHARED_CACHE
49728      if( p->sharable ){
49729	assert( p->lock.pBtree==p && p->lock.iTable==1 );
49730        p->lock.eLock = READ_LOCK;
49731        p->lock.pNext = pBt->pLock;
49732        pBt->pLock = &p->lock;
49733      }
49734#endif
49735    }
49736    p->inTrans = (wrflag?TRANS_WRITE:TRANS_READ);
49737    if( p->inTrans>pBt->inTransaction ){
49738      pBt->inTransaction = p->inTrans;
49739    }
49740    if( wrflag ){
49741      MemPage *pPage1 = pBt->pPage1;
49742#ifndef SQLITE_OMIT_SHARED_CACHE
49743      assert( !pBt->pWriter );
49744      pBt->pWriter = p;
49745      pBt->isExclusive = (u8)(wrflag>1);
49746#endif
49747
49748      /* If the db-size header field is incorrect (as it may be if an old
49749      ** client has been writing the database file), update it now. Doing
49750      ** this sooner rather than later means the database size can safely
49751      ** re-read the database size from page 1 if a savepoint or transaction
49752      ** rollback occurs within the transaction.
49753      */
49754      if( pBt->nPage!=get4byte(&pPage1->aData[28]) ){
49755        rc = sqlite3PagerWrite(pPage1->pDbPage);
49756        if( rc==SQLITE_OK ){
49757          put4byte(&pPage1->aData[28], pBt->nPage);
49758        }
49759      }
49760    }
49761  }
49762
49763
49764trans_begun:
49765  if( rc==SQLITE_OK && wrflag ){
49766    /* This call makes sure that the pager has the correct number of
49767    ** open savepoints. If the second parameter is greater than 0 and
49768    ** the sub-journal is not already open, then it will be opened here.
49769    */
49770    rc = sqlite3PagerOpenSavepoint(pBt->pPager, p->db->nSavepoint);
49771  }
49772
49773  btreeIntegrity(p);
49774  sqlite3BtreeLeave(p);
49775  return rc;
49776}
49777
49778#ifndef SQLITE_OMIT_AUTOVACUUM
49779
49780/*
49781** Set the pointer-map entries for all children of page pPage. Also, if
49782** pPage contains cells that point to overflow pages, set the pointer
49783** map entries for the overflow pages as well.
49784*/
49785static int setChildPtrmaps(MemPage *pPage){
49786  int i;                             /* Counter variable */
49787  int nCell;                         /* Number of cells in page pPage */
49788  int rc;                            /* Return code */
49789  BtShared *pBt = pPage->pBt;
49790  u8 isInitOrig = pPage->isInit;
49791  Pgno pgno = pPage->pgno;
49792
49793  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
49794  rc = btreeInitPage(pPage);
49795  if( rc!=SQLITE_OK ){
49796    goto set_child_ptrmaps_out;
49797  }
49798  nCell = pPage->nCell;
49799
49800  for(i=0; i<nCell; i++){
49801    u8 *pCell = findCell(pPage, i);
49802
49803    ptrmapPutOvflPtr(pPage, pCell, &rc);
49804
49805    if( !pPage->leaf ){
49806      Pgno childPgno = get4byte(pCell);
49807      ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
49808    }
49809  }
49810
49811  if( !pPage->leaf ){
49812    Pgno childPgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
49813    ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
49814  }
49815
49816set_child_ptrmaps_out:
49817  pPage->isInit = isInitOrig;
49818  return rc;
49819}
49820
49821/*
49822** Somewhere on pPage is a pointer to page iFrom.  Modify this pointer so
49823** that it points to iTo. Parameter eType describes the type of pointer to
49824** be modified, as  follows:
49825**
49826** PTRMAP_BTREE:     pPage is a btree-page. The pointer points at a child
49827**                   page of pPage.
49828**
49829** PTRMAP_OVERFLOW1: pPage is a btree-page. The pointer points at an overflow
49830**                   page pointed to by one of the cells on pPage.
49831**
49832** PTRMAP_OVERFLOW2: pPage is an overflow-page. The pointer points at the next
49833**                   overflow page in the list.
49834*/
49835static int modifyPagePointer(MemPage *pPage, Pgno iFrom, Pgno iTo, u8 eType){
49836  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
49837  assert( sqlite3PagerIswriteable(pPage->pDbPage) );
49838  if( eType==PTRMAP_OVERFLOW2 ){
49839    /* The pointer is always the first 4 bytes of the page in this case.  */
49840    if( get4byte(pPage->aData)!=iFrom ){
49841      return SQLITE_CORRUPT_BKPT;
49842    }
49843    put4byte(pPage->aData, iTo);
49844  }else{
49845    u8 isInitOrig = pPage->isInit;
49846    int i;
49847    int nCell;
49848
49849    btreeInitPage(pPage);
49850    nCell = pPage->nCell;
49851
49852    for(i=0; i<nCell; i++){
49853      u8 *pCell = findCell(pPage, i);
49854      if( eType==PTRMAP_OVERFLOW1 ){
49855        CellInfo info;
49856        btreeParseCellPtr(pPage, pCell, &info);
49857        if( info.iOverflow ){
49858          if( iFrom==get4byte(&pCell[info.iOverflow]) ){
49859            put4byte(&pCell[info.iOverflow], iTo);
49860            break;
49861          }
49862        }
49863      }else{
49864        if( get4byte(pCell)==iFrom ){
49865          put4byte(pCell, iTo);
49866          break;
49867        }
49868      }
49869    }
49870
49871    if( i==nCell ){
49872      if( eType!=PTRMAP_BTREE ||
49873          get4byte(&pPage->aData[pPage->hdrOffset+8])!=iFrom ){
49874        return SQLITE_CORRUPT_BKPT;
49875      }
49876      put4byte(&pPage->aData[pPage->hdrOffset+8], iTo);
49877    }
49878
49879    pPage->isInit = isInitOrig;
49880  }
49881  return SQLITE_OK;
49882}
49883
49884
49885/*
49886** Move the open database page pDbPage to location iFreePage in the
49887** database. The pDbPage reference remains valid.
49888**
49889** The isCommit flag indicates that there is no need to remember that
49890** the journal needs to be sync()ed before database page pDbPage->pgno
49891** can be written to. The caller has already promised not to write to that
49892** page.
49893*/
49894static int relocatePage(
49895  BtShared *pBt,           /* Btree */
49896  MemPage *pDbPage,        /* Open page to move */
49897  u8 eType,                /* Pointer map 'type' entry for pDbPage */
49898  Pgno iPtrPage,           /* Pointer map 'page-no' entry for pDbPage */
49899  Pgno iFreePage,          /* The location to move pDbPage to */
49900  int isCommit             /* isCommit flag passed to sqlite3PagerMovepage */
49901){
49902  MemPage *pPtrPage;   /* The page that contains a pointer to pDbPage */
49903  Pgno iDbPage = pDbPage->pgno;
49904  Pager *pPager = pBt->pPager;
49905  int rc;
49906
49907  assert( eType==PTRMAP_OVERFLOW2 || eType==PTRMAP_OVERFLOW1 ||
49908      eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE );
49909  assert( sqlite3_mutex_held(pBt->mutex) );
49910  assert( pDbPage->pBt==pBt );
49911
49912  /* Move page iDbPage from its current location to page number iFreePage */
49913  TRACE(("AUTOVACUUM: Moving %d to free page %d (ptr page %d type %d)\n",
49914      iDbPage, iFreePage, iPtrPage, eType));
49915  rc = sqlite3PagerMovepage(pPager, pDbPage->pDbPage, iFreePage, isCommit);
49916  if( rc!=SQLITE_OK ){
49917    return rc;
49918  }
49919  pDbPage->pgno = iFreePage;
49920
49921  /* If pDbPage was a btree-page, then it may have child pages and/or cells
49922  ** that point to overflow pages. The pointer map entries for all these
49923  ** pages need to be changed.
49924  **
49925  ** If pDbPage is an overflow page, then the first 4 bytes may store a
49926  ** pointer to a subsequent overflow page. If this is the case, then
49927  ** the pointer map needs to be updated for the subsequent overflow page.
49928  */
49929  if( eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE ){
49930    rc = setChildPtrmaps(pDbPage);
49931    if( rc!=SQLITE_OK ){
49932      return rc;
49933    }
49934  }else{
49935    Pgno nextOvfl = get4byte(pDbPage->aData);
49936    if( nextOvfl!=0 ){
49937      ptrmapPut(pBt, nextOvfl, PTRMAP_OVERFLOW2, iFreePage, &rc);
49938      if( rc!=SQLITE_OK ){
49939        return rc;
49940      }
49941    }
49942  }
49943
49944  /* Fix the database pointer on page iPtrPage that pointed at iDbPage so
49945  ** that it points at iFreePage. Also fix the pointer map entry for
49946  ** iPtrPage.
49947  */
49948  if( eType!=PTRMAP_ROOTPAGE ){
49949    rc = btreeGetPage(pBt, iPtrPage, &pPtrPage, 0);
49950    if( rc!=SQLITE_OK ){
49951      return rc;
49952    }
49953    rc = sqlite3PagerWrite(pPtrPage->pDbPage);
49954    if( rc!=SQLITE_OK ){
49955      releasePage(pPtrPage);
49956      return rc;
49957    }
49958    rc = modifyPagePointer(pPtrPage, iDbPage, iFreePage, eType);
49959    releasePage(pPtrPage);
49960    if( rc==SQLITE_OK ){
49961      ptrmapPut(pBt, iFreePage, eType, iPtrPage, &rc);
49962    }
49963  }
49964  return rc;
49965}
49966
49967/* Forward declaration required by incrVacuumStep(). */
49968static int allocateBtreePage(BtShared *, MemPage **, Pgno *, Pgno, u8);
49969
49970/*
49971** Perform a single step of an incremental-vacuum. If successful,
49972** return SQLITE_OK. If there is no work to do (and therefore no
49973** point in calling this function again), return SQLITE_DONE.
49974**
49975** More specificly, this function attempts to re-organize the
49976** database so that the last page of the file currently in use
49977** is no longer in use.
49978**
49979** If the nFin parameter is non-zero, this function assumes
49980** that the caller will keep calling incrVacuumStep() until
49981** it returns SQLITE_DONE or an error, and that nFin is the
49982** number of pages the database file will contain after this
49983** process is complete.  If nFin is zero, it is assumed that
49984** incrVacuumStep() will be called a finite amount of times
49985** which may or may not empty the freelist.  A full autovacuum
49986** has nFin>0.  A "PRAGMA incremental_vacuum" has nFin==0.
49987*/
49988static int incrVacuumStep(BtShared *pBt, Pgno nFin, Pgno iLastPg){
49989  Pgno nFreeList;           /* Number of pages still on the free-list */
49990  int rc;
49991
49992  assert( sqlite3_mutex_held(pBt->mutex) );
49993  assert( iLastPg>nFin );
49994
49995  if( !PTRMAP_ISPAGE(pBt, iLastPg) && iLastPg!=PENDING_BYTE_PAGE(pBt) ){
49996    u8 eType;
49997    Pgno iPtrPage;
49998
49999    nFreeList = get4byte(&pBt->pPage1->aData[36]);
50000    if( nFreeList==0 ){
50001      return SQLITE_DONE;
50002    }
50003
50004    rc = ptrmapGet(pBt, iLastPg, &eType, &iPtrPage);
50005    if( rc!=SQLITE_OK ){
50006      return rc;
50007    }
50008    if( eType==PTRMAP_ROOTPAGE ){
50009      return SQLITE_CORRUPT_BKPT;
50010    }
50011
50012    if( eType==PTRMAP_FREEPAGE ){
50013      if( nFin==0 ){
50014        /* Remove the page from the files free-list. This is not required
50015        ** if nFin is non-zero. In that case, the free-list will be
50016        ** truncated to zero after this function returns, so it doesn't
50017        ** matter if it still contains some garbage entries.
50018        */
50019        Pgno iFreePg;
50020        MemPage *pFreePg;
50021        rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iLastPg, 1);
50022        if( rc!=SQLITE_OK ){
50023          return rc;
50024        }
50025        assert( iFreePg==iLastPg );
50026        releasePage(pFreePg);
50027      }
50028    } else {
50029      Pgno iFreePg;             /* Index of free page to move pLastPg to */
50030      MemPage *pLastPg;
50031
50032      rc = btreeGetPage(pBt, iLastPg, &pLastPg, 0);
50033      if( rc!=SQLITE_OK ){
50034        return rc;
50035      }
50036
50037      /* If nFin is zero, this loop runs exactly once and page pLastPg
50038      ** is swapped with the first free page pulled off the free list.
50039      **
50040      ** On the other hand, if nFin is greater than zero, then keep
50041      ** looping until a free-page located within the first nFin pages
50042      ** of the file is found.
50043      */
50044      do {
50045        MemPage *pFreePg;
50046        rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, 0, 0);
50047        if( rc!=SQLITE_OK ){
50048          releasePage(pLastPg);
50049          return rc;
50050        }
50051        releasePage(pFreePg);
50052      }while( nFin!=0 && iFreePg>nFin );
50053      assert( iFreePg<iLastPg );
50054
50055      rc = sqlite3PagerWrite(pLastPg->pDbPage);
50056      if( rc==SQLITE_OK ){
50057        rc = relocatePage(pBt, pLastPg, eType, iPtrPage, iFreePg, nFin!=0);
50058      }
50059      releasePage(pLastPg);
50060      if( rc!=SQLITE_OK ){
50061        return rc;
50062      }
50063    }
50064  }
50065
50066  if( nFin==0 ){
50067    iLastPg--;
50068    while( iLastPg==PENDING_BYTE_PAGE(pBt)||PTRMAP_ISPAGE(pBt, iLastPg) ){
50069      if( PTRMAP_ISPAGE(pBt, iLastPg) ){
50070        MemPage *pPg;
50071        rc = btreeGetPage(pBt, iLastPg, &pPg, 0);
50072        if( rc!=SQLITE_OK ){
50073          return rc;
50074        }
50075        rc = sqlite3PagerWrite(pPg->pDbPage);
50076        releasePage(pPg);
50077        if( rc!=SQLITE_OK ){
50078          return rc;
50079        }
50080      }
50081      iLastPg--;
50082    }
50083    sqlite3PagerTruncateImage(pBt->pPager, iLastPg);
50084    pBt->nPage = iLastPg;
50085  }
50086  return SQLITE_OK;
50087}
50088
50089/*
50090** A write-transaction must be opened before calling this function.
50091** It performs a single unit of work towards an incremental vacuum.
50092**
50093** If the incremental vacuum is finished after this function has run,
50094** SQLITE_DONE is returned. If it is not finished, but no error occurred,
50095** SQLITE_OK is returned. Otherwise an SQLite error code.
50096*/
50097SQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *p){
50098  int rc;
50099  BtShared *pBt = p->pBt;
50100
50101  sqlite3BtreeEnter(p);
50102  assert( pBt->inTransaction==TRANS_WRITE && p->inTrans==TRANS_WRITE );
50103  if( !pBt->autoVacuum ){
50104    rc = SQLITE_DONE;
50105  }else{
50106    invalidateAllOverflowCache(pBt);
50107    rc = incrVacuumStep(pBt, 0, btreePagecount(pBt));
50108    if( rc==SQLITE_OK ){
50109      rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
50110      put4byte(&pBt->pPage1->aData[28], pBt->nPage);
50111    }
50112  }
50113  sqlite3BtreeLeave(p);
50114  return rc;
50115}
50116
50117/*
50118** This routine is called prior to sqlite3PagerCommit when a transaction
50119** is commited for an auto-vacuum database.
50120**
50121** If SQLITE_OK is returned, then *pnTrunc is set to the number of pages
50122** the database file should be truncated to during the commit process.
50123** i.e. the database has been reorganized so that only the first *pnTrunc
50124** pages are in use.
50125*/
50126static int autoVacuumCommit(BtShared *pBt){
50127  int rc = SQLITE_OK;
50128  Pager *pPager = pBt->pPager;
50129  VVA_ONLY( int nRef = sqlite3PagerRefcount(pPager) );
50130
50131  assert( sqlite3_mutex_held(pBt->mutex) );
50132  invalidateAllOverflowCache(pBt);
50133  assert(pBt->autoVacuum);
50134  if( !pBt->incrVacuum ){
50135    Pgno nFin;         /* Number of pages in database after autovacuuming */
50136    Pgno nFree;        /* Number of pages on the freelist initially */
50137    Pgno nPtrmap;      /* Number of PtrMap pages to be freed */
50138    Pgno iFree;        /* The next page to be freed */
50139    int nEntry;        /* Number of entries on one ptrmap page */
50140    Pgno nOrig;        /* Database size before freeing */
50141
50142    nOrig = btreePagecount(pBt);
50143    if( PTRMAP_ISPAGE(pBt, nOrig) || nOrig==PENDING_BYTE_PAGE(pBt) ){
50144      /* It is not possible to create a database for which the final page
50145      ** is either a pointer-map page or the pending-byte page. If one
50146      ** is encountered, this indicates corruption.
50147      */
50148      return SQLITE_CORRUPT_BKPT;
50149    }
50150
50151    nFree = get4byte(&pBt->pPage1->aData[36]);
50152    nEntry = pBt->usableSize/5;
50153    nPtrmap = (nFree-nOrig+PTRMAP_PAGENO(pBt, nOrig)+nEntry)/nEntry;
50154    nFin = nOrig - nFree - nPtrmap;
50155    if( nOrig>PENDING_BYTE_PAGE(pBt) && nFin<PENDING_BYTE_PAGE(pBt) ){
50156      nFin--;
50157    }
50158    while( PTRMAP_ISPAGE(pBt, nFin) || nFin==PENDING_BYTE_PAGE(pBt) ){
50159      nFin--;
50160    }
50161    if( nFin>nOrig ) return SQLITE_CORRUPT_BKPT;
50162
50163    for(iFree=nOrig; iFree>nFin && rc==SQLITE_OK; iFree--){
50164      rc = incrVacuumStep(pBt, nFin, iFree);
50165    }
50166    if( (rc==SQLITE_DONE || rc==SQLITE_OK) && nFree>0 ){
50167      rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
50168      put4byte(&pBt->pPage1->aData[32], 0);
50169      put4byte(&pBt->pPage1->aData[36], 0);
50170      put4byte(&pBt->pPage1->aData[28], nFin);
50171      sqlite3PagerTruncateImage(pBt->pPager, nFin);
50172      pBt->nPage = nFin;
50173    }
50174    if( rc!=SQLITE_OK ){
50175      sqlite3PagerRollback(pPager);
50176    }
50177  }
50178
50179  assert( nRef==sqlite3PagerRefcount(pPager) );
50180  return rc;
50181}
50182
50183#else /* ifndef SQLITE_OMIT_AUTOVACUUM */
50184# define setChildPtrmaps(x) SQLITE_OK
50185#endif
50186
50187/*
50188** This routine does the first phase of a two-phase commit.  This routine
50189** causes a rollback journal to be created (if it does not already exist)
50190** and populated with enough information so that if a power loss occurs
50191** the database can be restored to its original state by playing back
50192** the journal.  Then the contents of the journal are flushed out to
50193** the disk.  After the journal is safely on oxide, the changes to the
50194** database are written into the database file and flushed to oxide.
50195** At the end of this call, the rollback journal still exists on the
50196** disk and we are still holding all locks, so the transaction has not
50197** committed.  See sqlite3BtreeCommitPhaseTwo() for the second phase of the
50198** commit process.
50199**
50200** This call is a no-op if no write-transaction is currently active on pBt.
50201**
50202** Otherwise, sync the database file for the btree pBt. zMaster points to
50203** the name of a master journal file that should be written into the
50204** individual journal file, or is NULL, indicating no master journal file
50205** (single database transaction).
50206**
50207** When this is called, the master journal should already have been
50208** created, populated with this journal pointer and synced to disk.
50209**
50210** Once this is routine has returned, the only thing required to commit
50211** the write-transaction for this database file is to delete the journal.
50212*/
50213SQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree *p, const char *zMaster){
50214  int rc = SQLITE_OK;
50215  if( p->inTrans==TRANS_WRITE ){
50216    BtShared *pBt = p->pBt;
50217    sqlite3BtreeEnter(p);
50218#ifndef SQLITE_OMIT_AUTOVACUUM
50219    if( pBt->autoVacuum ){
50220      rc = autoVacuumCommit(pBt);
50221      if( rc!=SQLITE_OK ){
50222        sqlite3BtreeLeave(p);
50223        return rc;
50224      }
50225    }
50226#endif
50227    rc = sqlite3PagerCommitPhaseOne(pBt->pPager, zMaster, 0);
50228    sqlite3BtreeLeave(p);
50229  }
50230  return rc;
50231}
50232
50233/*
50234** This function is called from both BtreeCommitPhaseTwo() and BtreeRollback()
50235** at the conclusion of a transaction.
50236*/
50237static void btreeEndTransaction(Btree *p){
50238  BtShared *pBt = p->pBt;
50239  assert( sqlite3BtreeHoldsMutex(p) );
50240
50241  btreeClearHasContent(pBt);
50242  if( p->inTrans>TRANS_NONE && p->db->activeVdbeCnt>1 ){
50243    /* If there are other active statements that belong to this database
50244    ** handle, downgrade to a read-only transaction. The other statements
50245    ** may still be reading from the database.  */
50246    downgradeAllSharedCacheTableLocks(p);
50247    p->inTrans = TRANS_READ;
50248  }else{
50249    /* If the handle had any kind of transaction open, decrement the
50250    ** transaction count of the shared btree. If the transaction count
50251    ** reaches 0, set the shared state to TRANS_NONE. The unlockBtreeIfUnused()
50252    ** call below will unlock the pager.  */
50253    if( p->inTrans!=TRANS_NONE ){
50254      clearAllSharedCacheTableLocks(p);
50255      pBt->nTransaction--;
50256      if( 0==pBt->nTransaction ){
50257        pBt->inTransaction = TRANS_NONE;
50258      }
50259    }
50260
50261    /* Set the current transaction state to TRANS_NONE and unlock the
50262    ** pager if this call closed the only read or write transaction.  */
50263    p->inTrans = TRANS_NONE;
50264    unlockBtreeIfUnused(pBt);
50265  }
50266
50267  btreeIntegrity(p);
50268}
50269
50270/*
50271** Commit the transaction currently in progress.
50272**
50273** This routine implements the second phase of a 2-phase commit.  The
50274** sqlite3BtreeCommitPhaseOne() routine does the first phase and should
50275** be invoked prior to calling this routine.  The sqlite3BtreeCommitPhaseOne()
50276** routine did all the work of writing information out to disk and flushing the
50277** contents so that they are written onto the disk platter.  All this
50278** routine has to do is delete or truncate or zero the header in the
50279** the rollback journal (which causes the transaction to commit) and
50280** drop locks.
50281**
50282** Normally, if an error occurs while the pager layer is attempting to
50283** finalize the underlying journal file, this function returns an error and
50284** the upper layer will attempt a rollback. However, if the second argument
50285** is non-zero then this b-tree transaction is part of a multi-file
50286** transaction. In this case, the transaction has already been committed
50287** (by deleting a master journal file) and the caller will ignore this
50288** functions return code. So, even if an error occurs in the pager layer,
50289** reset the b-tree objects internal state to indicate that the write
50290** transaction has been closed. This is quite safe, as the pager will have
50291** transitioned to the error state.
50292**
50293** This will release the write lock on the database file.  If there
50294** are no active cursors, it also releases the read lock.
50295*/
50296SQLITE_PRIVATE int sqlite3BtreeCommitPhaseTwo(Btree *p, int bCleanup){
50297
50298  if( p->inTrans==TRANS_NONE ) return SQLITE_OK;
50299  sqlite3BtreeEnter(p);
50300  btreeIntegrity(p);
50301
50302  /* If the handle has a write-transaction open, commit the shared-btrees
50303  ** transaction and set the shared state to TRANS_READ.
50304  */
50305  if( p->inTrans==TRANS_WRITE ){
50306    int rc;
50307    BtShared *pBt = p->pBt;
50308    assert( pBt->inTransaction==TRANS_WRITE );
50309    assert( pBt->nTransaction>0 );
50310    rc = sqlite3PagerCommitPhaseTwo(pBt->pPager);
50311    if( rc!=SQLITE_OK && bCleanup==0 ){
50312      sqlite3BtreeLeave(p);
50313      return rc;
50314    }
50315    pBt->inTransaction = TRANS_READ;
50316  }
50317
50318  btreeEndTransaction(p);
50319  sqlite3BtreeLeave(p);
50320  return SQLITE_OK;
50321}
50322
50323/*
50324** Do both phases of a commit.
50325*/
50326SQLITE_PRIVATE int sqlite3BtreeCommit(Btree *p){
50327  int rc;
50328  sqlite3BtreeEnter(p);
50329  rc = sqlite3BtreeCommitPhaseOne(p, 0);
50330  if( rc==SQLITE_OK ){
50331    rc = sqlite3BtreeCommitPhaseTwo(p, 0);
50332  }
50333  sqlite3BtreeLeave(p);
50334  return rc;
50335}
50336
50337#ifndef NDEBUG
50338/*
50339** Return the number of write-cursors open on this handle. This is for use
50340** in assert() expressions, so it is only compiled if NDEBUG is not
50341** defined.
50342**
50343** For the purposes of this routine, a write-cursor is any cursor that
50344** is capable of writing to the databse.  That means the cursor was
50345** originally opened for writing and the cursor has not be disabled
50346** by having its state changed to CURSOR_FAULT.
50347*/
50348static int countWriteCursors(BtShared *pBt){
50349  BtCursor *pCur;
50350  int r = 0;
50351  for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){
50352    if( pCur->wrFlag && pCur->eState!=CURSOR_FAULT ) r++;
50353  }
50354  return r;
50355}
50356#endif
50357
50358/*
50359** This routine sets the state to CURSOR_FAULT and the error
50360** code to errCode for every cursor on BtShared that pBtree
50361** references.
50362**
50363** Every cursor is tripped, including cursors that belong
50364** to other database connections that happen to be sharing
50365** the cache with pBtree.
50366**
50367** This routine gets called when a rollback occurs.
50368** All cursors using the same cache must be tripped
50369** to prevent them from trying to use the btree after
50370** the rollback.  The rollback may have deleted tables
50371** or moved root pages, so it is not sufficient to
50372** save the state of the cursor.  The cursor must be
50373** invalidated.
50374*/
50375SQLITE_PRIVATE void sqlite3BtreeTripAllCursors(Btree *pBtree, int errCode){
50376  BtCursor *p;
50377  sqlite3BtreeEnter(pBtree);
50378  for(p=pBtree->pBt->pCursor; p; p=p->pNext){
50379    int i;
50380    sqlite3BtreeClearCursor(p);
50381    p->eState = CURSOR_FAULT;
50382    p->skipNext = errCode;
50383    for(i=0; i<=p->iPage; i++){
50384      releasePage(p->apPage[i]);
50385      p->apPage[i] = 0;
50386    }
50387  }
50388  sqlite3BtreeLeave(pBtree);
50389}
50390
50391/*
50392** Rollback the transaction in progress.  All cursors will be
50393** invalided by this operation.  Any attempt to use a cursor
50394** that was open at the beginning of this operation will result
50395** in an error.
50396**
50397** This will release the write lock on the database file.  If there
50398** are no active cursors, it also releases the read lock.
50399*/
50400SQLITE_PRIVATE int sqlite3BtreeRollback(Btree *p){
50401  int rc;
50402  BtShared *pBt = p->pBt;
50403  MemPage *pPage1;
50404
50405  sqlite3BtreeEnter(p);
50406  rc = saveAllCursors(pBt, 0, 0);
50407#ifndef SQLITE_OMIT_SHARED_CACHE
50408  if( rc!=SQLITE_OK ){
50409    /* This is a horrible situation. An IO or malloc() error occurred whilst
50410    ** trying to save cursor positions. If this is an automatic rollback (as
50411    ** the result of a constraint, malloc() failure or IO error) then
50412    ** the cache may be internally inconsistent (not contain valid trees) so
50413    ** we cannot simply return the error to the caller. Instead, abort
50414    ** all queries that may be using any of the cursors that failed to save.
50415    */
50416    sqlite3BtreeTripAllCursors(p, rc);
50417  }
50418#endif
50419  btreeIntegrity(p);
50420
50421  if( p->inTrans==TRANS_WRITE ){
50422    int rc2;
50423
50424    assert( TRANS_WRITE==pBt->inTransaction );
50425    rc2 = sqlite3PagerRollback(pBt->pPager);
50426    if( rc2!=SQLITE_OK ){
50427      rc = rc2;
50428    }
50429
50430    /* The rollback may have destroyed the pPage1->aData value.  So
50431    ** call btreeGetPage() on page 1 again to make
50432    ** sure pPage1->aData is set correctly. */
50433    if( btreeGetPage(pBt, 1, &pPage1, 0)==SQLITE_OK ){
50434      int nPage = get4byte(28+(u8*)pPage1->aData);
50435      testcase( nPage==0 );
50436      if( nPage==0 ) sqlite3PagerPagecount(pBt->pPager, &nPage);
50437      testcase( pBt->nPage!=nPage );
50438      pBt->nPage = nPage;
50439      releasePage(pPage1);
50440    }
50441    assert( countWriteCursors(pBt)==0 );
50442    pBt->inTransaction = TRANS_READ;
50443  }
50444
50445  btreeEndTransaction(p);
50446  sqlite3BtreeLeave(p);
50447  return rc;
50448}
50449
50450/*
50451** Start a statement subtransaction. The subtransaction can can be rolled
50452** back independently of the main transaction. You must start a transaction
50453** before starting a subtransaction. The subtransaction is ended automatically
50454** if the main transaction commits or rolls back.
50455**
50456** Statement subtransactions are used around individual SQL statements
50457** that are contained within a BEGIN...COMMIT block.  If a constraint
50458** error occurs within the statement, the effect of that one statement
50459** can be rolled back without having to rollback the entire transaction.
50460**
50461** A statement sub-transaction is implemented as an anonymous savepoint. The
50462** value passed as the second parameter is the total number of savepoints,
50463** including the new anonymous savepoint, open on the B-Tree. i.e. if there
50464** are no active savepoints and no other statement-transactions open,
50465** iStatement is 1. This anonymous savepoint can be released or rolled back
50466** using the sqlite3BtreeSavepoint() function.
50467*/
50468SQLITE_PRIVATE int sqlite3BtreeBeginStmt(Btree *p, int iStatement){
50469  int rc;
50470  BtShared *pBt = p->pBt;
50471  sqlite3BtreeEnter(p);
50472  assert( p->inTrans==TRANS_WRITE );
50473  assert( pBt->readOnly==0 );
50474  assert( iStatement>0 );
50475  assert( iStatement>p->db->nSavepoint );
50476  assert( pBt->inTransaction==TRANS_WRITE );
50477  /* At the pager level, a statement transaction is a savepoint with
50478  ** an index greater than all savepoints created explicitly using
50479  ** SQL statements. It is illegal to open, release or rollback any
50480  ** such savepoints while the statement transaction savepoint is active.
50481  */
50482  rc = sqlite3PagerOpenSavepoint(pBt->pPager, iStatement);
50483  sqlite3BtreeLeave(p);
50484  return rc;
50485}
50486
50487/*
50488** The second argument to this function, op, is always SAVEPOINT_ROLLBACK
50489** or SAVEPOINT_RELEASE. This function either releases or rolls back the
50490** savepoint identified by parameter iSavepoint, depending on the value
50491** of op.
50492**
50493** Normally, iSavepoint is greater than or equal to zero. However, if op is
50494** SAVEPOINT_ROLLBACK, then iSavepoint may also be -1. In this case the
50495** contents of the entire transaction are rolled back. This is different
50496** from a normal transaction rollback, as no locks are released and the
50497** transaction remains open.
50498*/
50499SQLITE_PRIVATE int sqlite3BtreeSavepoint(Btree *p, int op, int iSavepoint){
50500  int rc = SQLITE_OK;
50501  if( p && p->inTrans==TRANS_WRITE ){
50502    BtShared *pBt = p->pBt;
50503    assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );
50504    assert( iSavepoint>=0 || (iSavepoint==-1 && op==SAVEPOINT_ROLLBACK) );
50505    sqlite3BtreeEnter(p);
50506    rc = sqlite3PagerSavepoint(pBt->pPager, op, iSavepoint);
50507    if( rc==SQLITE_OK ){
50508      if( iSavepoint<0 && pBt->initiallyEmpty ) pBt->nPage = 0;
50509      rc = newDatabase(pBt);
50510      pBt->nPage = get4byte(28 + pBt->pPage1->aData);
50511
50512      /* The database size was written into the offset 28 of the header
50513      ** when the transaction started, so we know that the value at offset
50514      ** 28 is nonzero. */
50515      assert( pBt->nPage>0 );
50516    }
50517    sqlite3BtreeLeave(p);
50518  }
50519  return rc;
50520}
50521
50522/*
50523** Create a new cursor for the BTree whose root is on the page
50524** iTable. If a read-only cursor is requested, it is assumed that
50525** the caller already has at least a read-only transaction open
50526** on the database already. If a write-cursor is requested, then
50527** the caller is assumed to have an open write transaction.
50528**
50529** If wrFlag==0, then the cursor can only be used for reading.
50530** If wrFlag==1, then the cursor can be used for reading or for
50531** writing if other conditions for writing are also met.  These
50532** are the conditions that must be met in order for writing to
50533** be allowed:
50534**
50535** 1:  The cursor must have been opened with wrFlag==1
50536**
50537** 2:  Other database connections that share the same pager cache
50538**     but which are not in the READ_UNCOMMITTED state may not have
50539**     cursors open with wrFlag==0 on the same table.  Otherwise
50540**     the changes made by this write cursor would be visible to
50541**     the read cursors in the other database connection.
50542**
50543** 3:  The database must be writable (not on read-only media)
50544**
50545** 4:  There must be an active transaction.
50546**
50547** No checking is done to make sure that page iTable really is the
50548** root page of a b-tree.  If it is not, then the cursor acquired
50549** will not work correctly.
50550**
50551** It is assumed that the sqlite3BtreeCursorZero() has been called
50552** on pCur to initialize the memory space prior to invoking this routine.
50553*/
50554static int btreeCursor(
50555  Btree *p,                              /* The btree */
50556  int iTable,                            /* Root page of table to open */
50557  int wrFlag,                            /* 1 to write. 0 read-only */
50558  struct KeyInfo *pKeyInfo,              /* First arg to comparison function */
50559  BtCursor *pCur                         /* Space for new cursor */
50560){
50561  BtShared *pBt = p->pBt;                /* Shared b-tree handle */
50562
50563  assert( sqlite3BtreeHoldsMutex(p) );
50564  assert( wrFlag==0 || wrFlag==1 );
50565
50566  /* The following assert statements verify that if this is a sharable
50567  ** b-tree database, the connection is holding the required table locks,
50568  ** and that no other connection has any open cursor that conflicts with
50569  ** this lock.  */
50570  assert( hasSharedCacheTableLock(p, iTable, pKeyInfo!=0, wrFlag+1) );
50571  assert( wrFlag==0 || !hasReadConflicts(p, iTable) );
50572
50573  /* Assert that the caller has opened the required transaction. */
50574  assert( p->inTrans>TRANS_NONE );
50575  assert( wrFlag==0 || p->inTrans==TRANS_WRITE );
50576  assert( pBt->pPage1 && pBt->pPage1->aData );
50577
50578  if( NEVER(wrFlag && pBt->readOnly) ){
50579    return SQLITE_READONLY;
50580  }
50581  if( iTable==1 && btreePagecount(pBt)==0 ){
50582    return SQLITE_EMPTY;
50583  }
50584
50585  /* Now that no other errors can occur, finish filling in the BtCursor
50586  ** variables and link the cursor into the BtShared list.  */
50587  pCur->pgnoRoot = (Pgno)iTable;
50588  pCur->iPage = -1;
50589  pCur->pKeyInfo = pKeyInfo;
50590  pCur->pBtree = p;
50591  pCur->pBt = pBt;
50592  pCur->wrFlag = (u8)wrFlag;
50593  pCur->pNext = pBt->pCursor;
50594  if( pCur->pNext ){
50595    pCur->pNext->pPrev = pCur;
50596  }
50597  pBt->pCursor = pCur;
50598  pCur->eState = CURSOR_INVALID;
50599  pCur->cachedRowid = 0;
50600  return SQLITE_OK;
50601}
50602SQLITE_PRIVATE int sqlite3BtreeCursor(
50603  Btree *p,                                   /* The btree */
50604  int iTable,                                 /* Root page of table to open */
50605  int wrFlag,                                 /* 1 to write. 0 read-only */
50606  struct KeyInfo *pKeyInfo,                   /* First arg to xCompare() */
50607  BtCursor *pCur                              /* Write new cursor here */
50608){
50609  int rc;
50610  sqlite3BtreeEnter(p);
50611  rc = btreeCursor(p, iTable, wrFlag, pKeyInfo, pCur);
50612  sqlite3BtreeLeave(p);
50613  return rc;
50614}
50615
50616/*
50617** Return the size of a BtCursor object in bytes.
50618**
50619** This interfaces is needed so that users of cursors can preallocate
50620** sufficient storage to hold a cursor.  The BtCursor object is opaque
50621** to users so they cannot do the sizeof() themselves - they must call
50622** this routine.
50623*/
50624SQLITE_PRIVATE int sqlite3BtreeCursorSize(void){
50625  return ROUND8(sizeof(BtCursor));
50626}
50627
50628/*
50629** Initialize memory that will be converted into a BtCursor object.
50630**
50631** The simple approach here would be to memset() the entire object
50632** to zero.  But it turns out that the apPage[] and aiIdx[] arrays
50633** do not need to be zeroed and they are large, so we can save a lot
50634** of run-time by skipping the initialization of those elements.
50635*/
50636SQLITE_PRIVATE void sqlite3BtreeCursorZero(BtCursor *p){
50637  memset(p, 0, offsetof(BtCursor, iPage));
50638}
50639
50640/*
50641** Set the cached rowid value of every cursor in the same database file
50642** as pCur and having the same root page number as pCur.  The value is
50643** set to iRowid.
50644**
50645** Only positive rowid values are considered valid for this cache.
50646** The cache is initialized to zero, indicating an invalid cache.
50647** A btree will work fine with zero or negative rowids.  We just cannot
50648** cache zero or negative rowids, which means tables that use zero or
50649** negative rowids might run a little slower.  But in practice, zero
50650** or negative rowids are very uncommon so this should not be a problem.
50651*/
50652SQLITE_PRIVATE void sqlite3BtreeSetCachedRowid(BtCursor *pCur, sqlite3_int64 iRowid){
50653  BtCursor *p;
50654  for(p=pCur->pBt->pCursor; p; p=p->pNext){
50655    if( p->pgnoRoot==pCur->pgnoRoot ) p->cachedRowid = iRowid;
50656  }
50657  assert( pCur->cachedRowid==iRowid );
50658}
50659
50660/*
50661** Return the cached rowid for the given cursor.  A negative or zero
50662** return value indicates that the rowid cache is invalid and should be
50663** ignored.  If the rowid cache has never before been set, then a
50664** zero is returned.
50665*/
50666SQLITE_PRIVATE sqlite3_int64 sqlite3BtreeGetCachedRowid(BtCursor *pCur){
50667  return pCur->cachedRowid;
50668}
50669
50670/*
50671** Close a cursor.  The read lock on the database file is released
50672** when the last cursor is closed.
50673*/
50674SQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor *pCur){
50675  Btree *pBtree = pCur->pBtree;
50676  if( pBtree ){
50677    int i;
50678    BtShared *pBt = pCur->pBt;
50679    sqlite3BtreeEnter(pBtree);
50680    sqlite3BtreeClearCursor(pCur);
50681    if( pCur->pPrev ){
50682      pCur->pPrev->pNext = pCur->pNext;
50683    }else{
50684      pBt->pCursor = pCur->pNext;
50685    }
50686    if( pCur->pNext ){
50687      pCur->pNext->pPrev = pCur->pPrev;
50688    }
50689    for(i=0; i<=pCur->iPage; i++){
50690      releasePage(pCur->apPage[i]);
50691    }
50692    unlockBtreeIfUnused(pBt);
50693    invalidateOverflowCache(pCur);
50694    /* sqlite3_free(pCur); */
50695    sqlite3BtreeLeave(pBtree);
50696  }
50697  return SQLITE_OK;
50698}
50699
50700/*
50701** Make sure the BtCursor* given in the argument has a valid
50702** BtCursor.info structure.  If it is not already valid, call
50703** btreeParseCell() to fill it in.
50704**
50705** BtCursor.info is a cache of the information in the current cell.
50706** Using this cache reduces the number of calls to btreeParseCell().
50707**
50708** 2007-06-25:  There is a bug in some versions of MSVC that cause the
50709** compiler to crash when getCellInfo() is implemented as a macro.
50710** But there is a measureable speed advantage to using the macro on gcc
50711** (when less compiler optimizations like -Os or -O0 are used and the
50712** compiler is not doing agressive inlining.)  So we use a real function
50713** for MSVC and a macro for everything else.  Ticket #2457.
50714*/
50715#ifndef NDEBUG
50716  static void assertCellInfo(BtCursor *pCur){
50717    CellInfo info;
50718    int iPage = pCur->iPage;
50719    memset(&info, 0, sizeof(info));
50720    btreeParseCell(pCur->apPage[iPage], pCur->aiIdx[iPage], &info);
50721    assert( memcmp(&info, &pCur->info, sizeof(info))==0 );
50722  }
50723#else
50724  #define assertCellInfo(x)
50725#endif
50726#ifdef _MSC_VER
50727  /* Use a real function in MSVC to work around bugs in that compiler. */
50728  static void getCellInfo(BtCursor *pCur){
50729    if( pCur->info.nSize==0 ){
50730      int iPage = pCur->iPage;
50731      btreeParseCell(pCur->apPage[iPage],pCur->aiIdx[iPage],&pCur->info);
50732      pCur->validNKey = 1;
50733    }else{
50734      assertCellInfo(pCur);
50735    }
50736  }
50737#else /* if not _MSC_VER */
50738  /* Use a macro in all other compilers so that the function is inlined */
50739#define getCellInfo(pCur)                                                      \
50740  if( pCur->info.nSize==0 ){                                                   \
50741    int iPage = pCur->iPage;                                                   \
50742    btreeParseCell(pCur->apPage[iPage],pCur->aiIdx[iPage],&pCur->info); \
50743    pCur->validNKey = 1;                                                       \
50744  }else{                                                                       \
50745    assertCellInfo(pCur);                                                      \
50746  }
50747#endif /* _MSC_VER */
50748
50749#ifndef NDEBUG  /* The next routine used only within assert() statements */
50750/*
50751** Return true if the given BtCursor is valid.  A valid cursor is one
50752** that is currently pointing to a row in a (non-empty) table.
50753** This is a verification routine is used only within assert() statements.
50754*/
50755SQLITE_PRIVATE int sqlite3BtreeCursorIsValid(BtCursor *pCur){
50756  return pCur && pCur->eState==CURSOR_VALID;
50757}
50758#endif /* NDEBUG */
50759
50760/*
50761** Set *pSize to the size of the buffer needed to hold the value of
50762** the key for the current entry.  If the cursor is not pointing
50763** to a valid entry, *pSize is set to 0.
50764**
50765** For a table with the INTKEY flag set, this routine returns the key
50766** itself, not the number of bytes in the key.
50767**
50768** The caller must position the cursor prior to invoking this routine.
50769**
50770** This routine cannot fail.  It always returns SQLITE_OK.
50771*/
50772SQLITE_PRIVATE int sqlite3BtreeKeySize(BtCursor *pCur, i64 *pSize){
50773  assert( cursorHoldsMutex(pCur) );
50774  assert( pCur->eState==CURSOR_INVALID || pCur->eState==CURSOR_VALID );
50775  if( pCur->eState!=CURSOR_VALID ){
50776    *pSize = 0;
50777  }else{
50778    getCellInfo(pCur);
50779    *pSize = pCur->info.nKey;
50780  }
50781  return SQLITE_OK;
50782}
50783
50784/*
50785** Set *pSize to the number of bytes of data in the entry the
50786** cursor currently points to.
50787**
50788** The caller must guarantee that the cursor is pointing to a non-NULL
50789** valid entry.  In other words, the calling procedure must guarantee
50790** that the cursor has Cursor.eState==CURSOR_VALID.
50791**
50792** Failure is not possible.  This function always returns SQLITE_OK.
50793** It might just as well be a procedure (returning void) but we continue
50794** to return an integer result code for historical reasons.
50795*/
50796SQLITE_PRIVATE int sqlite3BtreeDataSize(BtCursor *pCur, u32 *pSize){
50797  assert( cursorHoldsMutex(pCur) );
50798  assert( pCur->eState==CURSOR_VALID );
50799  getCellInfo(pCur);
50800  *pSize = pCur->info.nData;
50801  return SQLITE_OK;
50802}
50803
50804/*
50805** Given the page number of an overflow page in the database (parameter
50806** ovfl), this function finds the page number of the next page in the
50807** linked list of overflow pages. If possible, it uses the auto-vacuum
50808** pointer-map data instead of reading the content of page ovfl to do so.
50809**
50810** If an error occurs an SQLite error code is returned. Otherwise:
50811**
50812** The page number of the next overflow page in the linked list is
50813** written to *pPgnoNext. If page ovfl is the last page in its linked
50814** list, *pPgnoNext is set to zero.
50815**
50816** If ppPage is not NULL, and a reference to the MemPage object corresponding
50817** to page number pOvfl was obtained, then *ppPage is set to point to that
50818** reference. It is the responsibility of the caller to call releasePage()
50819** on *ppPage to free the reference. In no reference was obtained (because
50820** the pointer-map was used to obtain the value for *pPgnoNext), then
50821** *ppPage is set to zero.
50822*/
50823static int getOverflowPage(
50824  BtShared *pBt,               /* The database file */
50825  Pgno ovfl,                   /* Current overflow page number */
50826  MemPage **ppPage,            /* OUT: MemPage handle (may be NULL) */
50827  Pgno *pPgnoNext              /* OUT: Next overflow page number */
50828){
50829  Pgno next = 0;
50830  MemPage *pPage = 0;
50831  int rc = SQLITE_OK;
50832
50833  assert( sqlite3_mutex_held(pBt->mutex) );
50834  assert(pPgnoNext);
50835
50836#ifndef SQLITE_OMIT_AUTOVACUUM
50837  /* Try to find the next page in the overflow list using the
50838  ** autovacuum pointer-map pages. Guess that the next page in
50839  ** the overflow list is page number (ovfl+1). If that guess turns
50840  ** out to be wrong, fall back to loading the data of page
50841  ** number ovfl to determine the next page number.
50842  */
50843  if( pBt->autoVacuum ){
50844    Pgno pgno;
50845    Pgno iGuess = ovfl+1;
50846    u8 eType;
50847
50848    while( PTRMAP_ISPAGE(pBt, iGuess) || iGuess==PENDING_BYTE_PAGE(pBt) ){
50849      iGuess++;
50850    }
50851
50852    if( iGuess<=btreePagecount(pBt) ){
50853      rc = ptrmapGet(pBt, iGuess, &eType, &pgno);
50854      if( rc==SQLITE_OK && eType==PTRMAP_OVERFLOW2 && pgno==ovfl ){
50855        next = iGuess;
50856        rc = SQLITE_DONE;
50857      }
50858    }
50859  }
50860#endif
50861
50862  assert( next==0 || rc==SQLITE_DONE );
50863  if( rc==SQLITE_OK ){
50864    rc = btreeGetPage(pBt, ovfl, &pPage, 0);
50865    assert( rc==SQLITE_OK || pPage==0 );
50866    if( rc==SQLITE_OK ){
50867      next = get4byte(pPage->aData);
50868    }
50869  }
50870
50871  *pPgnoNext = next;
50872  if( ppPage ){
50873    *ppPage = pPage;
50874  }else{
50875    releasePage(pPage);
50876  }
50877  return (rc==SQLITE_DONE ? SQLITE_OK : rc);
50878}
50879
50880/*
50881** Copy data from a buffer to a page, or from a page to a buffer.
50882**
50883** pPayload is a pointer to data stored on database page pDbPage.
50884** If argument eOp is false, then nByte bytes of data are copied
50885** from pPayload to the buffer pointed at by pBuf. If eOp is true,
50886** then sqlite3PagerWrite() is called on pDbPage and nByte bytes
50887** of data are copied from the buffer pBuf to pPayload.
50888**
50889** SQLITE_OK is returned on success, otherwise an error code.
50890*/
50891static int copyPayload(
50892  void *pPayload,           /* Pointer to page data */
50893  void *pBuf,               /* Pointer to buffer */
50894  int nByte,                /* Number of bytes to copy */
50895  int eOp,                  /* 0 -> copy from page, 1 -> copy to page */
50896  DbPage *pDbPage           /* Page containing pPayload */
50897){
50898  if( eOp ){
50899    /* Copy data from buffer to page (a write operation) */
50900    int rc = sqlite3PagerWrite(pDbPage);
50901    if( rc!=SQLITE_OK ){
50902      return rc;
50903    }
50904    memcpy(pPayload, pBuf, nByte);
50905  }else{
50906    /* Copy data from page to buffer (a read operation) */
50907    memcpy(pBuf, pPayload, nByte);
50908  }
50909  return SQLITE_OK;
50910}
50911
50912/*
50913** This function is used to read or overwrite payload information
50914** for the entry that the pCur cursor is pointing to. If the eOp
50915** parameter is 0, this is a read operation (data copied into
50916** buffer pBuf). If it is non-zero, a write (data copied from
50917** buffer pBuf).
50918**
50919** A total of "amt" bytes are read or written beginning at "offset".
50920** Data is read to or from the buffer pBuf.
50921**
50922** The content being read or written might appear on the main page
50923** or be scattered out on multiple overflow pages.
50924**
50925** If the BtCursor.isIncrblobHandle flag is set, and the current
50926** cursor entry uses one or more overflow pages, this function
50927** allocates space for and lazily popluates the overflow page-list
50928** cache array (BtCursor.aOverflow). Subsequent calls use this
50929** cache to make seeking to the supplied offset more efficient.
50930**
50931** Once an overflow page-list cache has been allocated, it may be
50932** invalidated if some other cursor writes to the same table, or if
50933** the cursor is moved to a different row. Additionally, in auto-vacuum
50934** mode, the following events may invalidate an overflow page-list cache.
50935**
50936**   * An incremental vacuum,
50937**   * A commit in auto_vacuum="full" mode,
50938**   * Creating a table (may require moving an overflow page).
50939*/
50940static int accessPayload(
50941  BtCursor *pCur,      /* Cursor pointing to entry to read from */
50942  u32 offset,          /* Begin reading this far into payload */
50943  u32 amt,             /* Read this many bytes */
50944  unsigned char *pBuf, /* Write the bytes into this buffer */
50945  int eOp              /* zero to read. non-zero to write. */
50946){
50947  unsigned char *aPayload;
50948  int rc = SQLITE_OK;
50949  u32 nKey;
50950  int iIdx = 0;
50951  MemPage *pPage = pCur->apPage[pCur->iPage]; /* Btree page of current entry */
50952  BtShared *pBt = pCur->pBt;                  /* Btree this cursor belongs to */
50953
50954  assert( pPage );
50955  assert( pCur->eState==CURSOR_VALID );
50956  assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
50957  assert( cursorHoldsMutex(pCur) );
50958
50959  getCellInfo(pCur);
50960  aPayload = pCur->info.pCell + pCur->info.nHeader;
50961  nKey = (pPage->intKey ? 0 : (int)pCur->info.nKey);
50962
50963  if( NEVER(offset+amt > nKey+pCur->info.nData)
50964   || &aPayload[pCur->info.nLocal] > &pPage->aData[pBt->usableSize]
50965  ){
50966    /* Trying to read or write past the end of the data is an error */
50967    return SQLITE_CORRUPT_BKPT;
50968  }
50969
50970  /* Check if data must be read/written to/from the btree page itself. */
50971  if( offset<pCur->info.nLocal ){
50972    int a = amt;
50973    if( a+offset>pCur->info.nLocal ){
50974      a = pCur->info.nLocal - offset;
50975    }
50976    rc = copyPayload(&aPayload[offset], pBuf, a, eOp, pPage->pDbPage);
50977    offset = 0;
50978    pBuf += a;
50979    amt -= a;
50980  }else{
50981    offset -= pCur->info.nLocal;
50982  }
50983
50984  if( rc==SQLITE_OK && amt>0 ){
50985    const u32 ovflSize = pBt->usableSize - 4;  /* Bytes content per ovfl page */
50986    Pgno nextPage;
50987
50988    nextPage = get4byte(&aPayload[pCur->info.nLocal]);
50989
50990#ifndef SQLITE_OMIT_INCRBLOB
50991    /* If the isIncrblobHandle flag is set and the BtCursor.aOverflow[]
50992    ** has not been allocated, allocate it now. The array is sized at
50993    ** one entry for each overflow page in the overflow chain. The
50994    ** page number of the first overflow page is stored in aOverflow[0],
50995    ** etc. A value of 0 in the aOverflow[] array means "not yet known"
50996    ** (the cache is lazily populated).
50997    */
50998    if( pCur->isIncrblobHandle && !pCur->aOverflow ){
50999      int nOvfl = (pCur->info.nPayload-pCur->info.nLocal+ovflSize-1)/ovflSize;
51000      pCur->aOverflow = (Pgno *)sqlite3MallocZero(sizeof(Pgno)*nOvfl);
51001      /* nOvfl is always positive.  If it were zero, fetchPayload would have
51002      ** been used instead of this routine. */
51003      if( ALWAYS(nOvfl) && !pCur->aOverflow ){
51004        rc = SQLITE_NOMEM;
51005      }
51006    }
51007
51008    /* If the overflow page-list cache has been allocated and the
51009    ** entry for the first required overflow page is valid, skip
51010    ** directly to it.
51011    */
51012    if( pCur->aOverflow && pCur->aOverflow[offset/ovflSize] ){
51013      iIdx = (offset/ovflSize);
51014      nextPage = pCur->aOverflow[iIdx];
51015      offset = (offset%ovflSize);
51016    }
51017#endif
51018
51019    for( ; rc==SQLITE_OK && amt>0 && nextPage; iIdx++){
51020
51021#ifndef SQLITE_OMIT_INCRBLOB
51022      /* If required, populate the overflow page-list cache. */
51023      if( pCur->aOverflow ){
51024        assert(!pCur->aOverflow[iIdx] || pCur->aOverflow[iIdx]==nextPage);
51025        pCur->aOverflow[iIdx] = nextPage;
51026      }
51027#endif
51028
51029      if( offset>=ovflSize ){
51030        /* The only reason to read this page is to obtain the page
51031        ** number for the next page in the overflow chain. The page
51032        ** data is not required. So first try to lookup the overflow
51033        ** page-list cache, if any, then fall back to the getOverflowPage()
51034        ** function.
51035        */
51036#ifndef SQLITE_OMIT_INCRBLOB
51037        if( pCur->aOverflow && pCur->aOverflow[iIdx+1] ){
51038          nextPage = pCur->aOverflow[iIdx+1];
51039        } else
51040#endif
51041          rc = getOverflowPage(pBt, nextPage, 0, &nextPage);
51042        offset -= ovflSize;
51043      }else{
51044        /* Need to read this page properly. It contains some of the
51045        ** range of data that is being read (eOp==0) or written (eOp!=0).
51046        */
51047        DbPage *pDbPage;
51048        int a = amt;
51049        rc = sqlite3PagerGet(pBt->pPager, nextPage, &pDbPage);
51050        if( rc==SQLITE_OK ){
51051          aPayload = sqlite3PagerGetData(pDbPage);
51052          nextPage = get4byte(aPayload);
51053          if( a + offset > ovflSize ){
51054            a = ovflSize - offset;
51055          }
51056          rc = copyPayload(&aPayload[offset+4], pBuf, a, eOp, pDbPage);
51057          sqlite3PagerUnref(pDbPage);
51058          offset = 0;
51059          amt -= a;
51060          pBuf += a;
51061        }
51062      }
51063    }
51064  }
51065
51066  if( rc==SQLITE_OK && amt>0 ){
51067    return SQLITE_CORRUPT_BKPT;
51068  }
51069  return rc;
51070}
51071
51072/*
51073** Read part of the key associated with cursor pCur.  Exactly
51074** "amt" bytes will be transfered into pBuf[].  The transfer
51075** begins at "offset".
51076**
51077** The caller must ensure that pCur is pointing to a valid row
51078** in the table.
51079**
51080** Return SQLITE_OK on success or an error code if anything goes
51081** wrong.  An error is returned if "offset+amt" is larger than
51082** the available payload.
51083*/
51084SQLITE_PRIVATE int sqlite3BtreeKey(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
51085  assert( cursorHoldsMutex(pCur) );
51086  assert( pCur->eState==CURSOR_VALID );
51087  assert( pCur->iPage>=0 && pCur->apPage[pCur->iPage] );
51088  assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
51089  return accessPayload(pCur, offset, amt, (unsigned char*)pBuf, 0);
51090}
51091
51092/*
51093** Read part of the data associated with cursor pCur.  Exactly
51094** "amt" bytes will be transfered into pBuf[].  The transfer
51095** begins at "offset".
51096**
51097** Return SQLITE_OK on success or an error code if anything goes
51098** wrong.  An error is returned if "offset+amt" is larger than
51099** the available payload.
51100*/
51101SQLITE_PRIVATE int sqlite3BtreeData(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
51102  int rc;
51103
51104#ifndef SQLITE_OMIT_INCRBLOB
51105  if ( pCur->eState==CURSOR_INVALID ){
51106    return SQLITE_ABORT;
51107  }
51108#endif
51109
51110  assert( cursorHoldsMutex(pCur) );
51111  rc = restoreCursorPosition(pCur);
51112  if( rc==SQLITE_OK ){
51113    assert( pCur->eState==CURSOR_VALID );
51114    assert( pCur->iPage>=0 && pCur->apPage[pCur->iPage] );
51115    assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
51116    rc = accessPayload(pCur, offset, amt, pBuf, 0);
51117  }
51118  return rc;
51119}
51120
51121/*
51122** Return a pointer to payload information from the entry that the
51123** pCur cursor is pointing to.  The pointer is to the beginning of
51124** the key if skipKey==0 and it points to the beginning of data if
51125** skipKey==1.  The number of bytes of available key/data is written
51126** into *pAmt.  If *pAmt==0, then the value returned will not be
51127** a valid pointer.
51128**
51129** This routine is an optimization.  It is common for the entire key
51130** and data to fit on the local page and for there to be no overflow
51131** pages.  When that is so, this routine can be used to access the
51132** key and data without making a copy.  If the key and/or data spills
51133** onto overflow pages, then accessPayload() must be used to reassemble
51134** the key/data and copy it into a preallocated buffer.
51135**
51136** The pointer returned by this routine looks directly into the cached
51137** page of the database.  The data might change or move the next time
51138** any btree routine is called.
51139*/
51140static const unsigned char *fetchPayload(
51141  BtCursor *pCur,      /* Cursor pointing to entry to read from */
51142  int *pAmt,           /* Write the number of available bytes here */
51143  int skipKey          /* read beginning at data if this is true */
51144){
51145  unsigned char *aPayload;
51146  MemPage *pPage;
51147  u32 nKey;
51148  u32 nLocal;
51149
51150  assert( pCur!=0 && pCur->iPage>=0 && pCur->apPage[pCur->iPage]);
51151  assert( pCur->eState==CURSOR_VALID );
51152  assert( cursorHoldsMutex(pCur) );
51153  pPage = pCur->apPage[pCur->iPage];
51154  assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
51155  if( NEVER(pCur->info.nSize==0) ){
51156    btreeParseCell(pCur->apPage[pCur->iPage], pCur->aiIdx[pCur->iPage],
51157                   &pCur->info);
51158  }
51159  aPayload = pCur->info.pCell;
51160  aPayload += pCur->info.nHeader;
51161  if( pPage->intKey ){
51162    nKey = 0;
51163  }else{
51164    nKey = (int)pCur->info.nKey;
51165  }
51166  if( skipKey ){
51167    aPayload += nKey;
51168    nLocal = pCur->info.nLocal - nKey;
51169  }else{
51170    nLocal = pCur->info.nLocal;
51171    assert( nLocal<=nKey );
51172  }
51173  *pAmt = nLocal;
51174  return aPayload;
51175}
51176
51177
51178/*
51179** For the entry that cursor pCur is point to, return as
51180** many bytes of the key or data as are available on the local
51181** b-tree page.  Write the number of available bytes into *pAmt.
51182**
51183** The pointer returned is ephemeral.  The key/data may move
51184** or be destroyed on the next call to any Btree routine,
51185** including calls from other threads against the same cache.
51186** Hence, a mutex on the BtShared should be held prior to calling
51187** this routine.
51188**
51189** These routines is used to get quick access to key and data
51190** in the common case where no overflow pages are used.
51191*/
51192SQLITE_PRIVATE const void *sqlite3BtreeKeyFetch(BtCursor *pCur, int *pAmt){
51193  const void *p = 0;
51194  assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
51195  assert( cursorHoldsMutex(pCur) );
51196  if( ALWAYS(pCur->eState==CURSOR_VALID) ){
51197    p = (const void*)fetchPayload(pCur, pAmt, 0);
51198  }
51199  return p;
51200}
51201SQLITE_PRIVATE const void *sqlite3BtreeDataFetch(BtCursor *pCur, int *pAmt){
51202  const void *p = 0;
51203  assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
51204  assert( cursorHoldsMutex(pCur) );
51205  if( ALWAYS(pCur->eState==CURSOR_VALID) ){
51206    p = (const void*)fetchPayload(pCur, pAmt, 1);
51207  }
51208  return p;
51209}
51210
51211
51212/*
51213** Move the cursor down to a new child page.  The newPgno argument is the
51214** page number of the child page to move to.
51215**
51216** This function returns SQLITE_CORRUPT if the page-header flags field of
51217** the new child page does not match the flags field of the parent (i.e.
51218** if an intkey page appears to be the parent of a non-intkey page, or
51219** vice-versa).
51220*/
51221static int moveToChild(BtCursor *pCur, u32 newPgno){
51222  int rc;
51223  int i = pCur->iPage;
51224  MemPage *pNewPage;
51225  BtShared *pBt = pCur->pBt;
51226
51227  assert( cursorHoldsMutex(pCur) );
51228  assert( pCur->eState==CURSOR_VALID );
51229  assert( pCur->iPage<BTCURSOR_MAX_DEPTH );
51230  if( pCur->iPage>=(BTCURSOR_MAX_DEPTH-1) ){
51231    return SQLITE_CORRUPT_BKPT;
51232  }
51233  rc = getAndInitPage(pBt, newPgno, &pNewPage);
51234  if( rc ) return rc;
51235  pCur->apPage[i+1] = pNewPage;
51236  pCur->aiIdx[i+1] = 0;
51237  pCur->iPage++;
51238
51239  pCur->info.nSize = 0;
51240  pCur->validNKey = 0;
51241  if( pNewPage->nCell<1 || pNewPage->intKey!=pCur->apPage[i]->intKey ){
51242    return SQLITE_CORRUPT_BKPT;
51243  }
51244  return SQLITE_OK;
51245}
51246
51247#ifndef NDEBUG
51248/*
51249** Page pParent is an internal (non-leaf) tree page. This function
51250** asserts that page number iChild is the left-child if the iIdx'th
51251** cell in page pParent. Or, if iIdx is equal to the total number of
51252** cells in pParent, that page number iChild is the right-child of
51253** the page.
51254*/
51255static void assertParentIndex(MemPage *pParent, int iIdx, Pgno iChild){
51256  assert( iIdx<=pParent->nCell );
51257  if( iIdx==pParent->nCell ){
51258    assert( get4byte(&pParent->aData[pParent->hdrOffset+8])==iChild );
51259  }else{
51260    assert( get4byte(findCell(pParent, iIdx))==iChild );
51261  }
51262}
51263#else
51264#  define assertParentIndex(x,y,z)
51265#endif
51266
51267/*
51268** Move the cursor up to the parent page.
51269**
51270** pCur->idx is set to the cell index that contains the pointer
51271** to the page we are coming from.  If we are coming from the
51272** right-most child page then pCur->idx is set to one more than
51273** the largest cell index.
51274*/
51275static void moveToParent(BtCursor *pCur){
51276  assert( cursorHoldsMutex(pCur) );
51277  assert( pCur->eState==CURSOR_VALID );
51278  assert( pCur->iPage>0 );
51279  assert( pCur->apPage[pCur->iPage] );
51280  assertParentIndex(
51281    pCur->apPage[pCur->iPage-1],
51282    pCur->aiIdx[pCur->iPage-1],
51283    pCur->apPage[pCur->iPage]->pgno
51284  );
51285  releasePage(pCur->apPage[pCur->iPage]);
51286  pCur->iPage--;
51287  pCur->info.nSize = 0;
51288  pCur->validNKey = 0;
51289}
51290
51291/*
51292** Move the cursor to point to the root page of its b-tree structure.
51293**
51294** If the table has a virtual root page, then the cursor is moved to point
51295** to the virtual root page instead of the actual root page. A table has a
51296** virtual root page when the actual root page contains no cells and a
51297** single child page. This can only happen with the table rooted at page 1.
51298**
51299** If the b-tree structure is empty, the cursor state is set to
51300** CURSOR_INVALID. Otherwise, the cursor is set to point to the first
51301** cell located on the root (or virtual root) page and the cursor state
51302** is set to CURSOR_VALID.
51303**
51304** If this function returns successfully, it may be assumed that the
51305** page-header flags indicate that the [virtual] root-page is the expected
51306** kind of b-tree page (i.e. if when opening the cursor the caller did not
51307** specify a KeyInfo structure the flags byte is set to 0x05 or 0x0D,
51308** indicating a table b-tree, or if the caller did specify a KeyInfo
51309** structure the flags byte is set to 0x02 or 0x0A, indicating an index
51310** b-tree).
51311*/
51312static int moveToRoot(BtCursor *pCur){
51313  MemPage *pRoot;
51314  int rc = SQLITE_OK;
51315  Btree *p = pCur->pBtree;
51316  BtShared *pBt = p->pBt;
51317
51318  assert( cursorHoldsMutex(pCur) );
51319  assert( CURSOR_INVALID < CURSOR_REQUIRESEEK );
51320  assert( CURSOR_VALID   < CURSOR_REQUIRESEEK );
51321  assert( CURSOR_FAULT   > CURSOR_REQUIRESEEK );
51322  if( pCur->eState>=CURSOR_REQUIRESEEK ){
51323    if( pCur->eState==CURSOR_FAULT ){
51324      assert( pCur->skipNext!=SQLITE_OK );
51325      return pCur->skipNext;
51326    }
51327    sqlite3BtreeClearCursor(pCur);
51328  }
51329
51330  if( pCur->iPage>=0 ){
51331    int i;
51332    for(i=1; i<=pCur->iPage; i++){
51333      releasePage(pCur->apPage[i]);
51334    }
51335    pCur->iPage = 0;
51336  }else{
51337    rc = getAndInitPage(pBt, pCur->pgnoRoot, &pCur->apPage[0]);
51338    if( rc!=SQLITE_OK ){
51339      pCur->eState = CURSOR_INVALID;
51340      return rc;
51341    }
51342    pCur->iPage = 0;
51343
51344    /* If pCur->pKeyInfo is not NULL, then the caller that opened this cursor
51345    ** expected to open it on an index b-tree. Otherwise, if pKeyInfo is
51346    ** NULL, the caller expects a table b-tree. If this is not the case,
51347    ** return an SQLITE_CORRUPT error.  */
51348    assert( pCur->apPage[0]->intKey==1 || pCur->apPage[0]->intKey==0 );
51349    if( (pCur->pKeyInfo==0)!=pCur->apPage[0]->intKey ){
51350      return SQLITE_CORRUPT_BKPT;
51351    }
51352  }
51353
51354  /* Assert that the root page is of the correct type. This must be the
51355  ** case as the call to this function that loaded the root-page (either
51356  ** this call or a previous invocation) would have detected corruption
51357  ** if the assumption were not true, and it is not possible for the flags
51358  ** byte to have been modified while this cursor is holding a reference
51359  ** to the page.  */
51360  pRoot = pCur->apPage[0];
51361  assert( pRoot->pgno==pCur->pgnoRoot );
51362  assert( pRoot->isInit && (pCur->pKeyInfo==0)==pRoot->intKey );
51363
51364  pCur->aiIdx[0] = 0;
51365  pCur->info.nSize = 0;
51366  pCur->atLast = 0;
51367  pCur->validNKey = 0;
51368
51369  if( pRoot->nCell==0 && !pRoot->leaf ){
51370    Pgno subpage;
51371    if( pRoot->pgno!=1 ) return SQLITE_CORRUPT_BKPT;
51372    subpage = get4byte(&pRoot->aData[pRoot->hdrOffset+8]);
51373    pCur->eState = CURSOR_VALID;
51374    rc = moveToChild(pCur, subpage);
51375  }else{
51376    pCur->eState = ((pRoot->nCell>0)?CURSOR_VALID:CURSOR_INVALID);
51377  }
51378  return rc;
51379}
51380
51381/*
51382** Move the cursor down to the left-most leaf entry beneath the
51383** entry to which it is currently pointing.
51384**
51385** The left-most leaf is the one with the smallest key - the first
51386** in ascending order.
51387*/
51388static int moveToLeftmost(BtCursor *pCur){
51389  Pgno pgno;
51390  int rc = SQLITE_OK;
51391  MemPage *pPage;
51392
51393  assert( cursorHoldsMutex(pCur) );
51394  assert( pCur->eState==CURSOR_VALID );
51395  while( rc==SQLITE_OK && !(pPage = pCur->apPage[pCur->iPage])->leaf ){
51396    assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
51397    pgno = get4byte(findCell(pPage, pCur->aiIdx[pCur->iPage]));
51398    rc = moveToChild(pCur, pgno);
51399  }
51400  return rc;
51401}
51402
51403/*
51404** Move the cursor down to the right-most leaf entry beneath the
51405** page to which it is currently pointing.  Notice the difference
51406** between moveToLeftmost() and moveToRightmost().  moveToLeftmost()
51407** finds the left-most entry beneath the *entry* whereas moveToRightmost()
51408** finds the right-most entry beneath the *page*.
51409**
51410** The right-most entry is the one with the largest key - the last
51411** key in ascending order.
51412*/
51413static int moveToRightmost(BtCursor *pCur){
51414  Pgno pgno;
51415  int rc = SQLITE_OK;
51416  MemPage *pPage = 0;
51417
51418  assert( cursorHoldsMutex(pCur) );
51419  assert( pCur->eState==CURSOR_VALID );
51420  while( rc==SQLITE_OK && !(pPage = pCur->apPage[pCur->iPage])->leaf ){
51421    pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
51422    pCur->aiIdx[pCur->iPage] = pPage->nCell;
51423    rc = moveToChild(pCur, pgno);
51424  }
51425  if( rc==SQLITE_OK ){
51426    pCur->aiIdx[pCur->iPage] = pPage->nCell-1;
51427    pCur->info.nSize = 0;
51428    pCur->validNKey = 0;
51429  }
51430  return rc;
51431}
51432
51433/* Move the cursor to the first entry in the table.  Return SQLITE_OK
51434** on success.  Set *pRes to 0 if the cursor actually points to something
51435** or set *pRes to 1 if the table is empty.
51436*/
51437SQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor *pCur, int *pRes){
51438  int rc;
51439
51440  assert( cursorHoldsMutex(pCur) );
51441  assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
51442  rc = moveToRoot(pCur);
51443  if( rc==SQLITE_OK ){
51444    if( pCur->eState==CURSOR_INVALID ){
51445      assert( pCur->apPage[pCur->iPage]->nCell==0 );
51446      *pRes = 1;
51447    }else{
51448      assert( pCur->apPage[pCur->iPage]->nCell>0 );
51449      *pRes = 0;
51450      rc = moveToLeftmost(pCur);
51451    }
51452  }
51453  return rc;
51454}
51455
51456/* Move the cursor to the last entry in the table.  Return SQLITE_OK
51457** on success.  Set *pRes to 0 if the cursor actually points to something
51458** or set *pRes to 1 if the table is empty.
51459*/
51460SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor *pCur, int *pRes){
51461  int rc;
51462
51463  assert( cursorHoldsMutex(pCur) );
51464  assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
51465
51466  /* If the cursor already points to the last entry, this is a no-op. */
51467  if( CURSOR_VALID==pCur->eState && pCur->atLast ){
51468#ifdef SQLITE_DEBUG
51469    /* This block serves to assert() that the cursor really does point
51470    ** to the last entry in the b-tree. */
51471    int ii;
51472    for(ii=0; ii<pCur->iPage; ii++){
51473      assert( pCur->aiIdx[ii]==pCur->apPage[ii]->nCell );
51474    }
51475    assert( pCur->aiIdx[pCur->iPage]==pCur->apPage[pCur->iPage]->nCell-1 );
51476    assert( pCur->apPage[pCur->iPage]->leaf );
51477#endif
51478    return SQLITE_OK;
51479  }
51480
51481  rc = moveToRoot(pCur);
51482  if( rc==SQLITE_OK ){
51483    if( CURSOR_INVALID==pCur->eState ){
51484      assert( pCur->apPage[pCur->iPage]->nCell==0 );
51485      *pRes = 1;
51486    }else{
51487      assert( pCur->eState==CURSOR_VALID );
51488      *pRes = 0;
51489      rc = moveToRightmost(pCur);
51490      pCur->atLast = rc==SQLITE_OK ?1:0;
51491    }
51492  }
51493  return rc;
51494}
51495
51496/* Move the cursor so that it points to an entry near the key
51497** specified by pIdxKey or intKey.   Return a success code.
51498**
51499** For INTKEY tables, the intKey parameter is used.  pIdxKey
51500** must be NULL.  For index tables, pIdxKey is used and intKey
51501** is ignored.
51502**
51503** If an exact match is not found, then the cursor is always
51504** left pointing at a leaf page which would hold the entry if it
51505** were present.  The cursor might point to an entry that comes
51506** before or after the key.
51507**
51508** An integer is written into *pRes which is the result of
51509** comparing the key with the entry to which the cursor is
51510** pointing.  The meaning of the integer written into
51511** *pRes is as follows:
51512**
51513**     *pRes<0      The cursor is left pointing at an entry that
51514**                  is smaller than intKey/pIdxKey or if the table is empty
51515**                  and the cursor is therefore left point to nothing.
51516**
51517**     *pRes==0     The cursor is left pointing at an entry that
51518**                  exactly matches intKey/pIdxKey.
51519**
51520**     *pRes>0      The cursor is left pointing at an entry that
51521**                  is larger than intKey/pIdxKey.
51522**
51523*/
51524SQLITE_PRIVATE int sqlite3BtreeMovetoUnpacked(
51525  BtCursor *pCur,          /* The cursor to be moved */
51526  UnpackedRecord *pIdxKey, /* Unpacked index key */
51527  i64 intKey,              /* The table key */
51528  int biasRight,           /* If true, bias the search to the high end */
51529  int *pRes                /* Write search results here */
51530){
51531  int rc;
51532
51533  assert( cursorHoldsMutex(pCur) );
51534  assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
51535  assert( pRes );
51536  assert( (pIdxKey==0)==(pCur->pKeyInfo==0) );
51537
51538  /* If the cursor is already positioned at the point we are trying
51539  ** to move to, then just return without doing any work */
51540  if( pCur->eState==CURSOR_VALID && pCur->validNKey
51541   && pCur->apPage[0]->intKey
51542  ){
51543    if( pCur->info.nKey==intKey ){
51544      *pRes = 0;
51545      return SQLITE_OK;
51546    }
51547    if( pCur->atLast && pCur->info.nKey<intKey ){
51548      *pRes = -1;
51549      return SQLITE_OK;
51550    }
51551  }
51552
51553  rc = moveToRoot(pCur);
51554  if( rc ){
51555    return rc;
51556  }
51557  assert( pCur->apPage[pCur->iPage] );
51558  assert( pCur->apPage[pCur->iPage]->isInit );
51559  assert( pCur->apPage[pCur->iPage]->nCell>0 || pCur->eState==CURSOR_INVALID );
51560  if( pCur->eState==CURSOR_INVALID ){
51561    *pRes = -1;
51562    assert( pCur->apPage[pCur->iPage]->nCell==0 );
51563    return SQLITE_OK;
51564  }
51565  assert( pCur->apPage[0]->intKey || pIdxKey );
51566  for(;;){
51567    int lwr, upr;
51568    Pgno chldPg;
51569    MemPage *pPage = pCur->apPage[pCur->iPage];
51570    int c;
51571
51572    /* pPage->nCell must be greater than zero. If this is the root-page
51573    ** the cursor would have been INVALID above and this for(;;) loop
51574    ** not run. If this is not the root-page, then the moveToChild() routine
51575    ** would have already detected db corruption. Similarly, pPage must
51576    ** be the right kind (index or table) of b-tree page. Otherwise
51577    ** a moveToChild() or moveToRoot() call would have detected corruption.  */
51578    assert( pPage->nCell>0 );
51579    assert( pPage->intKey==(pIdxKey==0) );
51580    lwr = 0;
51581    upr = pPage->nCell-1;
51582    if( biasRight ){
51583      pCur->aiIdx[pCur->iPage] = (u16)upr;
51584    }else{
51585      pCur->aiIdx[pCur->iPage] = (u16)((upr+lwr)/2);
51586    }
51587    for(;;){
51588      int idx = pCur->aiIdx[pCur->iPage]; /* Index of current cell in pPage */
51589      u8 *pCell;                          /* Pointer to current cell in pPage */
51590
51591      pCur->info.nSize = 0;
51592      pCell = findCell(pPage, idx) + pPage->childPtrSize;
51593      if( pPage->intKey ){
51594        i64 nCellKey;
51595        if( pPage->hasData ){
51596          u32 dummy;
51597          pCell += getVarint32(pCell, dummy);
51598        }
51599        getVarint(pCell, (u64*)&nCellKey);
51600        if( nCellKey==intKey ){
51601          c = 0;
51602        }else if( nCellKey<intKey ){
51603          c = -1;
51604        }else{
51605          assert( nCellKey>intKey );
51606          c = +1;
51607        }
51608        pCur->validNKey = 1;
51609        pCur->info.nKey = nCellKey;
51610      }else{
51611        /* The maximum supported page-size is 65536 bytes. This means that
51612        ** the maximum number of record bytes stored on an index B-Tree
51613        ** page is less than 16384 bytes and may be stored as a 2-byte
51614        ** varint. This information is used to attempt to avoid parsing
51615        ** the entire cell by checking for the cases where the record is
51616        ** stored entirely within the b-tree page by inspecting the first
51617        ** 2 bytes of the cell.
51618        */
51619        int nCell = pCell[0];
51620        if( !(nCell & 0x80) && nCell<=pPage->maxLocal ){
51621          /* This branch runs if the record-size field of the cell is a
51622          ** single byte varint and the record fits entirely on the main
51623          ** b-tree page.  */
51624          c = sqlite3VdbeRecordCompare(nCell, (void*)&pCell[1], pIdxKey);
51625        }else if( !(pCell[1] & 0x80)
51626          && (nCell = ((nCell&0x7f)<<7) + pCell[1])<=pPage->maxLocal
51627        ){
51628          /* The record-size field is a 2 byte varint and the record
51629          ** fits entirely on the main b-tree page.  */
51630          c = sqlite3VdbeRecordCompare(nCell, (void*)&pCell[2], pIdxKey);
51631        }else{
51632          /* The record flows over onto one or more overflow pages. In
51633          ** this case the whole cell needs to be parsed, a buffer allocated
51634          ** and accessPayload() used to retrieve the record into the
51635          ** buffer before VdbeRecordCompare() can be called. */
51636          void *pCellKey;
51637          u8 * const pCellBody = pCell - pPage->childPtrSize;
51638          btreeParseCellPtr(pPage, pCellBody, &pCur->info);
51639          nCell = (int)pCur->info.nKey;
51640          pCellKey = sqlite3Malloc( nCell );
51641          if( pCellKey==0 ){
51642            rc = SQLITE_NOMEM;
51643            goto moveto_finish;
51644          }
51645          rc = accessPayload(pCur, 0, nCell, (unsigned char*)pCellKey, 0);
51646          if( rc ){
51647            sqlite3_free(pCellKey);
51648            goto moveto_finish;
51649          }
51650          c = sqlite3VdbeRecordCompare(nCell, pCellKey, pIdxKey);
51651          sqlite3_free(pCellKey);
51652        }
51653      }
51654      if( c==0 ){
51655        if( pPage->intKey && !pPage->leaf ){
51656          lwr = idx;
51657          upr = lwr - 1;
51658          break;
51659        }else{
51660          *pRes = 0;
51661          rc = SQLITE_OK;
51662          goto moveto_finish;
51663        }
51664      }
51665      if( c<0 ){
51666        lwr = idx+1;
51667      }else{
51668        upr = idx-1;
51669      }
51670      if( lwr>upr ){
51671        break;
51672      }
51673      pCur->aiIdx[pCur->iPage] = (u16)((lwr+upr)/2);
51674    }
51675    assert( lwr==upr+1 );
51676    assert( pPage->isInit );
51677    if( pPage->leaf ){
51678      chldPg = 0;
51679    }else if( lwr>=pPage->nCell ){
51680      chldPg = get4byte(&pPage->aData[pPage->hdrOffset+8]);
51681    }else{
51682      chldPg = get4byte(findCell(pPage, lwr));
51683    }
51684    if( chldPg==0 ){
51685      assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
51686      *pRes = c;
51687      rc = SQLITE_OK;
51688      goto moveto_finish;
51689    }
51690    pCur->aiIdx[pCur->iPage] = (u16)lwr;
51691    pCur->info.nSize = 0;
51692    pCur->validNKey = 0;
51693    rc = moveToChild(pCur, chldPg);
51694    if( rc ) goto moveto_finish;
51695  }
51696moveto_finish:
51697  return rc;
51698}
51699
51700
51701/*
51702** Return TRUE if the cursor is not pointing at an entry of the table.
51703**
51704** TRUE will be returned after a call to sqlite3BtreeNext() moves
51705** past the last entry in the table or sqlite3BtreePrev() moves past
51706** the first entry.  TRUE is also returned if the table is empty.
51707*/
51708SQLITE_PRIVATE int sqlite3BtreeEof(BtCursor *pCur){
51709  /* TODO: What if the cursor is in CURSOR_REQUIRESEEK but all table entries
51710  ** have been deleted? This API will need to change to return an error code
51711  ** as well as the boolean result value.
51712  */
51713  return (CURSOR_VALID!=pCur->eState);
51714}
51715
51716/*
51717** Advance the cursor to the next entry in the database.  If
51718** successful then set *pRes=0.  If the cursor
51719** was already pointing to the last entry in the database before
51720** this routine was called, then set *pRes=1.
51721*/
51722SQLITE_PRIVATE int sqlite3BtreeNext(BtCursor *pCur, int *pRes){
51723  int rc;
51724  int idx;
51725  MemPage *pPage;
51726
51727  assert( cursorHoldsMutex(pCur) );
51728  rc = restoreCursorPosition(pCur);
51729  if( rc!=SQLITE_OK ){
51730    return rc;
51731  }
51732  assert( pRes!=0 );
51733  if( CURSOR_INVALID==pCur->eState ){
51734    *pRes = 1;
51735    return SQLITE_OK;
51736  }
51737  if( pCur->skipNext>0 ){
51738    pCur->skipNext = 0;
51739    *pRes = 0;
51740    return SQLITE_OK;
51741  }
51742  pCur->skipNext = 0;
51743
51744  pPage = pCur->apPage[pCur->iPage];
51745  idx = ++pCur->aiIdx[pCur->iPage];
51746  assert( pPage->isInit );
51747  assert( idx<=pPage->nCell );
51748
51749  pCur->info.nSize = 0;
51750  pCur->validNKey = 0;
51751  if( idx>=pPage->nCell ){
51752    if( !pPage->leaf ){
51753      rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
51754      if( rc ) return rc;
51755      rc = moveToLeftmost(pCur);
51756      *pRes = 0;
51757      return rc;
51758    }
51759    do{
51760      if( pCur->iPage==0 ){
51761        *pRes = 1;
51762        pCur->eState = CURSOR_INVALID;
51763        return SQLITE_OK;
51764      }
51765      moveToParent(pCur);
51766      pPage = pCur->apPage[pCur->iPage];
51767    }while( pCur->aiIdx[pCur->iPage]>=pPage->nCell );
51768    *pRes = 0;
51769    if( pPage->intKey ){
51770      rc = sqlite3BtreeNext(pCur, pRes);
51771    }else{
51772      rc = SQLITE_OK;
51773    }
51774    return rc;
51775  }
51776  *pRes = 0;
51777  if( pPage->leaf ){
51778    return SQLITE_OK;
51779  }
51780  rc = moveToLeftmost(pCur);
51781  return rc;
51782}
51783
51784
51785/*
51786** Step the cursor to the back to the previous entry in the database.  If
51787** successful then set *pRes=0.  If the cursor
51788** was already pointing to the first entry in the database before
51789** this routine was called, then set *pRes=1.
51790*/
51791SQLITE_PRIVATE int sqlite3BtreePrevious(BtCursor *pCur, int *pRes){
51792  int rc;
51793  MemPage *pPage;
51794
51795  assert( cursorHoldsMutex(pCur) );
51796  rc = restoreCursorPosition(pCur);
51797  if( rc!=SQLITE_OK ){
51798    return rc;
51799  }
51800  pCur->atLast = 0;
51801  if( CURSOR_INVALID==pCur->eState ){
51802    *pRes = 1;
51803    return SQLITE_OK;
51804  }
51805  if( pCur->skipNext<0 ){
51806    pCur->skipNext = 0;
51807    *pRes = 0;
51808    return SQLITE_OK;
51809  }
51810  pCur->skipNext = 0;
51811
51812  pPage = pCur->apPage[pCur->iPage];
51813  assert( pPage->isInit );
51814  if( !pPage->leaf ){
51815    int idx = pCur->aiIdx[pCur->iPage];
51816    rc = moveToChild(pCur, get4byte(findCell(pPage, idx)));
51817    if( rc ){
51818      return rc;
51819    }
51820    rc = moveToRightmost(pCur);
51821  }else{
51822    while( pCur->aiIdx[pCur->iPage]==0 ){
51823      if( pCur->iPage==0 ){
51824        pCur->eState = CURSOR_INVALID;
51825        *pRes = 1;
51826        return SQLITE_OK;
51827      }
51828      moveToParent(pCur);
51829    }
51830    pCur->info.nSize = 0;
51831    pCur->validNKey = 0;
51832
51833    pCur->aiIdx[pCur->iPage]--;
51834    pPage = pCur->apPage[pCur->iPage];
51835    if( pPage->intKey && !pPage->leaf ){
51836      rc = sqlite3BtreePrevious(pCur, pRes);
51837    }else{
51838      rc = SQLITE_OK;
51839    }
51840  }
51841  *pRes = 0;
51842  return rc;
51843}
51844
51845/*
51846** Allocate a new page from the database file.
51847**
51848** The new page is marked as dirty.  (In other words, sqlite3PagerWrite()
51849** has already been called on the new page.)  The new page has also
51850** been referenced and the calling routine is responsible for calling
51851** sqlite3PagerUnref() on the new page when it is done.
51852**
51853** SQLITE_OK is returned on success.  Any other return value indicates
51854** an error.  *ppPage and *pPgno are undefined in the event of an error.
51855** Do not invoke sqlite3PagerUnref() on *ppPage if an error is returned.
51856**
51857** If the "nearby" parameter is not 0, then a (feeble) effort is made to
51858** locate a page close to the page number "nearby".  This can be used in an
51859** attempt to keep related pages close to each other in the database file,
51860** which in turn can make database access faster.
51861**
51862** If the "exact" parameter is not 0, and the page-number nearby exists
51863** anywhere on the free-list, then it is guarenteed to be returned. This
51864** is only used by auto-vacuum databases when allocating a new table.
51865*/
51866static int allocateBtreePage(
51867  BtShared *pBt,
51868  MemPage **ppPage,
51869  Pgno *pPgno,
51870  Pgno nearby,
51871  u8 exact
51872){
51873  MemPage *pPage1;
51874  int rc;
51875  u32 n;     /* Number of pages on the freelist */
51876  u32 k;     /* Number of leaves on the trunk of the freelist */
51877  MemPage *pTrunk = 0;
51878  MemPage *pPrevTrunk = 0;
51879  Pgno mxPage;     /* Total size of the database file */
51880
51881  assert( sqlite3_mutex_held(pBt->mutex) );
51882  pPage1 = pBt->pPage1;
51883  mxPage = btreePagecount(pBt);
51884  n = get4byte(&pPage1->aData[36]);
51885  testcase( n==mxPage-1 );
51886  if( n>=mxPage ){
51887    return SQLITE_CORRUPT_BKPT;
51888  }
51889  if( n>0 ){
51890    /* There are pages on the freelist.  Reuse one of those pages. */
51891    Pgno iTrunk;
51892    u8 searchList = 0; /* If the free-list must be searched for 'nearby' */
51893
51894    /* If the 'exact' parameter was true and a query of the pointer-map
51895    ** shows that the page 'nearby' is somewhere on the free-list, then
51896    ** the entire-list will be searched for that page.
51897    */
51898#ifndef SQLITE_OMIT_AUTOVACUUM
51899    if( exact && nearby<=mxPage ){
51900      u8 eType;
51901      assert( nearby>0 );
51902      assert( pBt->autoVacuum );
51903      rc = ptrmapGet(pBt, nearby, &eType, 0);
51904      if( rc ) return rc;
51905      if( eType==PTRMAP_FREEPAGE ){
51906        searchList = 1;
51907      }
51908      *pPgno = nearby;
51909    }
51910#endif
51911
51912    /* Decrement the free-list count by 1. Set iTrunk to the index of the
51913    ** first free-list trunk page. iPrevTrunk is initially 1.
51914    */
51915    rc = sqlite3PagerWrite(pPage1->pDbPage);
51916    if( rc ) return rc;
51917    put4byte(&pPage1->aData[36], n-1);
51918
51919    /* The code within this loop is run only once if the 'searchList' variable
51920    ** is not true. Otherwise, it runs once for each trunk-page on the
51921    ** free-list until the page 'nearby' is located.
51922    */
51923    do {
51924      pPrevTrunk = pTrunk;
51925      if( pPrevTrunk ){
51926        iTrunk = get4byte(&pPrevTrunk->aData[0]);
51927      }else{
51928        iTrunk = get4byte(&pPage1->aData[32]);
51929      }
51930      testcase( iTrunk==mxPage );
51931      if( iTrunk>mxPage ){
51932        rc = SQLITE_CORRUPT_BKPT;
51933      }else{
51934        rc = btreeGetPage(pBt, iTrunk, &pTrunk, 0);
51935      }
51936      if( rc ){
51937        pTrunk = 0;
51938        goto end_allocate_page;
51939      }
51940
51941      k = get4byte(&pTrunk->aData[4]); /* # of leaves on this trunk page */
51942      if( k==0 && !searchList ){
51943        /* The trunk has no leaves and the list is not being searched.
51944        ** So extract the trunk page itself and use it as the newly
51945        ** allocated page */
51946        assert( pPrevTrunk==0 );
51947        rc = sqlite3PagerWrite(pTrunk->pDbPage);
51948        if( rc ){
51949          goto end_allocate_page;
51950        }
51951        *pPgno = iTrunk;
51952        memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
51953        *ppPage = pTrunk;
51954        pTrunk = 0;
51955        TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
51956      }else if( k>(u32)(pBt->usableSize/4 - 2) ){
51957        /* Value of k is out of range.  Database corruption */
51958        rc = SQLITE_CORRUPT_BKPT;
51959        goto end_allocate_page;
51960#ifndef SQLITE_OMIT_AUTOVACUUM
51961      }else if( searchList && nearby==iTrunk ){
51962        /* The list is being searched and this trunk page is the page
51963        ** to allocate, regardless of whether it has leaves.
51964        */
51965        assert( *pPgno==iTrunk );
51966        *ppPage = pTrunk;
51967        searchList = 0;
51968        rc = sqlite3PagerWrite(pTrunk->pDbPage);
51969        if( rc ){
51970          goto end_allocate_page;
51971        }
51972        if( k==0 ){
51973          if( !pPrevTrunk ){
51974            memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
51975          }else{
51976            rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
51977            if( rc!=SQLITE_OK ){
51978              goto end_allocate_page;
51979            }
51980            memcpy(&pPrevTrunk->aData[0], &pTrunk->aData[0], 4);
51981          }
51982        }else{
51983          /* The trunk page is required by the caller but it contains
51984          ** pointers to free-list leaves. The first leaf becomes a trunk
51985          ** page in this case.
51986          */
51987          MemPage *pNewTrunk;
51988          Pgno iNewTrunk = get4byte(&pTrunk->aData[8]);
51989          if( iNewTrunk>mxPage ){
51990            rc = SQLITE_CORRUPT_BKPT;
51991            goto end_allocate_page;
51992          }
51993          testcase( iNewTrunk==mxPage );
51994          rc = btreeGetPage(pBt, iNewTrunk, &pNewTrunk, 0);
51995          if( rc!=SQLITE_OK ){
51996            goto end_allocate_page;
51997          }
51998          rc = sqlite3PagerWrite(pNewTrunk->pDbPage);
51999          if( rc!=SQLITE_OK ){
52000            releasePage(pNewTrunk);
52001            goto end_allocate_page;
52002          }
52003          memcpy(&pNewTrunk->aData[0], &pTrunk->aData[0], 4);
52004          put4byte(&pNewTrunk->aData[4], k-1);
52005          memcpy(&pNewTrunk->aData[8], &pTrunk->aData[12], (k-1)*4);
52006          releasePage(pNewTrunk);
52007          if( !pPrevTrunk ){
52008            assert( sqlite3PagerIswriteable(pPage1->pDbPage) );
52009            put4byte(&pPage1->aData[32], iNewTrunk);
52010          }else{
52011            rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
52012            if( rc ){
52013              goto end_allocate_page;
52014            }
52015            put4byte(&pPrevTrunk->aData[0], iNewTrunk);
52016          }
52017        }
52018        pTrunk = 0;
52019        TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
52020#endif
52021      }else if( k>0 ){
52022        /* Extract a leaf from the trunk */
52023        u32 closest;
52024        Pgno iPage;
52025        unsigned char *aData = pTrunk->aData;
52026        if( nearby>0 ){
52027          u32 i;
52028          int dist;
52029          closest = 0;
52030          dist = sqlite3AbsInt32(get4byte(&aData[8]) - nearby);
52031          for(i=1; i<k; i++){
52032            int d2 = sqlite3AbsInt32(get4byte(&aData[8+i*4]) - nearby);
52033            if( d2<dist ){
52034              closest = i;
52035              dist = d2;
52036            }
52037          }
52038        }else{
52039          closest = 0;
52040        }
52041
52042        iPage = get4byte(&aData[8+closest*4]);
52043        testcase( iPage==mxPage );
52044        if( iPage>mxPage ){
52045          rc = SQLITE_CORRUPT_BKPT;
52046          goto end_allocate_page;
52047        }
52048        testcase( iPage==mxPage );
52049        if( !searchList || iPage==nearby ){
52050          int noContent;
52051          *pPgno = iPage;
52052          TRACE(("ALLOCATE: %d was leaf %d of %d on trunk %d"
52053                 ": %d more free pages\n",
52054                 *pPgno, closest+1, k, pTrunk->pgno, n-1));
52055          rc = sqlite3PagerWrite(pTrunk->pDbPage);
52056          if( rc ) goto end_allocate_page;
52057          if( closest<k-1 ){
52058            memcpy(&aData[8+closest*4], &aData[4+k*4], 4);
52059          }
52060          put4byte(&aData[4], k-1);
52061          noContent = !btreeGetHasContent(pBt, *pPgno);
52062          rc = btreeGetPage(pBt, *pPgno, ppPage, noContent);
52063          if( rc==SQLITE_OK ){
52064            rc = sqlite3PagerWrite((*ppPage)->pDbPage);
52065            if( rc!=SQLITE_OK ){
52066              releasePage(*ppPage);
52067            }
52068          }
52069          searchList = 0;
52070        }
52071      }
52072      releasePage(pPrevTrunk);
52073      pPrevTrunk = 0;
52074    }while( searchList );
52075  }else{
52076    /* There are no pages on the freelist, so create a new page at the
52077    ** end of the file */
52078    rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
52079    if( rc ) return rc;
52080    pBt->nPage++;
52081    if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ) pBt->nPage++;
52082
52083#ifndef SQLITE_OMIT_AUTOVACUUM
52084    if( pBt->autoVacuum && PTRMAP_ISPAGE(pBt, pBt->nPage) ){
52085      /* If *pPgno refers to a pointer-map page, allocate two new pages
52086      ** at the end of the file instead of one. The first allocated page
52087      ** becomes a new pointer-map page, the second is used by the caller.
52088      */
52089      MemPage *pPg = 0;
52090      TRACE(("ALLOCATE: %d from end of file (pointer-map page)\n", pBt->nPage));
52091      assert( pBt->nPage!=PENDING_BYTE_PAGE(pBt) );
52092      rc = btreeGetPage(pBt, pBt->nPage, &pPg, 1);
52093      if( rc==SQLITE_OK ){
52094        rc = sqlite3PagerWrite(pPg->pDbPage);
52095        releasePage(pPg);
52096      }
52097      if( rc ) return rc;
52098      pBt->nPage++;
52099      if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ){ pBt->nPage++; }
52100    }
52101#endif
52102    put4byte(28 + (u8*)pBt->pPage1->aData, pBt->nPage);
52103    *pPgno = pBt->nPage;
52104
52105    assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
52106    rc = btreeGetPage(pBt, *pPgno, ppPage, 1);
52107    if( rc ) return rc;
52108    rc = sqlite3PagerWrite((*ppPage)->pDbPage);
52109    if( rc!=SQLITE_OK ){
52110      releasePage(*ppPage);
52111    }
52112    TRACE(("ALLOCATE: %d from end of file\n", *pPgno));
52113  }
52114
52115  assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
52116
52117end_allocate_page:
52118  releasePage(pTrunk);
52119  releasePage(pPrevTrunk);
52120  if( rc==SQLITE_OK ){
52121    if( sqlite3PagerPageRefcount((*ppPage)->pDbPage)>1 ){
52122      releasePage(*ppPage);
52123      return SQLITE_CORRUPT_BKPT;
52124    }
52125    (*ppPage)->isInit = 0;
52126  }else{
52127    *ppPage = 0;
52128  }
52129  assert( rc!=SQLITE_OK || sqlite3PagerIswriteable((*ppPage)->pDbPage) );
52130  return rc;
52131}
52132
52133/*
52134** This function is used to add page iPage to the database file free-list.
52135** It is assumed that the page is not already a part of the free-list.
52136**
52137** The value passed as the second argument to this function is optional.
52138** If the caller happens to have a pointer to the MemPage object
52139** corresponding to page iPage handy, it may pass it as the second value.
52140** Otherwise, it may pass NULL.
52141**
52142** If a pointer to a MemPage object is passed as the second argument,
52143** its reference count is not altered by this function.
52144*/
52145static int freePage2(BtShared *pBt, MemPage *pMemPage, Pgno iPage){
52146  MemPage *pTrunk = 0;                /* Free-list trunk page */
52147  Pgno iTrunk = 0;                    /* Page number of free-list trunk page */
52148  MemPage *pPage1 = pBt->pPage1;      /* Local reference to page 1 */
52149  MemPage *pPage;                     /* Page being freed. May be NULL. */
52150  int rc;                             /* Return Code */
52151  int nFree;                          /* Initial number of pages on free-list */
52152
52153  assert( sqlite3_mutex_held(pBt->mutex) );
52154  assert( iPage>1 );
52155  assert( !pMemPage || pMemPage->pgno==iPage );
52156
52157  if( pMemPage ){
52158    pPage = pMemPage;
52159    sqlite3PagerRef(pPage->pDbPage);
52160  }else{
52161    pPage = btreePageLookup(pBt, iPage);
52162  }
52163
52164  /* Increment the free page count on pPage1 */
52165  rc = sqlite3PagerWrite(pPage1->pDbPage);
52166  if( rc ) goto freepage_out;
52167  nFree = get4byte(&pPage1->aData[36]);
52168  put4byte(&pPage1->aData[36], nFree+1);
52169
52170  if( pBt->secureDelete ){
52171    /* If the secure_delete option is enabled, then
52172    ** always fully overwrite deleted information with zeros.
52173    */
52174    if( (!pPage && ((rc = btreeGetPage(pBt, iPage, &pPage, 0))!=0) )
52175     ||            ((rc = sqlite3PagerWrite(pPage->pDbPage))!=0)
52176    ){
52177      goto freepage_out;
52178    }
52179    memset(pPage->aData, 0, pPage->pBt->pageSize);
52180  }
52181
52182  /* If the database supports auto-vacuum, write an entry in the pointer-map
52183  ** to indicate that the page is free.
52184  */
52185  if( ISAUTOVACUUM ){
52186    ptrmapPut(pBt, iPage, PTRMAP_FREEPAGE, 0, &rc);
52187    if( rc ) goto freepage_out;
52188  }
52189
52190  /* Now manipulate the actual database free-list structure. There are two
52191  ** possibilities. If the free-list is currently empty, or if the first
52192  ** trunk page in the free-list is full, then this page will become a
52193  ** new free-list trunk page. Otherwise, it will become a leaf of the
52194  ** first trunk page in the current free-list. This block tests if it
52195  ** is possible to add the page as a new free-list leaf.
52196  */
52197  if( nFree!=0 ){
52198    u32 nLeaf;                /* Initial number of leaf cells on trunk page */
52199
52200    iTrunk = get4byte(&pPage1->aData[32]);
52201    rc = btreeGetPage(pBt, iTrunk, &pTrunk, 0);
52202    if( rc!=SQLITE_OK ){
52203      goto freepage_out;
52204    }
52205
52206    nLeaf = get4byte(&pTrunk->aData[4]);
52207    assert( pBt->usableSize>32 );
52208    if( nLeaf > (u32)pBt->usableSize/4 - 2 ){
52209      rc = SQLITE_CORRUPT_BKPT;
52210      goto freepage_out;
52211    }
52212    if( nLeaf < (u32)pBt->usableSize/4 - 8 ){
52213      /* In this case there is room on the trunk page to insert the page
52214      ** being freed as a new leaf.
52215      **
52216      ** Note that the trunk page is not really full until it contains
52217      ** usableSize/4 - 2 entries, not usableSize/4 - 8 entries as we have
52218      ** coded.  But due to a coding error in versions of SQLite prior to
52219      ** 3.6.0, databases with freelist trunk pages holding more than
52220      ** usableSize/4 - 8 entries will be reported as corrupt.  In order
52221      ** to maintain backwards compatibility with older versions of SQLite,
52222      ** we will continue to restrict the number of entries to usableSize/4 - 8
52223      ** for now.  At some point in the future (once everyone has upgraded
52224      ** to 3.6.0 or later) we should consider fixing the conditional above
52225      ** to read "usableSize/4-2" instead of "usableSize/4-8".
52226      */
52227      rc = sqlite3PagerWrite(pTrunk->pDbPage);
52228      if( rc==SQLITE_OK ){
52229        put4byte(&pTrunk->aData[4], nLeaf+1);
52230        put4byte(&pTrunk->aData[8+nLeaf*4], iPage);
52231        if( pPage && !pBt->secureDelete ){
52232          sqlite3PagerDontWrite(pPage->pDbPage);
52233        }
52234        rc = btreeSetHasContent(pBt, iPage);
52235      }
52236      TRACE(("FREE-PAGE: %d leaf on trunk page %d\n",pPage->pgno,pTrunk->pgno));
52237      goto freepage_out;
52238    }
52239  }
52240
52241  /* If control flows to this point, then it was not possible to add the
52242  ** the page being freed as a leaf page of the first trunk in the free-list.
52243  ** Possibly because the free-list is empty, or possibly because the
52244  ** first trunk in the free-list is full. Either way, the page being freed
52245  ** will become the new first trunk page in the free-list.
52246  */
52247  if( pPage==0 && SQLITE_OK!=(rc = btreeGetPage(pBt, iPage, &pPage, 0)) ){
52248    goto freepage_out;
52249  }
52250  rc = sqlite3PagerWrite(pPage->pDbPage);
52251  if( rc!=SQLITE_OK ){
52252    goto freepage_out;
52253  }
52254  put4byte(pPage->aData, iTrunk);
52255  put4byte(&pPage->aData[4], 0);
52256  put4byte(&pPage1->aData[32], iPage);
52257  TRACE(("FREE-PAGE: %d new trunk page replacing %d\n", pPage->pgno, iTrunk));
52258
52259freepage_out:
52260  if( pPage ){
52261    pPage->isInit = 0;
52262  }
52263  releasePage(pPage);
52264  releasePage(pTrunk);
52265  return rc;
52266}
52267static void freePage(MemPage *pPage, int *pRC){
52268  if( (*pRC)==SQLITE_OK ){
52269    *pRC = freePage2(pPage->pBt, pPage, pPage->pgno);
52270  }
52271}
52272
52273/*
52274** Free any overflow pages associated with the given Cell.
52275*/
52276static int clearCell(MemPage *pPage, unsigned char *pCell){
52277  BtShared *pBt = pPage->pBt;
52278  CellInfo info;
52279  Pgno ovflPgno;
52280  int rc;
52281  int nOvfl;
52282  u32 ovflPageSize;
52283
52284  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
52285  btreeParseCellPtr(pPage, pCell, &info);
52286  if( info.iOverflow==0 ){
52287    return SQLITE_OK;  /* No overflow pages. Return without doing anything */
52288  }
52289  ovflPgno = get4byte(&pCell[info.iOverflow]);
52290  assert( pBt->usableSize > 4 );
52291  ovflPageSize = pBt->usableSize - 4;
52292  nOvfl = (info.nPayload - info.nLocal + ovflPageSize - 1)/ovflPageSize;
52293  assert( ovflPgno==0 || nOvfl>0 );
52294  while( nOvfl-- ){
52295    Pgno iNext = 0;
52296    MemPage *pOvfl = 0;
52297    if( ovflPgno<2 || ovflPgno>btreePagecount(pBt) ){
52298      /* 0 is not a legal page number and page 1 cannot be an
52299      ** overflow page. Therefore if ovflPgno<2 or past the end of the
52300      ** file the database must be corrupt. */
52301      return SQLITE_CORRUPT_BKPT;
52302    }
52303    if( nOvfl ){
52304      rc = getOverflowPage(pBt, ovflPgno, &pOvfl, &iNext);
52305      if( rc ) return rc;
52306    }
52307
52308    if( ( pOvfl || ((pOvfl = btreePageLookup(pBt, ovflPgno))!=0) )
52309     && sqlite3PagerPageRefcount(pOvfl->pDbPage)!=1
52310    ){
52311      /* There is no reason any cursor should have an outstanding reference
52312      ** to an overflow page belonging to a cell that is being deleted/updated.
52313      ** So if there exists more than one reference to this page, then it
52314      ** must not really be an overflow page and the database must be corrupt.
52315      ** It is helpful to detect this before calling freePage2(), as
52316      ** freePage2() may zero the page contents if secure-delete mode is
52317      ** enabled. If this 'overflow' page happens to be a page that the
52318      ** caller is iterating through or using in some other way, this
52319      ** can be problematic.
52320      */
52321      rc = SQLITE_CORRUPT_BKPT;
52322    }else{
52323      rc = freePage2(pBt, pOvfl, ovflPgno);
52324    }
52325
52326    if( pOvfl ){
52327      sqlite3PagerUnref(pOvfl->pDbPage);
52328    }
52329    if( rc ) return rc;
52330    ovflPgno = iNext;
52331  }
52332  return SQLITE_OK;
52333}
52334
52335/*
52336** Create the byte sequence used to represent a cell on page pPage
52337** and write that byte sequence into pCell[].  Overflow pages are
52338** allocated and filled in as necessary.  The calling procedure
52339** is responsible for making sure sufficient space has been allocated
52340** for pCell[].
52341**
52342** Note that pCell does not necessary need to point to the pPage->aData
52343** area.  pCell might point to some temporary storage.  The cell will
52344** be constructed in this temporary area then copied into pPage->aData
52345** later.
52346*/
52347static int fillInCell(
52348  MemPage *pPage,                /* The page that contains the cell */
52349  unsigned char *pCell,          /* Complete text of the cell */
52350  const void *pKey, i64 nKey,    /* The key */
52351  const void *pData,int nData,   /* The data */
52352  int nZero,                     /* Extra zero bytes to append to pData */
52353  int *pnSize                    /* Write cell size here */
52354){
52355  int nPayload;
52356  const u8 *pSrc;
52357  int nSrc, n, rc;
52358  int spaceLeft;
52359  MemPage *pOvfl = 0;
52360  MemPage *pToRelease = 0;
52361  unsigned char *pPrior;
52362  unsigned char *pPayload;
52363  BtShared *pBt = pPage->pBt;
52364  Pgno pgnoOvfl = 0;
52365  int nHeader;
52366  CellInfo info;
52367
52368  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
52369
52370  /* pPage is not necessarily writeable since pCell might be auxiliary
52371  ** buffer space that is separate from the pPage buffer area */
52372  assert( pCell<pPage->aData || pCell>=&pPage->aData[pBt->pageSize]
52373            || sqlite3PagerIswriteable(pPage->pDbPage) );
52374
52375  /* Fill in the header. */
52376  nHeader = 0;
52377  if( !pPage->leaf ){
52378    nHeader += 4;
52379  }
52380  if( pPage->hasData ){
52381    nHeader += putVarint(&pCell[nHeader], nData+nZero);
52382  }else{
52383    nData = nZero = 0;
52384  }
52385  nHeader += putVarint(&pCell[nHeader], *(u64*)&nKey);
52386  btreeParseCellPtr(pPage, pCell, &info);
52387  assert( info.nHeader==nHeader );
52388  assert( info.nKey==nKey );
52389  assert( info.nData==(u32)(nData+nZero) );
52390
52391  /* Fill in the payload */
52392  nPayload = nData + nZero;
52393  if( pPage->intKey ){
52394    pSrc = pData;
52395    nSrc = nData;
52396    nData = 0;
52397  }else{
52398    if( NEVER(nKey>0x7fffffff || pKey==0) ){
52399      return SQLITE_CORRUPT_BKPT;
52400    }
52401    nPayload += (int)nKey;
52402    pSrc = pKey;
52403    nSrc = (int)nKey;
52404  }
52405  *pnSize = info.nSize;
52406  spaceLeft = info.nLocal;
52407  pPayload = &pCell[nHeader];
52408  pPrior = &pCell[info.iOverflow];
52409
52410  while( nPayload>0 ){
52411    if( spaceLeft==0 ){
52412#ifndef SQLITE_OMIT_AUTOVACUUM
52413      Pgno pgnoPtrmap = pgnoOvfl; /* Overflow page pointer-map entry page */
52414      if( pBt->autoVacuum ){
52415        do{
52416          pgnoOvfl++;
52417        } while(
52418          PTRMAP_ISPAGE(pBt, pgnoOvfl) || pgnoOvfl==PENDING_BYTE_PAGE(pBt)
52419        );
52420      }
52421#endif
52422      rc = allocateBtreePage(pBt, &pOvfl, &pgnoOvfl, pgnoOvfl, 0);
52423#ifndef SQLITE_OMIT_AUTOVACUUM
52424      /* If the database supports auto-vacuum, and the second or subsequent
52425      ** overflow page is being allocated, add an entry to the pointer-map
52426      ** for that page now.
52427      **
52428      ** If this is the first overflow page, then write a partial entry
52429      ** to the pointer-map. If we write nothing to this pointer-map slot,
52430      ** then the optimistic overflow chain processing in clearCell()
52431      ** may misinterpret the uninitialised values and delete the
52432      ** wrong pages from the database.
52433      */
52434      if( pBt->autoVacuum && rc==SQLITE_OK ){
52435        u8 eType = (pgnoPtrmap?PTRMAP_OVERFLOW2:PTRMAP_OVERFLOW1);
52436        ptrmapPut(pBt, pgnoOvfl, eType, pgnoPtrmap, &rc);
52437        if( rc ){
52438          releasePage(pOvfl);
52439        }
52440      }
52441#endif
52442      if( rc ){
52443        releasePage(pToRelease);
52444        return rc;
52445      }
52446
52447      /* If pToRelease is not zero than pPrior points into the data area
52448      ** of pToRelease.  Make sure pToRelease is still writeable. */
52449      assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
52450
52451      /* If pPrior is part of the data area of pPage, then make sure pPage
52452      ** is still writeable */
52453      assert( pPrior<pPage->aData || pPrior>=&pPage->aData[pBt->pageSize]
52454            || sqlite3PagerIswriteable(pPage->pDbPage) );
52455
52456      put4byte(pPrior, pgnoOvfl);
52457      releasePage(pToRelease);
52458      pToRelease = pOvfl;
52459      pPrior = pOvfl->aData;
52460      put4byte(pPrior, 0);
52461      pPayload = &pOvfl->aData[4];
52462      spaceLeft = pBt->usableSize - 4;
52463    }
52464    n = nPayload;
52465    if( n>spaceLeft ) n = spaceLeft;
52466
52467    /* If pToRelease is not zero than pPayload points into the data area
52468    ** of pToRelease.  Make sure pToRelease is still writeable. */
52469    assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
52470
52471    /* If pPayload is part of the data area of pPage, then make sure pPage
52472    ** is still writeable */
52473    assert( pPayload<pPage->aData || pPayload>=&pPage->aData[pBt->pageSize]
52474            || sqlite3PagerIswriteable(pPage->pDbPage) );
52475
52476    if( nSrc>0 ){
52477      if( n>nSrc ) n = nSrc;
52478      assert( pSrc );
52479      memcpy(pPayload, pSrc, n);
52480    }else{
52481      memset(pPayload, 0, n);
52482    }
52483    nPayload -= n;
52484    pPayload += n;
52485    pSrc += n;
52486    nSrc -= n;
52487    spaceLeft -= n;
52488    if( nSrc==0 ){
52489      nSrc = nData;
52490      pSrc = pData;
52491    }
52492  }
52493  releasePage(pToRelease);
52494  return SQLITE_OK;
52495}
52496
52497/*
52498** Remove the i-th cell from pPage.  This routine effects pPage only.
52499** The cell content is not freed or deallocated.  It is assumed that
52500** the cell content has been copied someplace else.  This routine just
52501** removes the reference to the cell from pPage.
52502**
52503** "sz" must be the number of bytes in the cell.
52504*/
52505static void dropCell(MemPage *pPage, int idx, int sz, int *pRC){
52506  int i;          /* Loop counter */
52507  u32 pc;         /* Offset to cell content of cell being deleted */
52508  u8 *data;       /* pPage->aData */
52509  u8 *ptr;        /* Used to move bytes around within data[] */
52510  int rc;         /* The return code */
52511  int hdr;        /* Beginning of the header.  0 most pages.  100 page 1 */
52512
52513  if( *pRC ) return;
52514
52515  assert( idx>=0 && idx<pPage->nCell );
52516  assert( sz==cellSize(pPage, idx) );
52517  assert( sqlite3PagerIswriteable(pPage->pDbPage) );
52518  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
52519  data = pPage->aData;
52520  ptr = &data[pPage->cellOffset + 2*idx];
52521  pc = get2byte(ptr);
52522  hdr = pPage->hdrOffset;
52523  testcase( pc==get2byte(&data[hdr+5]) );
52524  testcase( pc+sz==pPage->pBt->usableSize );
52525  if( pc < (u32)get2byte(&data[hdr+5]) || pc+sz > pPage->pBt->usableSize ){
52526    *pRC = SQLITE_CORRUPT_BKPT;
52527    return;
52528  }
52529  rc = freeSpace(pPage, pc, sz);
52530  if( rc ){
52531    *pRC = rc;
52532    return;
52533  }
52534  for(i=idx+1; i<pPage->nCell; i++, ptr+=2){
52535    ptr[0] = ptr[2];
52536    ptr[1] = ptr[3];
52537  }
52538  pPage->nCell--;
52539  put2byte(&data[hdr+3], pPage->nCell);
52540  pPage->nFree += 2;
52541}
52542
52543/*
52544** Insert a new cell on pPage at cell index "i".  pCell points to the
52545** content of the cell.
52546**
52547** If the cell content will fit on the page, then put it there.  If it
52548** will not fit, then make a copy of the cell content into pTemp if
52549** pTemp is not null.  Regardless of pTemp, allocate a new entry
52550** in pPage->aOvfl[] and make it point to the cell content (either
52551** in pTemp or the original pCell) and also record its index.
52552** Allocating a new entry in pPage->aCell[] implies that
52553** pPage->nOverflow is incremented.
52554**
52555** If nSkip is non-zero, then do not copy the first nSkip bytes of the
52556** cell. The caller will overwrite them after this function returns. If
52557** nSkip is non-zero, then pCell may not point to an invalid memory location
52558** (but pCell+nSkip is always valid).
52559*/
52560static void insertCell(
52561  MemPage *pPage,   /* Page into which we are copying */
52562  int i,            /* New cell becomes the i-th cell of the page */
52563  u8 *pCell,        /* Content of the new cell */
52564  int sz,           /* Bytes of content in pCell */
52565  u8 *pTemp,        /* Temp storage space for pCell, if needed */
52566  Pgno iChild,      /* If non-zero, replace first 4 bytes with this value */
52567  int *pRC          /* Read and write return code from here */
52568){
52569  int idx = 0;      /* Where to write new cell content in data[] */
52570  int j;            /* Loop counter */
52571  int end;          /* First byte past the last cell pointer in data[] */
52572  int ins;          /* Index in data[] where new cell pointer is inserted */
52573  int cellOffset;   /* Address of first cell pointer in data[] */
52574  u8 *data;         /* The content of the whole page */
52575  u8 *ptr;          /* Used for moving information around in data[] */
52576
52577  int nSkip = (iChild ? 4 : 0);
52578
52579  if( *pRC ) return;
52580
52581  assert( i>=0 && i<=pPage->nCell+pPage->nOverflow );
52582  assert( pPage->nCell<=MX_CELL(pPage->pBt) && MX_CELL(pPage->pBt)<=10921 );
52583  assert( pPage->nOverflow<=ArraySize(pPage->aOvfl) );
52584  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
52585  /* The cell should normally be sized correctly.  However, when moving a
52586  ** malformed cell from a leaf page to an interior page, if the cell size
52587  ** wanted to be less than 4 but got rounded up to 4 on the leaf, then size
52588  ** might be less than 8 (leaf-size + pointer) on the interior node.  Hence
52589  ** the term after the || in the following assert(). */
52590  assert( sz==cellSizePtr(pPage, pCell) || (sz==8 && iChild>0) );
52591  if( pPage->nOverflow || sz+2>pPage->nFree ){
52592    if( pTemp ){
52593      memcpy(pTemp+nSkip, pCell+nSkip, sz-nSkip);
52594      pCell = pTemp;
52595    }
52596    if( iChild ){
52597      put4byte(pCell, iChild);
52598    }
52599    j = pPage->nOverflow++;
52600    assert( j<(int)(sizeof(pPage->aOvfl)/sizeof(pPage->aOvfl[0])) );
52601    pPage->aOvfl[j].pCell = pCell;
52602    pPage->aOvfl[j].idx = (u16)i;
52603  }else{
52604    int rc = sqlite3PagerWrite(pPage->pDbPage);
52605    if( rc!=SQLITE_OK ){
52606      *pRC = rc;
52607      return;
52608    }
52609    assert( sqlite3PagerIswriteable(pPage->pDbPage) );
52610    data = pPage->aData;
52611    cellOffset = pPage->cellOffset;
52612    end = cellOffset + 2*pPage->nCell;
52613    ins = cellOffset + 2*i;
52614    rc = allocateSpace(pPage, sz, &idx);
52615    if( rc ){ *pRC = rc; return; }
52616    /* The allocateSpace() routine guarantees the following two properties
52617    ** if it returns success */
52618    assert( idx >= end+2 );
52619    assert( idx+sz <= (int)pPage->pBt->usableSize );
52620    pPage->nCell++;
52621    pPage->nFree -= (u16)(2 + sz);
52622    memcpy(&data[idx+nSkip], pCell+nSkip, sz-nSkip);
52623    if( iChild ){
52624      put4byte(&data[idx], iChild);
52625    }
52626    for(j=end, ptr=&data[j]; j>ins; j-=2, ptr-=2){
52627      ptr[0] = ptr[-2];
52628      ptr[1] = ptr[-1];
52629    }
52630    put2byte(&data[ins], idx);
52631    put2byte(&data[pPage->hdrOffset+3], pPage->nCell);
52632#ifndef SQLITE_OMIT_AUTOVACUUM
52633    if( pPage->pBt->autoVacuum ){
52634      /* The cell may contain a pointer to an overflow page. If so, write
52635      ** the entry for the overflow page into the pointer map.
52636      */
52637      ptrmapPutOvflPtr(pPage, pCell, pRC);
52638    }
52639#endif
52640  }
52641}
52642
52643/*
52644** Add a list of cells to a page.  The page should be initially empty.
52645** The cells are guaranteed to fit on the page.
52646*/
52647static void assemblePage(
52648  MemPage *pPage,   /* The page to be assemblied */
52649  int nCell,        /* The number of cells to add to this page */
52650  u8 **apCell,      /* Pointers to cell bodies */
52651  u16 *aSize        /* Sizes of the cells */
52652){
52653  int i;            /* Loop counter */
52654  u8 *pCellptr;     /* Address of next cell pointer */
52655  int cellbody;     /* Address of next cell body */
52656  u8 * const data = pPage->aData;             /* Pointer to data for pPage */
52657  const int hdr = pPage->hdrOffset;           /* Offset of header on pPage */
52658  const int nUsable = pPage->pBt->usableSize; /* Usable size of page */
52659
52660  assert( pPage->nOverflow==0 );
52661  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
52662  assert( nCell>=0 && nCell<=(int)MX_CELL(pPage->pBt)
52663            && (int)MX_CELL(pPage->pBt)<=10921);
52664  assert( sqlite3PagerIswriteable(pPage->pDbPage) );
52665
52666  /* Check that the page has just been zeroed by zeroPage() */
52667  assert( pPage->nCell==0 );
52668  assert( get2byteNotZero(&data[hdr+5])==nUsable );
52669
52670  pCellptr = &data[pPage->cellOffset + nCell*2];
52671  cellbody = nUsable;
52672  for(i=nCell-1; i>=0; i--){
52673    pCellptr -= 2;
52674    cellbody -= aSize[i];
52675    put2byte(pCellptr, cellbody);
52676    memcpy(&data[cellbody], apCell[i], aSize[i]);
52677  }
52678  put2byte(&data[hdr+3], nCell);
52679  put2byte(&data[hdr+5], cellbody);
52680  pPage->nFree -= (nCell*2 + nUsable - cellbody);
52681  pPage->nCell = (u16)nCell;
52682}
52683
52684/*
52685** The following parameters determine how many adjacent pages get involved
52686** in a balancing operation.  NN is the number of neighbors on either side
52687** of the page that participate in the balancing operation.  NB is the
52688** total number of pages that participate, including the target page and
52689** NN neighbors on either side.
52690**
52691** The minimum value of NN is 1 (of course).  Increasing NN above 1
52692** (to 2 or 3) gives a modest improvement in SELECT and DELETE performance
52693** in exchange for a larger degradation in INSERT and UPDATE performance.
52694** The value of NN appears to give the best results overall.
52695*/
52696#define NN 1             /* Number of neighbors on either side of pPage */
52697#define NB (NN*2+1)      /* Total pages involved in the balance */
52698
52699
52700#ifndef SQLITE_OMIT_QUICKBALANCE
52701/*
52702** This version of balance() handles the common special case where
52703** a new entry is being inserted on the extreme right-end of the
52704** tree, in other words, when the new entry will become the largest
52705** entry in the tree.
52706**
52707** Instead of trying to balance the 3 right-most leaf pages, just add
52708** a new page to the right-hand side and put the one new entry in
52709** that page.  This leaves the right side of the tree somewhat
52710** unbalanced.  But odds are that we will be inserting new entries
52711** at the end soon afterwards so the nearly empty page will quickly
52712** fill up.  On average.
52713**
52714** pPage is the leaf page which is the right-most page in the tree.
52715** pParent is its parent.  pPage must have a single overflow entry
52716** which is also the right-most entry on the page.
52717**
52718** The pSpace buffer is used to store a temporary copy of the divider
52719** cell that will be inserted into pParent. Such a cell consists of a 4
52720** byte page number followed by a variable length integer. In other
52721** words, at most 13 bytes. Hence the pSpace buffer must be at
52722** least 13 bytes in size.
52723*/
52724static int balance_quick(MemPage *pParent, MemPage *pPage, u8 *pSpace){
52725  BtShared *const pBt = pPage->pBt;    /* B-Tree Database */
52726  MemPage *pNew;                       /* Newly allocated page */
52727  int rc;                              /* Return Code */
52728  Pgno pgnoNew;                        /* Page number of pNew */
52729
52730  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
52731  assert( sqlite3PagerIswriteable(pParent->pDbPage) );
52732  assert( pPage->nOverflow==1 );
52733
52734  /* This error condition is now caught prior to reaching this function */
52735  if( pPage->nCell<=0 ) return SQLITE_CORRUPT_BKPT;
52736
52737  /* Allocate a new page. This page will become the right-sibling of
52738  ** pPage. Make the parent page writable, so that the new divider cell
52739  ** may be inserted. If both these operations are successful, proceed.
52740  */
52741  rc = allocateBtreePage(pBt, &pNew, &pgnoNew, 0, 0);
52742
52743  if( rc==SQLITE_OK ){
52744
52745    u8 *pOut = &pSpace[4];
52746    u8 *pCell = pPage->aOvfl[0].pCell;
52747    u16 szCell = cellSizePtr(pPage, pCell);
52748    u8 *pStop;
52749
52750    assert( sqlite3PagerIswriteable(pNew->pDbPage) );
52751    assert( pPage->aData[0]==(PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF) );
52752    zeroPage(pNew, PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF);
52753    assemblePage(pNew, 1, &pCell, &szCell);
52754
52755    /* If this is an auto-vacuum database, update the pointer map
52756    ** with entries for the new page, and any pointer from the
52757    ** cell on the page to an overflow page. If either of these
52758    ** operations fails, the return code is set, but the contents
52759    ** of the parent page are still manipulated by thh code below.
52760    ** That is Ok, at this point the parent page is guaranteed to
52761    ** be marked as dirty. Returning an error code will cause a
52762    ** rollback, undoing any changes made to the parent page.
52763    */
52764    if( ISAUTOVACUUM ){
52765      ptrmapPut(pBt, pgnoNew, PTRMAP_BTREE, pParent->pgno, &rc);
52766      if( szCell>pNew->minLocal ){
52767        ptrmapPutOvflPtr(pNew, pCell, &rc);
52768      }
52769    }
52770
52771    /* Create a divider cell to insert into pParent. The divider cell
52772    ** consists of a 4-byte page number (the page number of pPage) and
52773    ** a variable length key value (which must be the same value as the
52774    ** largest key on pPage).
52775    **
52776    ** To find the largest key value on pPage, first find the right-most
52777    ** cell on pPage. The first two fields of this cell are the
52778    ** record-length (a variable length integer at most 32-bits in size)
52779    ** and the key value (a variable length integer, may have any value).
52780    ** The first of the while(...) loops below skips over the record-length
52781    ** field. The second while(...) loop copies the key value from the
52782    ** cell on pPage into the pSpace buffer.
52783    */
52784    pCell = findCell(pPage, pPage->nCell-1);
52785    pStop = &pCell[9];
52786    while( (*(pCell++)&0x80) && pCell<pStop );
52787    pStop = &pCell[9];
52788    while( ((*(pOut++) = *(pCell++))&0x80) && pCell<pStop );
52789
52790    /* Insert the new divider cell into pParent. */
52791    insertCell(pParent, pParent->nCell, pSpace, (int)(pOut-pSpace),
52792               0, pPage->pgno, &rc);
52793
52794    /* Set the right-child pointer of pParent to point to the new page. */
52795    put4byte(&pParent->aData[pParent->hdrOffset+8], pgnoNew);
52796
52797    /* Release the reference to the new page. */
52798    releasePage(pNew);
52799  }
52800
52801  return rc;
52802}
52803#endif /* SQLITE_OMIT_QUICKBALANCE */
52804
52805#if 0
52806/*
52807** This function does not contribute anything to the operation of SQLite.
52808** it is sometimes activated temporarily while debugging code responsible
52809** for setting pointer-map entries.
52810*/
52811static int ptrmapCheckPages(MemPage **apPage, int nPage){
52812  int i, j;
52813  for(i=0; i<nPage; i++){
52814    Pgno n;
52815    u8 e;
52816    MemPage *pPage = apPage[i];
52817    BtShared *pBt = pPage->pBt;
52818    assert( pPage->isInit );
52819
52820    for(j=0; j<pPage->nCell; j++){
52821      CellInfo info;
52822      u8 *z;
52823
52824      z = findCell(pPage, j);
52825      btreeParseCellPtr(pPage, z, &info);
52826      if( info.iOverflow ){
52827        Pgno ovfl = get4byte(&z[info.iOverflow]);
52828        ptrmapGet(pBt, ovfl, &e, &n);
52829        assert( n==pPage->pgno && e==PTRMAP_OVERFLOW1 );
52830      }
52831      if( !pPage->leaf ){
52832        Pgno child = get4byte(z);
52833        ptrmapGet(pBt, child, &e, &n);
52834        assert( n==pPage->pgno && e==PTRMAP_BTREE );
52835      }
52836    }
52837    if( !pPage->leaf ){
52838      Pgno child = get4byte(&pPage->aData[pPage->hdrOffset+8]);
52839      ptrmapGet(pBt, child, &e, &n);
52840      assert( n==pPage->pgno && e==PTRMAP_BTREE );
52841    }
52842  }
52843  return 1;
52844}
52845#endif
52846
52847/*
52848** This function is used to copy the contents of the b-tree node stored
52849** on page pFrom to page pTo. If page pFrom was not a leaf page, then
52850** the pointer-map entries for each child page are updated so that the
52851** parent page stored in the pointer map is page pTo. If pFrom contained
52852** any cells with overflow page pointers, then the corresponding pointer
52853** map entries are also updated so that the parent page is page pTo.
52854**
52855** If pFrom is currently carrying any overflow cells (entries in the
52856** MemPage.aOvfl[] array), they are not copied to pTo.
52857**
52858** Before returning, page pTo is reinitialized using btreeInitPage().
52859**
52860** The performance of this function is not critical. It is only used by
52861** the balance_shallower() and balance_deeper() procedures, neither of
52862** which are called often under normal circumstances.
52863*/
52864static void copyNodeContent(MemPage *pFrom, MemPage *pTo, int *pRC){
52865  if( (*pRC)==SQLITE_OK ){
52866    BtShared * const pBt = pFrom->pBt;
52867    u8 * const aFrom = pFrom->aData;
52868    u8 * const aTo = pTo->aData;
52869    int const iFromHdr = pFrom->hdrOffset;
52870    int const iToHdr = ((pTo->pgno==1) ? 100 : 0);
52871    int rc;
52872    int iData;
52873
52874
52875    assert( pFrom->isInit );
52876    assert( pFrom->nFree>=iToHdr );
52877    assert( get2byte(&aFrom[iFromHdr+5]) <= (int)pBt->usableSize );
52878
52879    /* Copy the b-tree node content from page pFrom to page pTo. */
52880    iData = get2byte(&aFrom[iFromHdr+5]);
52881    memcpy(&aTo[iData], &aFrom[iData], pBt->usableSize-iData);
52882    memcpy(&aTo[iToHdr], &aFrom[iFromHdr], pFrom->cellOffset + 2*pFrom->nCell);
52883
52884    /* Reinitialize page pTo so that the contents of the MemPage structure
52885    ** match the new data. The initialization of pTo can actually fail under
52886    ** fairly obscure circumstances, even though it is a copy of initialized
52887    ** page pFrom.
52888    */
52889    pTo->isInit = 0;
52890    rc = btreeInitPage(pTo);
52891    if( rc!=SQLITE_OK ){
52892      *pRC = rc;
52893      return;
52894    }
52895
52896    /* If this is an auto-vacuum database, update the pointer-map entries
52897    ** for any b-tree or overflow pages that pTo now contains the pointers to.
52898    */
52899    if( ISAUTOVACUUM ){
52900      *pRC = setChildPtrmaps(pTo);
52901    }
52902  }
52903}
52904
52905/*
52906** This routine redistributes cells on the iParentIdx'th child of pParent
52907** (hereafter "the page") and up to 2 siblings so that all pages have about the
52908** same amount of free space. Usually a single sibling on either side of the
52909** page are used in the balancing, though both siblings might come from one
52910** side if the page is the first or last child of its parent. If the page
52911** has fewer than 2 siblings (something which can only happen if the page
52912** is a root page or a child of a root page) then all available siblings
52913** participate in the balancing.
52914**
52915** The number of siblings of the page might be increased or decreased by
52916** one or two in an effort to keep pages nearly full but not over full.
52917**
52918** Note that when this routine is called, some of the cells on the page
52919** might not actually be stored in MemPage.aData[]. This can happen
52920** if the page is overfull. This routine ensures that all cells allocated
52921** to the page and its siblings fit into MemPage.aData[] before returning.
52922**
52923** In the course of balancing the page and its siblings, cells may be
52924** inserted into or removed from the parent page (pParent). Doing so
52925** may cause the parent page to become overfull or underfull. If this
52926** happens, it is the responsibility of the caller to invoke the correct
52927** balancing routine to fix this problem (see the balance() routine).
52928**
52929** If this routine fails for any reason, it might leave the database
52930** in a corrupted state. So if this routine fails, the database should
52931** be rolled back.
52932**
52933** The third argument to this function, aOvflSpace, is a pointer to a
52934** buffer big enough to hold one page. If while inserting cells into the parent
52935** page (pParent) the parent page becomes overfull, this buffer is
52936** used to store the parent's overflow cells. Because this function inserts
52937** a maximum of four divider cells into the parent page, and the maximum
52938** size of a cell stored within an internal node is always less than 1/4
52939** of the page-size, the aOvflSpace[] buffer is guaranteed to be large
52940** enough for all overflow cells.
52941**
52942** If aOvflSpace is set to a null pointer, this function returns
52943** SQLITE_NOMEM.
52944*/
52945static int balance_nonroot(
52946  MemPage *pParent,               /* Parent page of siblings being balanced */
52947  int iParentIdx,                 /* Index of "the page" in pParent */
52948  u8 *aOvflSpace,                 /* page-size bytes of space for parent ovfl */
52949  int isRoot                      /* True if pParent is a root-page */
52950){
52951  BtShared *pBt;               /* The whole database */
52952  int nCell = 0;               /* Number of cells in apCell[] */
52953  int nMaxCells = 0;           /* Allocated size of apCell, szCell, aFrom. */
52954  int nNew = 0;                /* Number of pages in apNew[] */
52955  int nOld;                    /* Number of pages in apOld[] */
52956  int i, j, k;                 /* Loop counters */
52957  int nxDiv;                   /* Next divider slot in pParent->aCell[] */
52958  int rc = SQLITE_OK;          /* The return code */
52959  u16 leafCorrection;          /* 4 if pPage is a leaf.  0 if not */
52960  int leafData;                /* True if pPage is a leaf of a LEAFDATA tree */
52961  int usableSpace;             /* Bytes in pPage beyond the header */
52962  int pageFlags;               /* Value of pPage->aData[0] */
52963  int subtotal;                /* Subtotal of bytes in cells on one page */
52964  int iSpace1 = 0;             /* First unused byte of aSpace1[] */
52965  int iOvflSpace = 0;          /* First unused byte of aOvflSpace[] */
52966  int szScratch;               /* Size of scratch memory requested */
52967  MemPage *apOld[NB];          /* pPage and up to two siblings */
52968  MemPage *apCopy[NB];         /* Private copies of apOld[] pages */
52969  MemPage *apNew[NB+2];        /* pPage and up to NB siblings after balancing */
52970  u8 *pRight;                  /* Location in parent of right-sibling pointer */
52971  u8 *apDiv[NB-1];             /* Divider cells in pParent */
52972  int cntNew[NB+2];            /* Index in aCell[] of cell after i-th page */
52973  int szNew[NB+2];             /* Combined size of cells place on i-th page */
52974  u8 **apCell = 0;             /* All cells begin balanced */
52975  u16 *szCell;                 /* Local size of all cells in apCell[] */
52976  u8 *aSpace1;                 /* Space for copies of dividers cells */
52977  Pgno pgno;                   /* Temp var to store a page number in */
52978
52979  pBt = pParent->pBt;
52980  assert( sqlite3_mutex_held(pBt->mutex) );
52981  assert( sqlite3PagerIswriteable(pParent->pDbPage) );
52982
52983#if 0
52984  TRACE(("BALANCE: begin page %d child of %d\n", pPage->pgno, pParent->pgno));
52985#endif
52986
52987  /* At this point pParent may have at most one overflow cell. And if
52988  ** this overflow cell is present, it must be the cell with
52989  ** index iParentIdx. This scenario comes about when this function
52990  ** is called (indirectly) from sqlite3BtreeDelete().
52991  */
52992  assert( pParent->nOverflow==0 || pParent->nOverflow==1 );
52993  assert( pParent->nOverflow==0 || pParent->aOvfl[0].idx==iParentIdx );
52994
52995  if( !aOvflSpace ){
52996    return SQLITE_NOMEM;
52997  }
52998
52999  /* Find the sibling pages to balance. Also locate the cells in pParent
53000  ** that divide the siblings. An attempt is made to find NN siblings on
53001  ** either side of pPage. More siblings are taken from one side, however,
53002  ** if there are fewer than NN siblings on the other side. If pParent
53003  ** has NB or fewer children then all children of pParent are taken.
53004  **
53005  ** This loop also drops the divider cells from the parent page. This
53006  ** way, the remainder of the function does not have to deal with any
53007  ** overflow cells in the parent page, since if any existed they will
53008  ** have already been removed.
53009  */
53010  i = pParent->nOverflow + pParent->nCell;
53011  if( i<2 ){
53012    nxDiv = 0;
53013    nOld = i+1;
53014  }else{
53015    nOld = 3;
53016    if( iParentIdx==0 ){
53017      nxDiv = 0;
53018    }else if( iParentIdx==i ){
53019      nxDiv = i-2;
53020    }else{
53021      nxDiv = iParentIdx-1;
53022    }
53023    i = 2;
53024  }
53025  if( (i+nxDiv-pParent->nOverflow)==pParent->nCell ){
53026    pRight = &pParent->aData[pParent->hdrOffset+8];
53027  }else{
53028    pRight = findCell(pParent, i+nxDiv-pParent->nOverflow);
53029  }
53030  pgno = get4byte(pRight);
53031  while( 1 ){
53032    rc = getAndInitPage(pBt, pgno, &apOld[i]);
53033    if( rc ){
53034      memset(apOld, 0, (i+1)*sizeof(MemPage*));
53035      goto balance_cleanup;
53036    }
53037    nMaxCells += 1+apOld[i]->nCell+apOld[i]->nOverflow;
53038    if( (i--)==0 ) break;
53039
53040    if( i+nxDiv==pParent->aOvfl[0].idx && pParent->nOverflow ){
53041      apDiv[i] = pParent->aOvfl[0].pCell;
53042      pgno = get4byte(apDiv[i]);
53043      szNew[i] = cellSizePtr(pParent, apDiv[i]);
53044      pParent->nOverflow = 0;
53045    }else{
53046      apDiv[i] = findCell(pParent, i+nxDiv-pParent->nOverflow);
53047      pgno = get4byte(apDiv[i]);
53048      szNew[i] = cellSizePtr(pParent, apDiv[i]);
53049
53050      /* Drop the cell from the parent page. apDiv[i] still points to
53051      ** the cell within the parent, even though it has been dropped.
53052      ** This is safe because dropping a cell only overwrites the first
53053      ** four bytes of it, and this function does not need the first
53054      ** four bytes of the divider cell. So the pointer is safe to use
53055      ** later on.
53056      **
53057      ** Unless SQLite is compiled in secure-delete mode. In this case,
53058      ** the dropCell() routine will overwrite the entire cell with zeroes.
53059      ** In this case, temporarily copy the cell into the aOvflSpace[]
53060      ** buffer. It will be copied out again as soon as the aSpace[] buffer
53061      ** is allocated.  */
53062      if( pBt->secureDelete ){
53063        int iOff = SQLITE_PTR_TO_INT(apDiv[i]) - SQLITE_PTR_TO_INT(pParent->aData);
53064        if( (iOff+szNew[i])>(int)pBt->usableSize ){
53065          rc = SQLITE_CORRUPT_BKPT;
53066          memset(apOld, 0, (i+1)*sizeof(MemPage*));
53067          goto balance_cleanup;
53068        }else{
53069          memcpy(&aOvflSpace[iOff], apDiv[i], szNew[i]);
53070          apDiv[i] = &aOvflSpace[apDiv[i]-pParent->aData];
53071        }
53072      }
53073      dropCell(pParent, i+nxDiv-pParent->nOverflow, szNew[i], &rc);
53074    }
53075  }
53076
53077  /* Make nMaxCells a multiple of 4 in order to preserve 8-byte
53078  ** alignment */
53079  nMaxCells = (nMaxCells + 3)&~3;
53080
53081  /*
53082  ** Allocate space for memory structures
53083  */
53084  k = pBt->pageSize + ROUND8(sizeof(MemPage));
53085  szScratch =
53086       nMaxCells*sizeof(u8*)                       /* apCell */
53087     + nMaxCells*sizeof(u16)                       /* szCell */
53088     + pBt->pageSize                               /* aSpace1 */
53089     + k*nOld;                                     /* Page copies (apCopy) */
53090  apCell = sqlite3ScratchMalloc( szScratch );
53091  if( apCell==0 ){
53092    rc = SQLITE_NOMEM;
53093    goto balance_cleanup;
53094  }
53095  szCell = (u16*)&apCell[nMaxCells];
53096  aSpace1 = (u8*)&szCell[nMaxCells];
53097  assert( EIGHT_BYTE_ALIGNMENT(aSpace1) );
53098
53099  /*
53100  ** Load pointers to all cells on sibling pages and the divider cells
53101  ** into the local apCell[] array.  Make copies of the divider cells
53102  ** into space obtained from aSpace1[] and remove the the divider Cells
53103  ** from pParent.
53104  **
53105  ** If the siblings are on leaf pages, then the child pointers of the
53106  ** divider cells are stripped from the cells before they are copied
53107  ** into aSpace1[].  In this way, all cells in apCell[] are without
53108  ** child pointers.  If siblings are not leaves, then all cell in
53109  ** apCell[] include child pointers.  Either way, all cells in apCell[]
53110  ** are alike.
53111  **
53112  ** leafCorrection:  4 if pPage is a leaf.  0 if pPage is not a leaf.
53113  **       leafData:  1 if pPage holds key+data and pParent holds only keys.
53114  */
53115  leafCorrection = apOld[0]->leaf*4;
53116  leafData = apOld[0]->hasData;
53117  for(i=0; i<nOld; i++){
53118    int limit;
53119
53120    /* Before doing anything else, take a copy of the i'th original sibling
53121    ** The rest of this function will use data from the copies rather
53122    ** that the original pages since the original pages will be in the
53123    ** process of being overwritten.  */
53124    MemPage *pOld = apCopy[i] = (MemPage*)&aSpace1[pBt->pageSize + k*i];
53125    memcpy(pOld, apOld[i], sizeof(MemPage));
53126    pOld->aData = (void*)&pOld[1];
53127    memcpy(pOld->aData, apOld[i]->aData, pBt->pageSize);
53128
53129    limit = pOld->nCell+pOld->nOverflow;
53130    for(j=0; j<limit; j++){
53131      assert( nCell<nMaxCells );
53132      apCell[nCell] = findOverflowCell(pOld, j);
53133      szCell[nCell] = cellSizePtr(pOld, apCell[nCell]);
53134      nCell++;
53135    }
53136    if( i<nOld-1 && !leafData){
53137      u16 sz = (u16)szNew[i];
53138      u8 *pTemp;
53139      assert( nCell<nMaxCells );
53140      szCell[nCell] = sz;
53141      pTemp = &aSpace1[iSpace1];
53142      iSpace1 += sz;
53143      assert( sz<=pBt->maxLocal+23 );
53144      assert( iSpace1 <= (int)pBt->pageSize );
53145      memcpy(pTemp, apDiv[i], sz);
53146      apCell[nCell] = pTemp+leafCorrection;
53147      assert( leafCorrection==0 || leafCorrection==4 );
53148      szCell[nCell] = szCell[nCell] - leafCorrection;
53149      if( !pOld->leaf ){
53150        assert( leafCorrection==0 );
53151        assert( pOld->hdrOffset==0 );
53152        /* The right pointer of the child page pOld becomes the left
53153        ** pointer of the divider cell */
53154        memcpy(apCell[nCell], &pOld->aData[8], 4);
53155      }else{
53156        assert( leafCorrection==4 );
53157        if( szCell[nCell]<4 ){
53158          /* Do not allow any cells smaller than 4 bytes. */
53159          szCell[nCell] = 4;
53160        }
53161      }
53162      nCell++;
53163    }
53164  }
53165
53166  /*
53167  ** Figure out the number of pages needed to hold all nCell cells.
53168  ** Store this number in "k".  Also compute szNew[] which is the total
53169  ** size of all cells on the i-th page and cntNew[] which is the index
53170  ** in apCell[] of the cell that divides page i from page i+1.
53171  ** cntNew[k] should equal nCell.
53172  **
53173  ** Values computed by this block:
53174  **
53175  **           k: The total number of sibling pages
53176  **    szNew[i]: Spaced used on the i-th sibling page.
53177  **   cntNew[i]: Index in apCell[] and szCell[] for the first cell to
53178  **              the right of the i-th sibling page.
53179  ** usableSpace: Number of bytes of space available on each sibling.
53180  **
53181  */
53182  usableSpace = pBt->usableSize - 12 + leafCorrection;
53183  for(subtotal=k=i=0; i<nCell; i++){
53184    assert( i<nMaxCells );
53185    subtotal += szCell[i] + 2;
53186    if( subtotal > usableSpace ){
53187      szNew[k] = subtotal - szCell[i];
53188      cntNew[k] = i;
53189      if( leafData ){ i--; }
53190      subtotal = 0;
53191      k++;
53192      if( k>NB+1 ){ rc = SQLITE_CORRUPT_BKPT; goto balance_cleanup; }
53193    }
53194  }
53195  szNew[k] = subtotal;
53196  cntNew[k] = nCell;
53197  k++;
53198
53199  /*
53200  ** The packing computed by the previous block is biased toward the siblings
53201  ** on the left side.  The left siblings are always nearly full, while the
53202  ** right-most sibling might be nearly empty.  This block of code attempts
53203  ** to adjust the packing of siblings to get a better balance.
53204  **
53205  ** This adjustment is more than an optimization.  The packing above might
53206  ** be so out of balance as to be illegal.  For example, the right-most
53207  ** sibling might be completely empty.  This adjustment is not optional.
53208  */
53209  for(i=k-1; i>0; i--){
53210    int szRight = szNew[i];  /* Size of sibling on the right */
53211    int szLeft = szNew[i-1]; /* Size of sibling on the left */
53212    int r;              /* Index of right-most cell in left sibling */
53213    int d;              /* Index of first cell to the left of right sibling */
53214
53215    r = cntNew[i-1] - 1;
53216    d = r + 1 - leafData;
53217    assert( d<nMaxCells );
53218    assert( r<nMaxCells );
53219    while( szRight==0 || szRight+szCell[d]+2<=szLeft-(szCell[r]+2) ){
53220      szRight += szCell[d] + 2;
53221      szLeft -= szCell[r] + 2;
53222      cntNew[i-1]--;
53223      r = cntNew[i-1] - 1;
53224      d = r + 1 - leafData;
53225    }
53226    szNew[i] = szRight;
53227    szNew[i-1] = szLeft;
53228  }
53229
53230  /* Either we found one or more cells (cntnew[0])>0) or pPage is
53231  ** a virtual root page.  A virtual root page is when the real root
53232  ** page is page 1 and we are the only child of that page.
53233  */
53234  assert( cntNew[0]>0 || (pParent->pgno==1 && pParent->nCell==0) );
53235
53236  TRACE(("BALANCE: old: %d %d %d  ",
53237    apOld[0]->pgno,
53238    nOld>=2 ? apOld[1]->pgno : 0,
53239    nOld>=3 ? apOld[2]->pgno : 0
53240  ));
53241
53242  /*
53243  ** Allocate k new pages.  Reuse old pages where possible.
53244  */
53245  if( apOld[0]->pgno<=1 ){
53246    rc = SQLITE_CORRUPT_BKPT;
53247    goto balance_cleanup;
53248  }
53249  pageFlags = apOld[0]->aData[0];
53250  for(i=0; i<k; i++){
53251    MemPage *pNew;
53252    if( i<nOld ){
53253      pNew = apNew[i] = apOld[i];
53254      apOld[i] = 0;
53255      rc = sqlite3PagerWrite(pNew->pDbPage);
53256      nNew++;
53257      if( rc ) goto balance_cleanup;
53258    }else{
53259      assert( i>0 );
53260      rc = allocateBtreePage(pBt, &pNew, &pgno, pgno, 0);
53261      if( rc ) goto balance_cleanup;
53262      apNew[i] = pNew;
53263      nNew++;
53264
53265      /* Set the pointer-map entry for the new sibling page. */
53266      if( ISAUTOVACUUM ){
53267        ptrmapPut(pBt, pNew->pgno, PTRMAP_BTREE, pParent->pgno, &rc);
53268        if( rc!=SQLITE_OK ){
53269          goto balance_cleanup;
53270        }
53271      }
53272    }
53273  }
53274
53275  /* Free any old pages that were not reused as new pages.
53276  */
53277  while( i<nOld ){
53278    freePage(apOld[i], &rc);
53279    if( rc ) goto balance_cleanup;
53280    releasePage(apOld[i]);
53281    apOld[i] = 0;
53282    i++;
53283  }
53284
53285  /*
53286  ** Put the new pages in accending order.  This helps to
53287  ** keep entries in the disk file in order so that a scan
53288  ** of the table is a linear scan through the file.  That
53289  ** in turn helps the operating system to deliver pages
53290  ** from the disk more rapidly.
53291  **
53292  ** An O(n^2) insertion sort algorithm is used, but since
53293  ** n is never more than NB (a small constant), that should
53294  ** not be a problem.
53295  **
53296  ** When NB==3, this one optimization makes the database
53297  ** about 25% faster for large insertions and deletions.
53298  */
53299  for(i=0; i<k-1; i++){
53300    int minV = apNew[i]->pgno;
53301    int minI = i;
53302    for(j=i+1; j<k; j++){
53303      if( apNew[j]->pgno<(unsigned)minV ){
53304        minI = j;
53305        minV = apNew[j]->pgno;
53306      }
53307    }
53308    if( minI>i ){
53309      MemPage *pT;
53310      pT = apNew[i];
53311      apNew[i] = apNew[minI];
53312      apNew[minI] = pT;
53313    }
53314  }
53315  TRACE(("new: %d(%d) %d(%d) %d(%d) %d(%d) %d(%d)\n",
53316    apNew[0]->pgno, szNew[0],
53317    nNew>=2 ? apNew[1]->pgno : 0, nNew>=2 ? szNew[1] : 0,
53318    nNew>=3 ? apNew[2]->pgno : 0, nNew>=3 ? szNew[2] : 0,
53319    nNew>=4 ? apNew[3]->pgno : 0, nNew>=4 ? szNew[3] : 0,
53320    nNew>=5 ? apNew[4]->pgno : 0, nNew>=5 ? szNew[4] : 0));
53321
53322  assert( sqlite3PagerIswriteable(pParent->pDbPage) );
53323  put4byte(pRight, apNew[nNew-1]->pgno);
53324
53325  /*
53326  ** Evenly distribute the data in apCell[] across the new pages.
53327  ** Insert divider cells into pParent as necessary.
53328  */
53329  j = 0;
53330  for(i=0; i<nNew; i++){
53331    /* Assemble the new sibling page. */
53332    MemPage *pNew = apNew[i];
53333    assert( j<nMaxCells );
53334    zeroPage(pNew, pageFlags);
53335    assemblePage(pNew, cntNew[i]-j, &apCell[j], &szCell[j]);
53336    assert( pNew->nCell>0 || (nNew==1 && cntNew[0]==0) );
53337    assert( pNew->nOverflow==0 );
53338
53339    j = cntNew[i];
53340
53341    /* If the sibling page assembled above was not the right-most sibling,
53342    ** insert a divider cell into the parent page.
53343    */
53344    assert( i<nNew-1 || j==nCell );
53345    if( j<nCell ){
53346      u8 *pCell;
53347      u8 *pTemp;
53348      int sz;
53349
53350      assert( j<nMaxCells );
53351      pCell = apCell[j];
53352      sz = szCell[j] + leafCorrection;
53353      pTemp = &aOvflSpace[iOvflSpace];
53354      if( !pNew->leaf ){
53355        memcpy(&pNew->aData[8], pCell, 4);
53356      }else if( leafData ){
53357        /* If the tree is a leaf-data tree, and the siblings are leaves,
53358        ** then there is no divider cell in apCell[]. Instead, the divider
53359        ** cell consists of the integer key for the right-most cell of
53360        ** the sibling-page assembled above only.
53361        */
53362        CellInfo info;
53363        j--;
53364        btreeParseCellPtr(pNew, apCell[j], &info);
53365        pCell = pTemp;
53366        sz = 4 + putVarint(&pCell[4], info.nKey);
53367        pTemp = 0;
53368      }else{
53369        pCell -= 4;
53370        /* Obscure case for non-leaf-data trees: If the cell at pCell was
53371        ** previously stored on a leaf node, and its reported size was 4
53372        ** bytes, then it may actually be smaller than this
53373        ** (see btreeParseCellPtr(), 4 bytes is the minimum size of
53374        ** any cell). But it is important to pass the correct size to
53375        ** insertCell(), so reparse the cell now.
53376        **
53377        ** Note that this can never happen in an SQLite data file, as all
53378        ** cells are at least 4 bytes. It only happens in b-trees used
53379        ** to evaluate "IN (SELECT ...)" and similar clauses.
53380        */
53381        if( szCell[j]==4 ){
53382          assert(leafCorrection==4);
53383          sz = cellSizePtr(pParent, pCell);
53384        }
53385      }
53386      iOvflSpace += sz;
53387      assert( sz<=pBt->maxLocal+23 );
53388      assert( iOvflSpace <= (int)pBt->pageSize );
53389      insertCell(pParent, nxDiv, pCell, sz, pTemp, pNew->pgno, &rc);
53390      if( rc!=SQLITE_OK ) goto balance_cleanup;
53391      assert( sqlite3PagerIswriteable(pParent->pDbPage) );
53392
53393      j++;
53394      nxDiv++;
53395    }
53396  }
53397  assert( j==nCell );
53398  assert( nOld>0 );
53399  assert( nNew>0 );
53400  if( (pageFlags & PTF_LEAF)==0 ){
53401    u8 *zChild = &apCopy[nOld-1]->aData[8];
53402    memcpy(&apNew[nNew-1]->aData[8], zChild, 4);
53403  }
53404
53405  if( isRoot && pParent->nCell==0 && pParent->hdrOffset<=apNew[0]->nFree ){
53406    /* The root page of the b-tree now contains no cells. The only sibling
53407    ** page is the right-child of the parent. Copy the contents of the
53408    ** child page into the parent, decreasing the overall height of the
53409    ** b-tree structure by one. This is described as the "balance-shallower"
53410    ** sub-algorithm in some documentation.
53411    **
53412    ** If this is an auto-vacuum database, the call to copyNodeContent()
53413    ** sets all pointer-map entries corresponding to database image pages
53414    ** for which the pointer is stored within the content being copied.
53415    **
53416    ** The second assert below verifies that the child page is defragmented
53417    ** (it must be, as it was just reconstructed using assemblePage()). This
53418    ** is important if the parent page happens to be page 1 of the database
53419    ** image.  */
53420    assert( nNew==1 );
53421    assert( apNew[0]->nFree ==
53422        (get2byte(&apNew[0]->aData[5])-apNew[0]->cellOffset-apNew[0]->nCell*2)
53423    );
53424    copyNodeContent(apNew[0], pParent, &rc);
53425    freePage(apNew[0], &rc);
53426  }else if( ISAUTOVACUUM ){
53427    /* Fix the pointer-map entries for all the cells that were shifted around.
53428    ** There are several different types of pointer-map entries that need to
53429    ** be dealt with by this routine. Some of these have been set already, but
53430    ** many have not. The following is a summary:
53431    **
53432    **   1) The entries associated with new sibling pages that were not
53433    **      siblings when this function was called. These have already
53434    **      been set. We don't need to worry about old siblings that were
53435    **      moved to the free-list - the freePage() code has taken care
53436    **      of those.
53437    **
53438    **   2) The pointer-map entries associated with the first overflow
53439    **      page in any overflow chains used by new divider cells. These
53440    **      have also already been taken care of by the insertCell() code.
53441    **
53442    **   3) If the sibling pages are not leaves, then the child pages of
53443    **      cells stored on the sibling pages may need to be updated.
53444    **
53445    **   4) If the sibling pages are not internal intkey nodes, then any
53446    **      overflow pages used by these cells may need to be updated
53447    **      (internal intkey nodes never contain pointers to overflow pages).
53448    **
53449    **   5) If the sibling pages are not leaves, then the pointer-map
53450    **      entries for the right-child pages of each sibling may need
53451    **      to be updated.
53452    **
53453    ** Cases 1 and 2 are dealt with above by other code. The next
53454    ** block deals with cases 3 and 4 and the one after that, case 5. Since
53455    ** setting a pointer map entry is a relatively expensive operation, this
53456    ** code only sets pointer map entries for child or overflow pages that have
53457    ** actually moved between pages.  */
53458    MemPage *pNew = apNew[0];
53459    MemPage *pOld = apCopy[0];
53460    int nOverflow = pOld->nOverflow;
53461    int iNextOld = pOld->nCell + nOverflow;
53462    int iOverflow = (nOverflow ? pOld->aOvfl[0].idx : -1);
53463    j = 0;                             /* Current 'old' sibling page */
53464    k = 0;                             /* Current 'new' sibling page */
53465    for(i=0; i<nCell; i++){
53466      int isDivider = 0;
53467      while( i==iNextOld ){
53468        /* Cell i is the cell immediately following the last cell on old
53469        ** sibling page j. If the siblings are not leaf pages of an
53470        ** intkey b-tree, then cell i was a divider cell. */
53471        pOld = apCopy[++j];
53472        iNextOld = i + !leafData + pOld->nCell + pOld->nOverflow;
53473        if( pOld->nOverflow ){
53474          nOverflow = pOld->nOverflow;
53475          iOverflow = i + !leafData + pOld->aOvfl[0].idx;
53476        }
53477        isDivider = !leafData;
53478      }
53479
53480      assert(nOverflow>0 || iOverflow<i );
53481      assert(nOverflow<2 || pOld->aOvfl[0].idx==pOld->aOvfl[1].idx-1);
53482      assert(nOverflow<3 || pOld->aOvfl[1].idx==pOld->aOvfl[2].idx-1);
53483      if( i==iOverflow ){
53484        isDivider = 1;
53485        if( (--nOverflow)>0 ){
53486          iOverflow++;
53487        }
53488      }
53489
53490      if( i==cntNew[k] ){
53491        /* Cell i is the cell immediately following the last cell on new
53492        ** sibling page k. If the siblings are not leaf pages of an
53493        ** intkey b-tree, then cell i is a divider cell.  */
53494        pNew = apNew[++k];
53495        if( !leafData ) continue;
53496      }
53497      assert( j<nOld );
53498      assert( k<nNew );
53499
53500      /* If the cell was originally divider cell (and is not now) or
53501      ** an overflow cell, or if the cell was located on a different sibling
53502      ** page before the balancing, then the pointer map entries associated
53503      ** with any child or overflow pages need to be updated.  */
53504      if( isDivider || pOld->pgno!=pNew->pgno ){
53505        if( !leafCorrection ){
53506          ptrmapPut(pBt, get4byte(apCell[i]), PTRMAP_BTREE, pNew->pgno, &rc);
53507        }
53508        if( szCell[i]>pNew->minLocal ){
53509          ptrmapPutOvflPtr(pNew, apCell[i], &rc);
53510        }
53511      }
53512    }
53513
53514    if( !leafCorrection ){
53515      for(i=0; i<nNew; i++){
53516        u32 key = get4byte(&apNew[i]->aData[8]);
53517        ptrmapPut(pBt, key, PTRMAP_BTREE, apNew[i]->pgno, &rc);
53518      }
53519    }
53520
53521#if 0
53522    /* The ptrmapCheckPages() contains assert() statements that verify that
53523    ** all pointer map pages are set correctly. This is helpful while
53524    ** debugging. This is usually disabled because a corrupt database may
53525    ** cause an assert() statement to fail.  */
53526    ptrmapCheckPages(apNew, nNew);
53527    ptrmapCheckPages(&pParent, 1);
53528#endif
53529  }
53530
53531  assert( pParent->isInit );
53532  TRACE(("BALANCE: finished: old=%d new=%d cells=%d\n",
53533          nOld, nNew, nCell));
53534
53535  /*
53536  ** Cleanup before returning.
53537  */
53538balance_cleanup:
53539  sqlite3ScratchFree(apCell);
53540  for(i=0; i<nOld; i++){
53541    releasePage(apOld[i]);
53542  }
53543  for(i=0; i<nNew; i++){
53544    releasePage(apNew[i]);
53545  }
53546
53547  return rc;
53548}
53549
53550
53551/*
53552** This function is called when the root page of a b-tree structure is
53553** overfull (has one or more overflow pages).
53554**
53555** A new child page is allocated and the contents of the current root
53556** page, including overflow cells, are copied into the child. The root
53557** page is then overwritten to make it an empty page with the right-child
53558** pointer pointing to the new page.
53559**
53560** Before returning, all pointer-map entries corresponding to pages
53561** that the new child-page now contains pointers to are updated. The
53562** entry corresponding to the new right-child pointer of the root
53563** page is also updated.
53564**
53565** If successful, *ppChild is set to contain a reference to the child
53566** page and SQLITE_OK is returned. In this case the caller is required
53567** to call releasePage() on *ppChild exactly once. If an error occurs,
53568** an error code is returned and *ppChild is set to 0.
53569*/
53570static int balance_deeper(MemPage *pRoot, MemPage **ppChild){
53571  int rc;                        /* Return value from subprocedures */
53572  MemPage *pChild = 0;           /* Pointer to a new child page */
53573  Pgno pgnoChild = 0;            /* Page number of the new child page */
53574  BtShared *pBt = pRoot->pBt;    /* The BTree */
53575
53576  assert( pRoot->nOverflow>0 );
53577  assert( sqlite3_mutex_held(pBt->mutex) );
53578
53579  /* Make pRoot, the root page of the b-tree, writable. Allocate a new
53580  ** page that will become the new right-child of pPage. Copy the contents
53581  ** of the node stored on pRoot into the new child page.
53582  */
53583  rc = sqlite3PagerWrite(pRoot->pDbPage);
53584  if( rc==SQLITE_OK ){
53585    rc = allocateBtreePage(pBt,&pChild,&pgnoChild,pRoot->pgno,0);
53586    copyNodeContent(pRoot, pChild, &rc);
53587    if( ISAUTOVACUUM ){
53588      ptrmapPut(pBt, pgnoChild, PTRMAP_BTREE, pRoot->pgno, &rc);
53589    }
53590  }
53591  if( rc ){
53592    *ppChild = 0;
53593    releasePage(pChild);
53594    return rc;
53595  }
53596  assert( sqlite3PagerIswriteable(pChild->pDbPage) );
53597  assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
53598  assert( pChild->nCell==pRoot->nCell );
53599
53600  TRACE(("BALANCE: copy root %d into %d\n", pRoot->pgno, pChild->pgno));
53601
53602  /* Copy the overflow cells from pRoot to pChild */
53603  memcpy(pChild->aOvfl, pRoot->aOvfl, pRoot->nOverflow*sizeof(pRoot->aOvfl[0]));
53604  pChild->nOverflow = pRoot->nOverflow;
53605
53606  /* Zero the contents of pRoot. Then install pChild as the right-child. */
53607  zeroPage(pRoot, pChild->aData[0] & ~PTF_LEAF);
53608  put4byte(&pRoot->aData[pRoot->hdrOffset+8], pgnoChild);
53609
53610  *ppChild = pChild;
53611  return SQLITE_OK;
53612}
53613
53614/*
53615** The page that pCur currently points to has just been modified in
53616** some way. This function figures out if this modification means the
53617** tree needs to be balanced, and if so calls the appropriate balancing
53618** routine. Balancing routines are:
53619**
53620**   balance_quick()
53621**   balance_deeper()
53622**   balance_nonroot()
53623*/
53624static int balance(BtCursor *pCur){
53625  int rc = SQLITE_OK;
53626  const int nMin = pCur->pBt->usableSize * 2 / 3;
53627  u8 aBalanceQuickSpace[13];
53628  u8 *pFree = 0;
53629
53630  TESTONLY( int balance_quick_called = 0 );
53631  TESTONLY( int balance_deeper_called = 0 );
53632
53633  do {
53634    int iPage = pCur->iPage;
53635    MemPage *pPage = pCur->apPage[iPage];
53636
53637    if( iPage==0 ){
53638      if( pPage->nOverflow ){
53639        /* The root page of the b-tree is overfull. In this case call the
53640        ** balance_deeper() function to create a new child for the root-page
53641        ** and copy the current contents of the root-page to it. The
53642        ** next iteration of the do-loop will balance the child page.
53643        */
53644        assert( (balance_deeper_called++)==0 );
53645        rc = balance_deeper(pPage, &pCur->apPage[1]);
53646        if( rc==SQLITE_OK ){
53647          pCur->iPage = 1;
53648          pCur->aiIdx[0] = 0;
53649          pCur->aiIdx[1] = 0;
53650          assert( pCur->apPage[1]->nOverflow );
53651        }
53652      }else{
53653        break;
53654      }
53655    }else if( pPage->nOverflow==0 && pPage->nFree<=nMin ){
53656      break;
53657    }else{
53658      MemPage * const pParent = pCur->apPage[iPage-1];
53659      int const iIdx = pCur->aiIdx[iPage-1];
53660
53661      rc = sqlite3PagerWrite(pParent->pDbPage);
53662      if( rc==SQLITE_OK ){
53663#ifndef SQLITE_OMIT_QUICKBALANCE
53664        if( pPage->hasData
53665         && pPage->nOverflow==1
53666         && pPage->aOvfl[0].idx==pPage->nCell
53667         && pParent->pgno!=1
53668         && pParent->nCell==iIdx
53669        ){
53670          /* Call balance_quick() to create a new sibling of pPage on which
53671          ** to store the overflow cell. balance_quick() inserts a new cell
53672          ** into pParent, which may cause pParent overflow. If this
53673          ** happens, the next interation of the do-loop will balance pParent
53674          ** use either balance_nonroot() or balance_deeper(). Until this
53675          ** happens, the overflow cell is stored in the aBalanceQuickSpace[]
53676          ** buffer.
53677          **
53678          ** The purpose of the following assert() is to check that only a
53679          ** single call to balance_quick() is made for each call to this
53680          ** function. If this were not verified, a subtle bug involving reuse
53681          ** of the aBalanceQuickSpace[] might sneak in.
53682          */
53683          assert( (balance_quick_called++)==0 );
53684          rc = balance_quick(pParent, pPage, aBalanceQuickSpace);
53685        }else
53686#endif
53687        {
53688          /* In this case, call balance_nonroot() to redistribute cells
53689          ** between pPage and up to 2 of its sibling pages. This involves
53690          ** modifying the contents of pParent, which may cause pParent to
53691          ** become overfull or underfull. The next iteration of the do-loop
53692          ** will balance the parent page to correct this.
53693          **
53694          ** If the parent page becomes overfull, the overflow cell or cells
53695          ** are stored in the pSpace buffer allocated immediately below.
53696          ** A subsequent iteration of the do-loop will deal with this by
53697          ** calling balance_nonroot() (balance_deeper() may be called first,
53698          ** but it doesn't deal with overflow cells - just moves them to a
53699          ** different page). Once this subsequent call to balance_nonroot()
53700          ** has completed, it is safe to release the pSpace buffer used by
53701          ** the previous call, as the overflow cell data will have been
53702          ** copied either into the body of a database page or into the new
53703          ** pSpace buffer passed to the latter call to balance_nonroot().
53704          */
53705          u8 *pSpace = sqlite3PageMalloc(pCur->pBt->pageSize);
53706          rc = balance_nonroot(pParent, iIdx, pSpace, iPage==1);
53707          if( pFree ){
53708            /* If pFree is not NULL, it points to the pSpace buffer used
53709            ** by a previous call to balance_nonroot(). Its contents are
53710            ** now stored either on real database pages or within the
53711            ** new pSpace buffer, so it may be safely freed here. */
53712            sqlite3PageFree(pFree);
53713          }
53714
53715          /* The pSpace buffer will be freed after the next call to
53716          ** balance_nonroot(), or just before this function returns, whichever
53717          ** comes first. */
53718          pFree = pSpace;
53719        }
53720      }
53721
53722      pPage->nOverflow = 0;
53723
53724      /* The next iteration of the do-loop balances the parent page. */
53725      releasePage(pPage);
53726      pCur->iPage--;
53727    }
53728  }while( rc==SQLITE_OK );
53729
53730  if( pFree ){
53731    sqlite3PageFree(pFree);
53732  }
53733  return rc;
53734}
53735
53736
53737/*
53738** Insert a new record into the BTree.  The key is given by (pKey,nKey)
53739** and the data is given by (pData,nData).  The cursor is used only to
53740** define what table the record should be inserted into.  The cursor
53741** is left pointing at a random location.
53742**
53743** For an INTKEY table, only the nKey value of the key is used.  pKey is
53744** ignored.  For a ZERODATA table, the pData and nData are both ignored.
53745**
53746** If the seekResult parameter is non-zero, then a successful call to
53747** MovetoUnpacked() to seek cursor pCur to (pKey, nKey) has already
53748** been performed. seekResult is the search result returned (a negative
53749** number if pCur points at an entry that is smaller than (pKey, nKey), or
53750** a positive value if pCur points at an etry that is larger than
53751** (pKey, nKey)).
53752**
53753** If the seekResult parameter is non-zero, then the caller guarantees that
53754** cursor pCur is pointing at the existing copy of a row that is to be
53755** overwritten.  If the seekResult parameter is 0, then cursor pCur may
53756** point to any entry or to no entry at all and so this function has to seek
53757** the cursor before the new key can be inserted.
53758*/
53759SQLITE_PRIVATE int sqlite3BtreeInsert(
53760  BtCursor *pCur,                /* Insert data into the table of this cursor */
53761  const void *pKey, i64 nKey,    /* The key of the new record */
53762  const void *pData, int nData,  /* The data of the new record */
53763  int nZero,                     /* Number of extra 0 bytes to append to data */
53764  int appendBias,                /* True if this is likely an append */
53765  int seekResult                 /* Result of prior MovetoUnpacked() call */
53766){
53767  int rc;
53768  int loc = seekResult;          /* -1: before desired location  +1: after */
53769  int szNew = 0;
53770  int idx;
53771  MemPage *pPage;
53772  Btree *p = pCur->pBtree;
53773  BtShared *pBt = p->pBt;
53774  unsigned char *oldCell;
53775  unsigned char *newCell = 0;
53776
53777  if( pCur->eState==CURSOR_FAULT ){
53778    assert( pCur->skipNext!=SQLITE_OK );
53779    return pCur->skipNext;
53780  }
53781
53782  assert( cursorHoldsMutex(pCur) );
53783  assert( pCur->wrFlag && pBt->inTransaction==TRANS_WRITE && !pBt->readOnly );
53784  assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
53785
53786  /* Assert that the caller has been consistent. If this cursor was opened
53787  ** expecting an index b-tree, then the caller should be inserting blob
53788  ** keys with no associated data. If the cursor was opened expecting an
53789  ** intkey table, the caller should be inserting integer keys with a
53790  ** blob of associated data.  */
53791  assert( (pKey==0)==(pCur->pKeyInfo==0) );
53792
53793  /* If this is an insert into a table b-tree, invalidate any incrblob
53794  ** cursors open on the row being replaced (assuming this is a replace
53795  ** operation - if it is not, the following is a no-op).  */
53796  if( pCur->pKeyInfo==0 ){
53797    invalidateIncrblobCursors(p, nKey, 0);
53798  }
53799
53800  /* Save the positions of any other cursors open on this table.
53801  **
53802  ** In some cases, the call to btreeMoveto() below is a no-op. For
53803  ** example, when inserting data into a table with auto-generated integer
53804  ** keys, the VDBE layer invokes sqlite3BtreeLast() to figure out the
53805  ** integer key to use. It then calls this function to actually insert the
53806  ** data into the intkey B-Tree. In this case btreeMoveto() recognizes
53807  ** that the cursor is already where it needs to be and returns without
53808  ** doing any work. To avoid thwarting these optimizations, it is important
53809  ** not to clear the cursor here.
53810  */
53811  rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
53812  if( rc ) return rc;
53813  if( !loc ){
53814    rc = btreeMoveto(pCur, pKey, nKey, appendBias, &loc);
53815    if( rc ) return rc;
53816  }
53817  assert( pCur->eState==CURSOR_VALID || (pCur->eState==CURSOR_INVALID && loc) );
53818
53819  pPage = pCur->apPage[pCur->iPage];
53820  assert( pPage->intKey || nKey>=0 );
53821  assert( pPage->leaf || !pPage->intKey );
53822
53823  TRACE(("INSERT: table=%d nkey=%lld ndata=%d page=%d %s\n",
53824          pCur->pgnoRoot, nKey, nData, pPage->pgno,
53825          loc==0 ? "overwrite" : "new entry"));
53826  assert( pPage->isInit );
53827  allocateTempSpace(pBt);
53828  newCell = pBt->pTmpSpace;
53829  if( newCell==0 ) return SQLITE_NOMEM;
53830  rc = fillInCell(pPage, newCell, pKey, nKey, pData, nData, nZero, &szNew);
53831  if( rc ) goto end_insert;
53832  assert( szNew==cellSizePtr(pPage, newCell) );
53833  assert( szNew <= MX_CELL_SIZE(pBt) );
53834  idx = pCur->aiIdx[pCur->iPage];
53835  if( loc==0 ){
53836    u16 szOld;
53837    assert( idx<pPage->nCell );
53838    rc = sqlite3PagerWrite(pPage->pDbPage);
53839    if( rc ){
53840      goto end_insert;
53841    }
53842    oldCell = findCell(pPage, idx);
53843    if( !pPage->leaf ){
53844      memcpy(newCell, oldCell, 4);
53845    }
53846    szOld = cellSizePtr(pPage, oldCell);
53847    rc = clearCell(pPage, oldCell);
53848    dropCell(pPage, idx, szOld, &rc);
53849    if( rc ) goto end_insert;
53850  }else if( loc<0 && pPage->nCell>0 ){
53851    assert( pPage->leaf );
53852    idx = ++pCur->aiIdx[pCur->iPage];
53853  }else{
53854    assert( pPage->leaf );
53855  }
53856  insertCell(pPage, idx, newCell, szNew, 0, 0, &rc);
53857  assert( rc!=SQLITE_OK || pPage->nCell>0 || pPage->nOverflow>0 );
53858
53859  /* If no error has occured and pPage has an overflow cell, call balance()
53860  ** to redistribute the cells within the tree. Since balance() may move
53861  ** the cursor, zero the BtCursor.info.nSize and BtCursor.validNKey
53862  ** variables.
53863  **
53864  ** Previous versions of SQLite called moveToRoot() to move the cursor
53865  ** back to the root page as balance() used to invalidate the contents
53866  ** of BtCursor.apPage[] and BtCursor.aiIdx[]. Instead of doing that,
53867  ** set the cursor state to "invalid". This makes common insert operations
53868  ** slightly faster.
53869  **
53870  ** There is a subtle but important optimization here too. When inserting
53871  ** multiple records into an intkey b-tree using a single cursor (as can
53872  ** happen while processing an "INSERT INTO ... SELECT" statement), it
53873  ** is advantageous to leave the cursor pointing to the last entry in
53874  ** the b-tree if possible. If the cursor is left pointing to the last
53875  ** entry in the table, and the next row inserted has an integer key
53876  ** larger than the largest existing key, it is possible to insert the
53877  ** row without seeking the cursor. This can be a big performance boost.
53878  */
53879  pCur->info.nSize = 0;
53880  pCur->validNKey = 0;
53881  if( rc==SQLITE_OK && pPage->nOverflow ){
53882    rc = balance(pCur);
53883
53884    /* Must make sure nOverflow is reset to zero even if the balance()
53885    ** fails. Internal data structure corruption will result otherwise.
53886    ** Also, set the cursor state to invalid. This stops saveCursorPosition()
53887    ** from trying to save the current position of the cursor.  */
53888    pCur->apPage[pCur->iPage]->nOverflow = 0;
53889    pCur->eState = CURSOR_INVALID;
53890  }
53891  assert( pCur->apPage[pCur->iPage]->nOverflow==0 );
53892
53893end_insert:
53894  return rc;
53895}
53896
53897/*
53898** Delete the entry that the cursor is pointing to.  The cursor
53899** is left pointing at a arbitrary location.
53900*/
53901SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor *pCur){
53902  Btree *p = pCur->pBtree;
53903  BtShared *pBt = p->pBt;
53904  int rc;                              /* Return code */
53905  MemPage *pPage;                      /* Page to delete cell from */
53906  unsigned char *pCell;                /* Pointer to cell to delete */
53907  int iCellIdx;                        /* Index of cell to delete */
53908  int iCellDepth;                      /* Depth of node containing pCell */
53909
53910  assert( cursorHoldsMutex(pCur) );
53911  assert( pBt->inTransaction==TRANS_WRITE );
53912  assert( !pBt->readOnly );
53913  assert( pCur->wrFlag );
53914  assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
53915  assert( !hasReadConflicts(p, pCur->pgnoRoot) );
53916
53917  if( NEVER(pCur->aiIdx[pCur->iPage]>=pCur->apPage[pCur->iPage]->nCell)
53918   || NEVER(pCur->eState!=CURSOR_VALID)
53919  ){
53920    return SQLITE_ERROR;  /* Something has gone awry. */
53921  }
53922
53923  /* If this is a delete operation to remove a row from a table b-tree,
53924  ** invalidate any incrblob cursors open on the row being deleted.  */
53925  if( pCur->pKeyInfo==0 ){
53926    invalidateIncrblobCursors(p, pCur->info.nKey, 0);
53927  }
53928
53929  iCellDepth = pCur->iPage;
53930  iCellIdx = pCur->aiIdx[iCellDepth];
53931  pPage = pCur->apPage[iCellDepth];
53932  pCell = findCell(pPage, iCellIdx);
53933
53934  /* If the page containing the entry to delete is not a leaf page, move
53935  ** the cursor to the largest entry in the tree that is smaller than
53936  ** the entry being deleted. This cell will replace the cell being deleted
53937  ** from the internal node. The 'previous' entry is used for this instead
53938  ** of the 'next' entry, as the previous entry is always a part of the
53939  ** sub-tree headed by the child page of the cell being deleted. This makes
53940  ** balancing the tree following the delete operation easier.  */
53941  if( !pPage->leaf ){
53942    int notUsed;
53943    rc = sqlite3BtreePrevious(pCur, &notUsed);
53944    if( rc ) return rc;
53945  }
53946
53947  /* Save the positions of any other cursors open on this table before
53948  ** making any modifications. Make the page containing the entry to be
53949  ** deleted writable. Then free any overflow pages associated with the
53950  ** entry and finally remove the cell itself from within the page.
53951  */
53952  rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
53953  if( rc ) return rc;
53954  rc = sqlite3PagerWrite(pPage->pDbPage);
53955  if( rc ) return rc;
53956  rc = clearCell(pPage, pCell);
53957  dropCell(pPage, iCellIdx, cellSizePtr(pPage, pCell), &rc);
53958  if( rc ) return rc;
53959
53960  /* If the cell deleted was not located on a leaf page, then the cursor
53961  ** is currently pointing to the largest entry in the sub-tree headed
53962  ** by the child-page of the cell that was just deleted from an internal
53963  ** node. The cell from the leaf node needs to be moved to the internal
53964  ** node to replace the deleted cell.  */
53965  if( !pPage->leaf ){
53966    MemPage *pLeaf = pCur->apPage[pCur->iPage];
53967    int nCell;
53968    Pgno n = pCur->apPage[iCellDepth+1]->pgno;
53969    unsigned char *pTmp;
53970
53971    pCell = findCell(pLeaf, pLeaf->nCell-1);
53972    nCell = cellSizePtr(pLeaf, pCell);
53973    assert( MX_CELL_SIZE(pBt) >= nCell );
53974
53975    allocateTempSpace(pBt);
53976    pTmp = pBt->pTmpSpace;
53977
53978    rc = sqlite3PagerWrite(pLeaf->pDbPage);
53979    insertCell(pPage, iCellIdx, pCell-4, nCell+4, pTmp, n, &rc);
53980    dropCell(pLeaf, pLeaf->nCell-1, nCell, &rc);
53981    if( rc ) return rc;
53982  }
53983
53984  /* Balance the tree. If the entry deleted was located on a leaf page,
53985  ** then the cursor still points to that page. In this case the first
53986  ** call to balance() repairs the tree, and the if(...) condition is
53987  ** never true.
53988  **
53989  ** Otherwise, if the entry deleted was on an internal node page, then
53990  ** pCur is pointing to the leaf page from which a cell was removed to
53991  ** replace the cell deleted from the internal node. This is slightly
53992  ** tricky as the leaf node may be underfull, and the internal node may
53993  ** be either under or overfull. In this case run the balancing algorithm
53994  ** on the leaf node first. If the balance proceeds far enough up the
53995  ** tree that we can be sure that any problem in the internal node has
53996  ** been corrected, so be it. Otherwise, after balancing the leaf node,
53997  ** walk the cursor up the tree to the internal node and balance it as
53998  ** well.  */
53999  rc = balance(pCur);
54000  if( rc==SQLITE_OK && pCur->iPage>iCellDepth ){
54001    while( pCur->iPage>iCellDepth ){
54002      releasePage(pCur->apPage[pCur->iPage--]);
54003    }
54004    rc = balance(pCur);
54005  }
54006
54007  if( rc==SQLITE_OK ){
54008    moveToRoot(pCur);
54009  }
54010  return rc;
54011}
54012
54013/*
54014** Create a new BTree table.  Write into *piTable the page
54015** number for the root page of the new table.
54016**
54017** The type of type is determined by the flags parameter.  Only the
54018** following values of flags are currently in use.  Other values for
54019** flags might not work:
54020**
54021**     BTREE_INTKEY|BTREE_LEAFDATA     Used for SQL tables with rowid keys
54022**     BTREE_ZERODATA                  Used for SQL indices
54023*/
54024static int btreeCreateTable(Btree *p, int *piTable, int createTabFlags){
54025  BtShared *pBt = p->pBt;
54026  MemPage *pRoot;
54027  Pgno pgnoRoot;
54028  int rc;
54029  int ptfFlags;          /* Page-type flage for the root page of new table */
54030
54031  assert( sqlite3BtreeHoldsMutex(p) );
54032  assert( pBt->inTransaction==TRANS_WRITE );
54033  assert( !pBt->readOnly );
54034
54035#ifdef SQLITE_OMIT_AUTOVACUUM
54036  rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
54037  if( rc ){
54038    return rc;
54039  }
54040#else
54041  if( pBt->autoVacuum ){
54042    Pgno pgnoMove;      /* Move a page here to make room for the root-page */
54043    MemPage *pPageMove; /* The page to move to. */
54044
54045    /* Creating a new table may probably require moving an existing database
54046    ** to make room for the new tables root page. In case this page turns
54047    ** out to be an overflow page, delete all overflow page-map caches
54048    ** held by open cursors.
54049    */
54050    invalidateAllOverflowCache(pBt);
54051
54052    /* Read the value of meta[3] from the database to determine where the
54053    ** root page of the new table should go. meta[3] is the largest root-page
54054    ** created so far, so the new root-page is (meta[3]+1).
54055    */
54056    sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &pgnoRoot);
54057    pgnoRoot++;
54058
54059    /* The new root-page may not be allocated on a pointer-map page, or the
54060    ** PENDING_BYTE page.
54061    */
54062    while( pgnoRoot==PTRMAP_PAGENO(pBt, pgnoRoot) ||
54063        pgnoRoot==PENDING_BYTE_PAGE(pBt) ){
54064      pgnoRoot++;
54065    }
54066    assert( pgnoRoot>=3 );
54067
54068    /* Allocate a page. The page that currently resides at pgnoRoot will
54069    ** be moved to the allocated page (unless the allocated page happens
54070    ** to reside at pgnoRoot).
54071    */
54072    rc = allocateBtreePage(pBt, &pPageMove, &pgnoMove, pgnoRoot, 1);
54073    if( rc!=SQLITE_OK ){
54074      return rc;
54075    }
54076
54077    if( pgnoMove!=pgnoRoot ){
54078      /* pgnoRoot is the page that will be used for the root-page of
54079      ** the new table (assuming an error did not occur). But we were
54080      ** allocated pgnoMove. If required (i.e. if it was not allocated
54081      ** by extending the file), the current page at position pgnoMove
54082      ** is already journaled.
54083      */
54084      u8 eType = 0;
54085      Pgno iPtrPage = 0;
54086
54087      releasePage(pPageMove);
54088
54089      /* Move the page currently at pgnoRoot to pgnoMove. */
54090      rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
54091      if( rc!=SQLITE_OK ){
54092        return rc;
54093      }
54094      rc = ptrmapGet(pBt, pgnoRoot, &eType, &iPtrPage);
54095      if( eType==PTRMAP_ROOTPAGE || eType==PTRMAP_FREEPAGE ){
54096        rc = SQLITE_CORRUPT_BKPT;
54097      }
54098      if( rc!=SQLITE_OK ){
54099        releasePage(pRoot);
54100        return rc;
54101      }
54102      assert( eType!=PTRMAP_ROOTPAGE );
54103      assert( eType!=PTRMAP_FREEPAGE );
54104      rc = relocatePage(pBt, pRoot, eType, iPtrPage, pgnoMove, 0);
54105      releasePage(pRoot);
54106
54107      /* Obtain the page at pgnoRoot */
54108      if( rc!=SQLITE_OK ){
54109        return rc;
54110      }
54111      rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
54112      if( rc!=SQLITE_OK ){
54113        return rc;
54114      }
54115      rc = sqlite3PagerWrite(pRoot->pDbPage);
54116      if( rc!=SQLITE_OK ){
54117        releasePage(pRoot);
54118        return rc;
54119      }
54120    }else{
54121      pRoot = pPageMove;
54122    }
54123
54124    /* Update the pointer-map and meta-data with the new root-page number. */
54125    ptrmapPut(pBt, pgnoRoot, PTRMAP_ROOTPAGE, 0, &rc);
54126    if( rc ){
54127      releasePage(pRoot);
54128      return rc;
54129    }
54130
54131    /* When the new root page was allocated, page 1 was made writable in
54132    ** order either to increase the database filesize, or to decrement the
54133    ** freelist count.  Hence, the sqlite3BtreeUpdateMeta() call cannot fail.
54134    */
54135    assert( sqlite3PagerIswriteable(pBt->pPage1->pDbPage) );
54136    rc = sqlite3BtreeUpdateMeta(p, 4, pgnoRoot);
54137    if( NEVER(rc) ){
54138      releasePage(pRoot);
54139      return rc;
54140    }
54141
54142  }else{
54143    rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
54144    if( rc ) return rc;
54145  }
54146#endif
54147  assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
54148  if( createTabFlags & BTREE_INTKEY ){
54149    ptfFlags = PTF_INTKEY | PTF_LEAFDATA | PTF_LEAF;
54150  }else{
54151    ptfFlags = PTF_ZERODATA | PTF_LEAF;
54152  }
54153  zeroPage(pRoot, ptfFlags);
54154  sqlite3PagerUnref(pRoot->pDbPage);
54155  assert( (pBt->openFlags & BTREE_SINGLE)==0 || pgnoRoot==2 );
54156  *piTable = (int)pgnoRoot;
54157  return SQLITE_OK;
54158}
54159SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree *p, int *piTable, int flags){
54160  int rc;
54161  sqlite3BtreeEnter(p);
54162  rc = btreeCreateTable(p, piTable, flags);
54163  sqlite3BtreeLeave(p);
54164  return rc;
54165}
54166
54167/*
54168** Erase the given database page and all its children.  Return
54169** the page to the freelist.
54170*/
54171static int clearDatabasePage(
54172  BtShared *pBt,           /* The BTree that contains the table */
54173  Pgno pgno,               /* Page number to clear */
54174  int freePageFlag,        /* Deallocate page if true */
54175  int *pnChange            /* Add number of Cells freed to this counter */
54176){
54177  MemPage *pPage;
54178  int rc;
54179  unsigned char *pCell;
54180  int i;
54181
54182  assert( sqlite3_mutex_held(pBt->mutex) );
54183  if( pgno>btreePagecount(pBt) ){
54184    return SQLITE_CORRUPT_BKPT;
54185  }
54186
54187  rc = getAndInitPage(pBt, pgno, &pPage);
54188  if( rc ) return rc;
54189  for(i=0; i<pPage->nCell; i++){
54190    pCell = findCell(pPage, i);
54191    if( !pPage->leaf ){
54192      rc = clearDatabasePage(pBt, get4byte(pCell), 1, pnChange);
54193      if( rc ) goto cleardatabasepage_out;
54194    }
54195    rc = clearCell(pPage, pCell);
54196    if( rc ) goto cleardatabasepage_out;
54197  }
54198  if( !pPage->leaf ){
54199    rc = clearDatabasePage(pBt, get4byte(&pPage->aData[8]), 1, pnChange);
54200    if( rc ) goto cleardatabasepage_out;
54201  }else if( pnChange ){
54202    assert( pPage->intKey );
54203    *pnChange += pPage->nCell;
54204  }
54205  if( freePageFlag ){
54206    freePage(pPage, &rc);
54207  }else if( (rc = sqlite3PagerWrite(pPage->pDbPage))==0 ){
54208    zeroPage(pPage, pPage->aData[0] | PTF_LEAF);
54209  }
54210
54211cleardatabasepage_out:
54212  releasePage(pPage);
54213  return rc;
54214}
54215
54216/*
54217** Delete all information from a single table in the database.  iTable is
54218** the page number of the root of the table.  After this routine returns,
54219** the root page is empty, but still exists.
54220**
54221** This routine will fail with SQLITE_LOCKED if there are any open
54222** read cursors on the table.  Open write cursors are moved to the
54223** root of the table.
54224**
54225** If pnChange is not NULL, then table iTable must be an intkey table. The
54226** integer value pointed to by pnChange is incremented by the number of
54227** entries in the table.
54228*/
54229SQLITE_PRIVATE int sqlite3BtreeClearTable(Btree *p, int iTable, int *pnChange){
54230  int rc;
54231  BtShared *pBt = p->pBt;
54232  sqlite3BtreeEnter(p);
54233  assert( p->inTrans==TRANS_WRITE );
54234
54235  /* Invalidate all incrblob cursors open on table iTable (assuming iTable
54236  ** is the root of a table b-tree - if it is not, the following call is
54237  ** a no-op).  */
54238  invalidateIncrblobCursors(p, 0, 1);
54239
54240  rc = saveAllCursors(pBt, (Pgno)iTable, 0);
54241  if( SQLITE_OK==rc ){
54242    rc = clearDatabasePage(pBt, (Pgno)iTable, 0, pnChange);
54243  }
54244  sqlite3BtreeLeave(p);
54245  return rc;
54246}
54247
54248/*
54249** Erase all information in a table and add the root of the table to
54250** the freelist.  Except, the root of the principle table (the one on
54251** page 1) is never added to the freelist.
54252**
54253** This routine will fail with SQLITE_LOCKED if there are any open
54254** cursors on the table.
54255**
54256** If AUTOVACUUM is enabled and the page at iTable is not the last
54257** root page in the database file, then the last root page
54258** in the database file is moved into the slot formerly occupied by
54259** iTable and that last slot formerly occupied by the last root page
54260** is added to the freelist instead of iTable.  In this say, all
54261** root pages are kept at the beginning of the database file, which
54262** is necessary for AUTOVACUUM to work right.  *piMoved is set to the
54263** page number that used to be the last root page in the file before
54264** the move.  If no page gets moved, *piMoved is set to 0.
54265** The last root page is recorded in meta[3] and the value of
54266** meta[3] is updated by this procedure.
54267*/
54268static int btreeDropTable(Btree *p, Pgno iTable, int *piMoved){
54269  int rc;
54270  MemPage *pPage = 0;
54271  BtShared *pBt = p->pBt;
54272
54273  assert( sqlite3BtreeHoldsMutex(p) );
54274  assert( p->inTrans==TRANS_WRITE );
54275
54276  /* It is illegal to drop a table if any cursors are open on the
54277  ** database. This is because in auto-vacuum mode the backend may
54278  ** need to move another root-page to fill a gap left by the deleted
54279  ** root page. If an open cursor was using this page a problem would
54280  ** occur.
54281  **
54282  ** This error is caught long before control reaches this point.
54283  */
54284  if( NEVER(pBt->pCursor) ){
54285    sqlite3ConnectionBlocked(p->db, pBt->pCursor->pBtree->db);
54286    return SQLITE_LOCKED_SHAREDCACHE;
54287  }
54288
54289  rc = btreeGetPage(pBt, (Pgno)iTable, &pPage, 0);
54290  if( rc ) return rc;
54291  rc = sqlite3BtreeClearTable(p, iTable, 0);
54292  if( rc ){
54293    releasePage(pPage);
54294    return rc;
54295  }
54296
54297  *piMoved = 0;
54298
54299  if( iTable>1 ){
54300#ifdef SQLITE_OMIT_AUTOVACUUM
54301    freePage(pPage, &rc);
54302    releasePage(pPage);
54303#else
54304    if( pBt->autoVacuum ){
54305      Pgno maxRootPgno;
54306      sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &maxRootPgno);
54307
54308      if( iTable==maxRootPgno ){
54309        /* If the table being dropped is the table with the largest root-page
54310        ** number in the database, put the root page on the free list.
54311        */
54312        freePage(pPage, &rc);
54313        releasePage(pPage);
54314        if( rc!=SQLITE_OK ){
54315          return rc;
54316        }
54317      }else{
54318        /* The table being dropped does not have the largest root-page
54319        ** number in the database. So move the page that does into the
54320        ** gap left by the deleted root-page.
54321        */
54322        MemPage *pMove;
54323        releasePage(pPage);
54324        rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
54325        if( rc!=SQLITE_OK ){
54326          return rc;
54327        }
54328        rc = relocatePage(pBt, pMove, PTRMAP_ROOTPAGE, 0, iTable, 0);
54329        releasePage(pMove);
54330        if( rc!=SQLITE_OK ){
54331          return rc;
54332        }
54333        pMove = 0;
54334        rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
54335        freePage(pMove, &rc);
54336        releasePage(pMove);
54337        if( rc!=SQLITE_OK ){
54338          return rc;
54339        }
54340        *piMoved = maxRootPgno;
54341      }
54342
54343      /* Set the new 'max-root-page' value in the database header. This
54344      ** is the old value less one, less one more if that happens to
54345      ** be a root-page number, less one again if that is the
54346      ** PENDING_BYTE_PAGE.
54347      */
54348      maxRootPgno--;
54349      while( maxRootPgno==PENDING_BYTE_PAGE(pBt)
54350             || PTRMAP_ISPAGE(pBt, maxRootPgno) ){
54351        maxRootPgno--;
54352      }
54353      assert( maxRootPgno!=PENDING_BYTE_PAGE(pBt) );
54354
54355      rc = sqlite3BtreeUpdateMeta(p, 4, maxRootPgno);
54356    }else{
54357      freePage(pPage, &rc);
54358      releasePage(pPage);
54359    }
54360#endif
54361  }else{
54362    /* If sqlite3BtreeDropTable was called on page 1.
54363    ** This really never should happen except in a corrupt
54364    ** database.
54365    */
54366    zeroPage(pPage, PTF_INTKEY|PTF_LEAF );
54367    releasePage(pPage);
54368  }
54369  return rc;
54370}
54371SQLITE_PRIVATE int sqlite3BtreeDropTable(Btree *p, int iTable, int *piMoved){
54372  int rc;
54373  sqlite3BtreeEnter(p);
54374  rc = btreeDropTable(p, iTable, piMoved);
54375  sqlite3BtreeLeave(p);
54376  return rc;
54377}
54378
54379
54380/*
54381** This function may only be called if the b-tree connection already
54382** has a read or write transaction open on the database.
54383**
54384** Read the meta-information out of a database file.  Meta[0]
54385** is the number of free pages currently in the database.  Meta[1]
54386** through meta[15] are available for use by higher layers.  Meta[0]
54387** is read-only, the others are read/write.
54388**
54389** The schema layer numbers meta values differently.  At the schema
54390** layer (and the SetCookie and ReadCookie opcodes) the number of
54391** free pages is not visible.  So Cookie[0] is the same as Meta[1].
54392*/
54393SQLITE_PRIVATE void sqlite3BtreeGetMeta(Btree *p, int idx, u32 *pMeta){
54394  BtShared *pBt = p->pBt;
54395
54396  sqlite3BtreeEnter(p);
54397  assert( p->inTrans>TRANS_NONE );
54398  assert( SQLITE_OK==querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK) );
54399  assert( pBt->pPage1 );
54400  assert( idx>=0 && idx<=15 );
54401
54402  *pMeta = get4byte(&pBt->pPage1->aData[36 + idx*4]);
54403
54404  /* If auto-vacuum is disabled in this build and this is an auto-vacuum
54405  ** database, mark the database as read-only.  */
54406#ifdef SQLITE_OMIT_AUTOVACUUM
54407  if( idx==BTREE_LARGEST_ROOT_PAGE && *pMeta>0 ) pBt->readOnly = 1;
54408#endif
54409
54410  sqlite3BtreeLeave(p);
54411}
54412
54413/*
54414** Write meta-information back into the database.  Meta[0] is
54415** read-only and may not be written.
54416*/
54417SQLITE_PRIVATE int sqlite3BtreeUpdateMeta(Btree *p, int idx, u32 iMeta){
54418  BtShared *pBt = p->pBt;
54419  unsigned char *pP1;
54420  int rc;
54421  assert( idx>=1 && idx<=15 );
54422  sqlite3BtreeEnter(p);
54423  assert( p->inTrans==TRANS_WRITE );
54424  assert( pBt->pPage1!=0 );
54425  pP1 = pBt->pPage1->aData;
54426  rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
54427  if( rc==SQLITE_OK ){
54428    put4byte(&pP1[36 + idx*4], iMeta);
54429#ifndef SQLITE_OMIT_AUTOVACUUM
54430    if( idx==BTREE_INCR_VACUUM ){
54431      assert( pBt->autoVacuum || iMeta==0 );
54432      assert( iMeta==0 || iMeta==1 );
54433      pBt->incrVacuum = (u8)iMeta;
54434    }
54435#endif
54436  }
54437  sqlite3BtreeLeave(p);
54438  return rc;
54439}
54440
54441#ifndef SQLITE_OMIT_BTREECOUNT
54442/*
54443** The first argument, pCur, is a cursor opened on some b-tree. Count the
54444** number of entries in the b-tree and write the result to *pnEntry.
54445**
54446** SQLITE_OK is returned if the operation is successfully executed.
54447** Otherwise, if an error is encountered (i.e. an IO error or database
54448** corruption) an SQLite error code is returned.
54449*/
54450SQLITE_PRIVATE int sqlite3BtreeCount(BtCursor *pCur, i64 *pnEntry){
54451  i64 nEntry = 0;                      /* Value to return in *pnEntry */
54452  int rc;                              /* Return code */
54453  rc = moveToRoot(pCur);
54454
54455  /* Unless an error occurs, the following loop runs one iteration for each
54456  ** page in the B-Tree structure (not including overflow pages).
54457  */
54458  while( rc==SQLITE_OK ){
54459    int iIdx;                          /* Index of child node in parent */
54460    MemPage *pPage;                    /* Current page of the b-tree */
54461
54462    /* If this is a leaf page or the tree is not an int-key tree, then
54463    ** this page contains countable entries. Increment the entry counter
54464    ** accordingly.
54465    */
54466    pPage = pCur->apPage[pCur->iPage];
54467    if( pPage->leaf || !pPage->intKey ){
54468      nEntry += pPage->nCell;
54469    }
54470
54471    /* pPage is a leaf node. This loop navigates the cursor so that it
54472    ** points to the first interior cell that it points to the parent of
54473    ** the next page in the tree that has not yet been visited. The
54474    ** pCur->aiIdx[pCur->iPage] value is set to the index of the parent cell
54475    ** of the page, or to the number of cells in the page if the next page
54476    ** to visit is the right-child of its parent.
54477    **
54478    ** If all pages in the tree have been visited, return SQLITE_OK to the
54479    ** caller.
54480    */
54481    if( pPage->leaf ){
54482      do {
54483        if( pCur->iPage==0 ){
54484          /* All pages of the b-tree have been visited. Return successfully. */
54485          *pnEntry = nEntry;
54486          return SQLITE_OK;
54487        }
54488        moveToParent(pCur);
54489      }while ( pCur->aiIdx[pCur->iPage]>=pCur->apPage[pCur->iPage]->nCell );
54490
54491      pCur->aiIdx[pCur->iPage]++;
54492      pPage = pCur->apPage[pCur->iPage];
54493    }
54494
54495    /* Descend to the child node of the cell that the cursor currently
54496    ** points at. This is the right-child if (iIdx==pPage->nCell).
54497    */
54498    iIdx = pCur->aiIdx[pCur->iPage];
54499    if( iIdx==pPage->nCell ){
54500      rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
54501    }else{
54502      rc = moveToChild(pCur, get4byte(findCell(pPage, iIdx)));
54503    }
54504  }
54505
54506  /* An error has occurred. Return an error code. */
54507  return rc;
54508}
54509#endif
54510
54511/*
54512** Return the pager associated with a BTree.  This routine is used for
54513** testing and debugging only.
54514*/
54515SQLITE_PRIVATE Pager *sqlite3BtreePager(Btree *p){
54516  return p->pBt->pPager;
54517}
54518
54519#ifndef SQLITE_OMIT_INTEGRITY_CHECK
54520/*
54521** Append a message to the error message string.
54522*/
54523static void checkAppendMsg(
54524  IntegrityCk *pCheck,
54525  char *zMsg1,
54526  const char *zFormat,
54527  ...
54528){
54529  va_list ap;
54530  if( !pCheck->mxErr ) return;
54531  pCheck->mxErr--;
54532  pCheck->nErr++;
54533  va_start(ap, zFormat);
54534  if( pCheck->errMsg.nChar ){
54535    sqlite3StrAccumAppend(&pCheck->errMsg, "\n", 1);
54536  }
54537  if( zMsg1 ){
54538    sqlite3StrAccumAppend(&pCheck->errMsg, zMsg1, -1);
54539  }
54540  sqlite3VXPrintf(&pCheck->errMsg, 1, zFormat, ap);
54541  va_end(ap);
54542  if( pCheck->errMsg.mallocFailed ){
54543    pCheck->mallocFailed = 1;
54544  }
54545}
54546#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
54547
54548#ifndef SQLITE_OMIT_INTEGRITY_CHECK
54549/*
54550** Add 1 to the reference count for page iPage.  If this is the second
54551** reference to the page, add an error message to pCheck->zErrMsg.
54552** Return 1 if there are 2 ore more references to the page and 0 if
54553** if this is the first reference to the page.
54554**
54555** Also check that the page number is in bounds.
54556*/
54557static int checkRef(IntegrityCk *pCheck, Pgno iPage, char *zContext){
54558  if( iPage==0 ) return 1;
54559  if( iPage>pCheck->nPage ){
54560    checkAppendMsg(pCheck, zContext, "invalid page number %d", iPage);
54561    return 1;
54562  }
54563  if( pCheck->anRef[iPage]==1 ){
54564    checkAppendMsg(pCheck, zContext, "2nd reference to page %d", iPage);
54565    return 1;
54566  }
54567  return  (pCheck->anRef[iPage]++)>1;
54568}
54569
54570#ifndef SQLITE_OMIT_AUTOVACUUM
54571/*
54572** Check that the entry in the pointer-map for page iChild maps to
54573** page iParent, pointer type ptrType. If not, append an error message
54574** to pCheck.
54575*/
54576static void checkPtrmap(
54577  IntegrityCk *pCheck,   /* Integrity check context */
54578  Pgno iChild,           /* Child page number */
54579  u8 eType,              /* Expected pointer map type */
54580  Pgno iParent,          /* Expected pointer map parent page number */
54581  char *zContext         /* Context description (used for error msg) */
54582){
54583  int rc;
54584  u8 ePtrmapType;
54585  Pgno iPtrmapParent;
54586
54587  rc = ptrmapGet(pCheck->pBt, iChild, &ePtrmapType, &iPtrmapParent);
54588  if( rc!=SQLITE_OK ){
54589    if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ) pCheck->mallocFailed = 1;
54590    checkAppendMsg(pCheck, zContext, "Failed to read ptrmap key=%d", iChild);
54591    return;
54592  }
54593
54594  if( ePtrmapType!=eType || iPtrmapParent!=iParent ){
54595    checkAppendMsg(pCheck, zContext,
54596      "Bad ptr map entry key=%d expected=(%d,%d) got=(%d,%d)",
54597      iChild, eType, iParent, ePtrmapType, iPtrmapParent);
54598  }
54599}
54600#endif
54601
54602/*
54603** Check the integrity of the freelist or of an overflow page list.
54604** Verify that the number of pages on the list is N.
54605*/
54606static void checkList(
54607  IntegrityCk *pCheck,  /* Integrity checking context */
54608  int isFreeList,       /* True for a freelist.  False for overflow page list */
54609  int iPage,            /* Page number for first page in the list */
54610  int N,                /* Expected number of pages in the list */
54611  char *zContext        /* Context for error messages */
54612){
54613  int i;
54614  int expected = N;
54615  int iFirst = iPage;
54616  while( N-- > 0 && pCheck->mxErr ){
54617    DbPage *pOvflPage;
54618    unsigned char *pOvflData;
54619    if( iPage<1 ){
54620      checkAppendMsg(pCheck, zContext,
54621         "%d of %d pages missing from overflow list starting at %d",
54622          N+1, expected, iFirst);
54623      break;
54624    }
54625    if( checkRef(pCheck, iPage, zContext) ) break;
54626    if( sqlite3PagerGet(pCheck->pPager, (Pgno)iPage, &pOvflPage) ){
54627      checkAppendMsg(pCheck, zContext, "failed to get page %d", iPage);
54628      break;
54629    }
54630    pOvflData = (unsigned char *)sqlite3PagerGetData(pOvflPage);
54631    if( isFreeList ){
54632      int n = get4byte(&pOvflData[4]);
54633#ifndef SQLITE_OMIT_AUTOVACUUM
54634      if( pCheck->pBt->autoVacuum ){
54635        checkPtrmap(pCheck, iPage, PTRMAP_FREEPAGE, 0, zContext);
54636      }
54637#endif
54638      if( n>(int)pCheck->pBt->usableSize/4-2 ){
54639        checkAppendMsg(pCheck, zContext,
54640           "freelist leaf count too big on page %d", iPage);
54641        N--;
54642      }else{
54643        for(i=0; i<n; i++){
54644          Pgno iFreePage = get4byte(&pOvflData[8+i*4]);
54645#ifndef SQLITE_OMIT_AUTOVACUUM
54646          if( pCheck->pBt->autoVacuum ){
54647            checkPtrmap(pCheck, iFreePage, PTRMAP_FREEPAGE, 0, zContext);
54648          }
54649#endif
54650          checkRef(pCheck, iFreePage, zContext);
54651        }
54652        N -= n;
54653      }
54654    }
54655#ifndef SQLITE_OMIT_AUTOVACUUM
54656    else{
54657      /* If this database supports auto-vacuum and iPage is not the last
54658      ** page in this overflow list, check that the pointer-map entry for
54659      ** the following page matches iPage.
54660      */
54661      if( pCheck->pBt->autoVacuum && N>0 ){
54662        i = get4byte(pOvflData);
54663        checkPtrmap(pCheck, i, PTRMAP_OVERFLOW2, iPage, zContext);
54664      }
54665    }
54666#endif
54667    iPage = get4byte(pOvflData);
54668    sqlite3PagerUnref(pOvflPage);
54669  }
54670}
54671#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
54672
54673#ifndef SQLITE_OMIT_INTEGRITY_CHECK
54674/*
54675** Do various sanity checks on a single page of a tree.  Return
54676** the tree depth.  Root pages return 0.  Parents of root pages
54677** return 1, and so forth.
54678**
54679** These checks are done:
54680**
54681**      1.  Make sure that cells and freeblocks do not overlap
54682**          but combine to completely cover the page.
54683**  NO  2.  Make sure cell keys are in order.
54684**  NO  3.  Make sure no key is less than or equal to zLowerBound.
54685**  NO  4.  Make sure no key is greater than or equal to zUpperBound.
54686**      5.  Check the integrity of overflow pages.
54687**      6.  Recursively call checkTreePage on all children.
54688**      7.  Verify that the depth of all children is the same.
54689**      8.  Make sure this page is at least 33% full or else it is
54690**          the root of the tree.
54691*/
54692static int checkTreePage(
54693  IntegrityCk *pCheck,  /* Context for the sanity check */
54694  int iPage,            /* Page number of the page to check */
54695  char *zParentContext, /* Parent context */
54696  i64 *pnParentMinKey,
54697  i64 *pnParentMaxKey
54698){
54699  MemPage *pPage;
54700  int i, rc, depth, d2, pgno, cnt;
54701  int hdr, cellStart;
54702  int nCell;
54703  u8 *data;
54704  BtShared *pBt;
54705  int usableSize;
54706  char zContext[100];
54707  char *hit = 0;
54708  i64 nMinKey = 0;
54709  i64 nMaxKey = 0;
54710
54711  sqlite3_snprintf(sizeof(zContext), zContext, "Page %d: ", iPage);
54712
54713  /* Check that the page exists
54714  */
54715  pBt = pCheck->pBt;
54716  usableSize = pBt->usableSize;
54717  if( iPage==0 ) return 0;
54718  if( checkRef(pCheck, iPage, zParentContext) ) return 0;
54719  if( (rc = btreeGetPage(pBt, (Pgno)iPage, &pPage, 0))!=0 ){
54720    checkAppendMsg(pCheck, zContext,
54721       "unable to get the page. error code=%d", rc);
54722    return 0;
54723  }
54724
54725  /* Clear MemPage.isInit to make sure the corruption detection code in
54726  ** btreeInitPage() is executed.  */
54727  pPage->isInit = 0;
54728  if( (rc = btreeInitPage(pPage))!=0 ){
54729    assert( rc==SQLITE_CORRUPT );  /* The only possible error from InitPage */
54730    checkAppendMsg(pCheck, zContext,
54731                   "btreeInitPage() returns error code %d", rc);
54732    releasePage(pPage);
54733    return 0;
54734  }
54735
54736  /* Check out all the cells.
54737  */
54738  depth = 0;
54739  for(i=0; i<pPage->nCell && pCheck->mxErr; i++){
54740    u8 *pCell;
54741    u32 sz;
54742    CellInfo info;
54743
54744    /* Check payload overflow pages
54745    */
54746    sqlite3_snprintf(sizeof(zContext), zContext,
54747             "On tree page %d cell %d: ", iPage, i);
54748    pCell = findCell(pPage,i);
54749    btreeParseCellPtr(pPage, pCell, &info);
54750    sz = info.nData;
54751    if( !pPage->intKey ) sz += (int)info.nKey;
54752    /* For intKey pages, check that the keys are in order.
54753    */
54754    else if( i==0 ) nMinKey = nMaxKey = info.nKey;
54755    else{
54756      if( info.nKey <= nMaxKey ){
54757        checkAppendMsg(pCheck, zContext,
54758            "Rowid %lld out of order (previous was %lld)", info.nKey, nMaxKey);
54759      }
54760      nMaxKey = info.nKey;
54761    }
54762    assert( sz==info.nPayload );
54763    if( (sz>info.nLocal)
54764     && (&pCell[info.iOverflow]<=&pPage->aData[pBt->usableSize])
54765    ){
54766      int nPage = (sz - info.nLocal + usableSize - 5)/(usableSize - 4);
54767      Pgno pgnoOvfl = get4byte(&pCell[info.iOverflow]);
54768#ifndef SQLITE_OMIT_AUTOVACUUM
54769      if( pBt->autoVacuum ){
54770        checkPtrmap(pCheck, pgnoOvfl, PTRMAP_OVERFLOW1, iPage, zContext);
54771      }
54772#endif
54773      checkList(pCheck, 0, pgnoOvfl, nPage, zContext);
54774    }
54775
54776    /* Check sanity of left child page.
54777    */
54778    if( !pPage->leaf ){
54779      pgno = get4byte(pCell);
54780#ifndef SQLITE_OMIT_AUTOVACUUM
54781      if( pBt->autoVacuum ){
54782        checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage, zContext);
54783      }
54784#endif
54785      d2 = checkTreePage(pCheck, pgno, zContext, &nMinKey, i==0 ? NULL : &nMaxKey);
54786      if( i>0 && d2!=depth ){
54787        checkAppendMsg(pCheck, zContext, "Child page depth differs");
54788      }
54789      depth = d2;
54790    }
54791  }
54792
54793  if( !pPage->leaf ){
54794    pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
54795    sqlite3_snprintf(sizeof(zContext), zContext,
54796                     "On page %d at right child: ", iPage);
54797#ifndef SQLITE_OMIT_AUTOVACUUM
54798    if( pBt->autoVacuum ){
54799      checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage, zContext);
54800    }
54801#endif
54802    checkTreePage(pCheck, pgno, zContext, NULL, !pPage->nCell ? NULL : &nMaxKey);
54803  }
54804
54805  /* For intKey leaf pages, check that the min/max keys are in order
54806  ** with any left/parent/right pages.
54807  */
54808  if( pPage->leaf && pPage->intKey ){
54809    /* if we are a left child page */
54810    if( pnParentMinKey ){
54811      /* if we are the left most child page */
54812      if( !pnParentMaxKey ){
54813        if( nMaxKey > *pnParentMinKey ){
54814          checkAppendMsg(pCheck, zContext,
54815              "Rowid %lld out of order (max larger than parent min of %lld)",
54816              nMaxKey, *pnParentMinKey);
54817        }
54818      }else{
54819        if( nMinKey <= *pnParentMinKey ){
54820          checkAppendMsg(pCheck, zContext,
54821              "Rowid %lld out of order (min less than parent min of %lld)",
54822              nMinKey, *pnParentMinKey);
54823        }
54824        if( nMaxKey > *pnParentMaxKey ){
54825          checkAppendMsg(pCheck, zContext,
54826              "Rowid %lld out of order (max larger than parent max of %lld)",
54827              nMaxKey, *pnParentMaxKey);
54828        }
54829        *pnParentMinKey = nMaxKey;
54830      }
54831    /* else if we're a right child page */
54832    } else if( pnParentMaxKey ){
54833      if( nMinKey <= *pnParentMaxKey ){
54834        checkAppendMsg(pCheck, zContext,
54835            "Rowid %lld out of order (min less than parent max of %lld)",
54836            nMinKey, *pnParentMaxKey);
54837      }
54838    }
54839  }
54840
54841  /* Check for complete coverage of the page
54842  */
54843  data = pPage->aData;
54844  hdr = pPage->hdrOffset;
54845  hit = sqlite3PageMalloc( pBt->pageSize );
54846  if( hit==0 ){
54847    pCheck->mallocFailed = 1;
54848  }else{
54849    int contentOffset = get2byteNotZero(&data[hdr+5]);
54850    assert( contentOffset<=usableSize );  /* Enforced by btreeInitPage() */
54851    memset(hit+contentOffset, 0, usableSize-contentOffset);
54852    memset(hit, 1, contentOffset);
54853    nCell = get2byte(&data[hdr+3]);
54854    cellStart = hdr + 12 - 4*pPage->leaf;
54855    for(i=0; i<nCell; i++){
54856      int pc = get2byte(&data[cellStart+i*2]);
54857      u32 size = 65536;
54858      int j;
54859      if( pc<=usableSize-4 ){
54860        size = cellSizePtr(pPage, &data[pc]);
54861      }
54862      if( (int)(pc+size-1)>=usableSize ){
54863        checkAppendMsg(pCheck, 0,
54864            "Corruption detected in cell %d on page %d",i,iPage);
54865      }else{
54866        for(j=pc+size-1; j>=pc; j--) hit[j]++;
54867      }
54868    }
54869    i = get2byte(&data[hdr+1]);
54870    while( i>0 ){
54871      int size, j;
54872      assert( i<=usableSize-4 );     /* Enforced by btreeInitPage() */
54873      size = get2byte(&data[i+2]);
54874      assert( i+size<=usableSize );  /* Enforced by btreeInitPage() */
54875      for(j=i+size-1; j>=i; j--) hit[j]++;
54876      j = get2byte(&data[i]);
54877      assert( j==0 || j>i+size );  /* Enforced by btreeInitPage() */
54878      assert( j<=usableSize-4 );   /* Enforced by btreeInitPage() */
54879      i = j;
54880    }
54881    for(i=cnt=0; i<usableSize; i++){
54882      if( hit[i]==0 ){
54883        cnt++;
54884      }else if( hit[i]>1 ){
54885        checkAppendMsg(pCheck, 0,
54886          "Multiple uses for byte %d of page %d", i, iPage);
54887        break;
54888      }
54889    }
54890    if( cnt!=data[hdr+7] ){
54891      checkAppendMsg(pCheck, 0,
54892          "Fragmentation of %d bytes reported as %d on page %d",
54893          cnt, data[hdr+7], iPage);
54894    }
54895  }
54896  sqlite3PageFree(hit);
54897  releasePage(pPage);
54898  return depth+1;
54899}
54900#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
54901
54902#ifndef SQLITE_OMIT_INTEGRITY_CHECK
54903/*
54904** This routine does a complete check of the given BTree file.  aRoot[] is
54905** an array of pages numbers were each page number is the root page of
54906** a table.  nRoot is the number of entries in aRoot.
54907**
54908** A read-only or read-write transaction must be opened before calling
54909** this function.
54910**
54911** Write the number of error seen in *pnErr.  Except for some memory
54912** allocation errors,  an error message held in memory obtained from
54913** malloc is returned if *pnErr is non-zero.  If *pnErr==0 then NULL is
54914** returned.  If a memory allocation error occurs, NULL is returned.
54915*/
54916SQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck(
54917  Btree *p,     /* The btree to be checked */
54918  int *aRoot,   /* An array of root pages numbers for individual trees */
54919  int nRoot,    /* Number of entries in aRoot[] */
54920  int mxErr,    /* Stop reporting errors after this many */
54921  int *pnErr    /* Write number of errors seen to this variable */
54922){
54923  Pgno i;
54924  int nRef;
54925  IntegrityCk sCheck;
54926  BtShared *pBt = p->pBt;
54927  char zErr[100];
54928
54929  sqlite3BtreeEnter(p);
54930  assert( p->inTrans>TRANS_NONE && pBt->inTransaction>TRANS_NONE );
54931  nRef = sqlite3PagerRefcount(pBt->pPager);
54932  sCheck.pBt = pBt;
54933  sCheck.pPager = pBt->pPager;
54934  sCheck.nPage = btreePagecount(sCheck.pBt);
54935  sCheck.mxErr = mxErr;
54936  sCheck.nErr = 0;
54937  sCheck.mallocFailed = 0;
54938  *pnErr = 0;
54939  if( sCheck.nPage==0 ){
54940    sqlite3BtreeLeave(p);
54941    return 0;
54942  }
54943  sCheck.anRef = sqlite3Malloc( (sCheck.nPage+1)*sizeof(sCheck.anRef[0]) );
54944  if( !sCheck.anRef ){
54945    *pnErr = 1;
54946    sqlite3BtreeLeave(p);
54947    return 0;
54948  }
54949  for(i=0; i<=sCheck.nPage; i++){ sCheck.anRef[i] = 0; }
54950  i = PENDING_BYTE_PAGE(pBt);
54951  if( i<=sCheck.nPage ){
54952    sCheck.anRef[i] = 1;
54953  }
54954  sqlite3StrAccumInit(&sCheck.errMsg, zErr, sizeof(zErr), 20000);
54955  sCheck.errMsg.useMalloc = 2;
54956
54957  /* Check the integrity of the freelist
54958  */
54959  checkList(&sCheck, 1, get4byte(&pBt->pPage1->aData[32]),
54960            get4byte(&pBt->pPage1->aData[36]), "Main freelist: ");
54961
54962  /* Check all the tables.
54963  */
54964  for(i=0; (int)i<nRoot && sCheck.mxErr; i++){
54965    if( aRoot[i]==0 ) continue;
54966#ifndef SQLITE_OMIT_AUTOVACUUM
54967    if( pBt->autoVacuum && aRoot[i]>1 ){
54968      checkPtrmap(&sCheck, aRoot[i], PTRMAP_ROOTPAGE, 0, 0);
54969    }
54970#endif
54971    checkTreePage(&sCheck, aRoot[i], "List of tree roots: ", NULL, NULL);
54972  }
54973
54974  /* Make sure every page in the file is referenced
54975  */
54976  for(i=1; i<=sCheck.nPage && sCheck.mxErr; i++){
54977#ifdef SQLITE_OMIT_AUTOVACUUM
54978    if( sCheck.anRef[i]==0 ){
54979      checkAppendMsg(&sCheck, 0, "Page %d is never used", i);
54980    }
54981#else
54982    /* If the database supports auto-vacuum, make sure no tables contain
54983    ** references to pointer-map pages.
54984    */
54985    if( sCheck.anRef[i]==0 &&
54986       (PTRMAP_PAGENO(pBt, i)!=i || !pBt->autoVacuum) ){
54987      checkAppendMsg(&sCheck, 0, "Page %d is never used", i);
54988    }
54989    if( sCheck.anRef[i]!=0 &&
54990       (PTRMAP_PAGENO(pBt, i)==i && pBt->autoVacuum) ){
54991      checkAppendMsg(&sCheck, 0, "Pointer map page %d is referenced", i);
54992    }
54993#endif
54994  }
54995
54996  /* Make sure this analysis did not leave any unref() pages.
54997  ** This is an internal consistency check; an integrity check
54998  ** of the integrity check.
54999  */
55000  if( NEVER(nRef != sqlite3PagerRefcount(pBt->pPager)) ){
55001    checkAppendMsg(&sCheck, 0,
55002      "Outstanding page count goes from %d to %d during this analysis",
55003      nRef, sqlite3PagerRefcount(pBt->pPager)
55004    );
55005  }
55006
55007  /* Clean  up and report errors.
55008  */
55009  sqlite3BtreeLeave(p);
55010  sqlite3_free(sCheck.anRef);
55011  if( sCheck.mallocFailed ){
55012    sqlite3StrAccumReset(&sCheck.errMsg);
55013    *pnErr = sCheck.nErr+1;
55014    return 0;
55015  }
55016  *pnErr = sCheck.nErr;
55017  if( sCheck.nErr==0 ) sqlite3StrAccumReset(&sCheck.errMsg);
55018  return sqlite3StrAccumFinish(&sCheck.errMsg);
55019}
55020#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
55021
55022/*
55023** Return the full pathname of the underlying database file.
55024**
55025** The pager filename is invariant as long as the pager is
55026** open so it is safe to access without the BtShared mutex.
55027*/
55028SQLITE_PRIVATE const char *sqlite3BtreeGetFilename(Btree *p){
55029  assert( p->pBt->pPager!=0 );
55030  return sqlite3PagerFilename(p->pBt->pPager);
55031}
55032
55033/*
55034** Return the pathname of the journal file for this database. The return
55035** value of this routine is the same regardless of whether the journal file
55036** has been created or not.
55037**
55038** The pager journal filename is invariant as long as the pager is
55039** open so it is safe to access without the BtShared mutex.
55040*/
55041SQLITE_PRIVATE const char *sqlite3BtreeGetJournalname(Btree *p){
55042  assert( p->pBt->pPager!=0 );
55043  return sqlite3PagerJournalname(p->pBt->pPager);
55044}
55045
55046/*
55047** Return non-zero if a transaction is active.
55048*/
55049SQLITE_PRIVATE int sqlite3BtreeIsInTrans(Btree *p){
55050  assert( p==0 || sqlite3_mutex_held(p->db->mutex) );
55051  return (p && (p->inTrans==TRANS_WRITE));
55052}
55053
55054#ifndef SQLITE_OMIT_WAL
55055/*
55056** Run a checkpoint on the Btree passed as the first argument.
55057**
55058** Return SQLITE_LOCKED if this or any other connection has an open
55059** transaction on the shared-cache the argument Btree is connected to.
55060**
55061** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
55062*/
55063SQLITE_PRIVATE int sqlite3BtreeCheckpoint(Btree *p, int eMode, int *pnLog, int *pnCkpt){
55064  int rc = SQLITE_OK;
55065  if( p ){
55066    BtShared *pBt = p->pBt;
55067    sqlite3BtreeEnter(p);
55068    if( pBt->inTransaction!=TRANS_NONE ){
55069      rc = SQLITE_LOCKED;
55070    }else{
55071      rc = sqlite3PagerCheckpoint(pBt->pPager, eMode, pnLog, pnCkpt);
55072    }
55073    sqlite3BtreeLeave(p);
55074  }
55075  return rc;
55076}
55077#endif
55078
55079/*
55080** Return non-zero if a read (or write) transaction is active.
55081*/
55082SQLITE_PRIVATE int sqlite3BtreeIsInReadTrans(Btree *p){
55083  assert( p );
55084  assert( sqlite3_mutex_held(p->db->mutex) );
55085  return p->inTrans!=TRANS_NONE;
55086}
55087
55088SQLITE_PRIVATE int sqlite3BtreeIsInBackup(Btree *p){
55089  assert( p );
55090  assert( sqlite3_mutex_held(p->db->mutex) );
55091  return p->nBackup!=0;
55092}
55093
55094/*
55095** This function returns a pointer to a blob of memory associated with
55096** a single shared-btree. The memory is used by client code for its own
55097** purposes (for example, to store a high-level schema associated with
55098** the shared-btree). The btree layer manages reference counting issues.
55099**
55100** The first time this is called on a shared-btree, nBytes bytes of memory
55101** are allocated, zeroed, and returned to the caller. For each subsequent
55102** call the nBytes parameter is ignored and a pointer to the same blob
55103** of memory returned.
55104**
55105** If the nBytes parameter is 0 and the blob of memory has not yet been
55106** allocated, a null pointer is returned. If the blob has already been
55107** allocated, it is returned as normal.
55108**
55109** Just before the shared-btree is closed, the function passed as the
55110** xFree argument when the memory allocation was made is invoked on the
55111** blob of allocated memory. The xFree function should not call sqlite3_free()
55112** on the memory, the btree layer does that.
55113*/
55114SQLITE_PRIVATE void *sqlite3BtreeSchema(Btree *p, int nBytes, void(*xFree)(void *)){
55115  BtShared *pBt = p->pBt;
55116  sqlite3BtreeEnter(p);
55117  if( !pBt->pSchema && nBytes ){
55118    pBt->pSchema = sqlite3DbMallocZero(0, nBytes);
55119    pBt->xFreeSchema = xFree;
55120  }
55121  sqlite3BtreeLeave(p);
55122  return pBt->pSchema;
55123}
55124
55125/*
55126** Return SQLITE_LOCKED_SHAREDCACHE if another user of the same shared
55127** btree as the argument handle holds an exclusive lock on the
55128** sqlite_master table. Otherwise SQLITE_OK.
55129*/
55130SQLITE_PRIVATE int sqlite3BtreeSchemaLocked(Btree *p){
55131  int rc;
55132  assert( sqlite3_mutex_held(p->db->mutex) );
55133  sqlite3BtreeEnter(p);
55134  rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK);
55135  assert( rc==SQLITE_OK || rc==SQLITE_LOCKED_SHAREDCACHE );
55136  sqlite3BtreeLeave(p);
55137  return rc;
55138}
55139
55140
55141#ifndef SQLITE_OMIT_SHARED_CACHE
55142/*
55143** Obtain a lock on the table whose root page is iTab.  The
55144** lock is a write lock if isWritelock is true or a read lock
55145** if it is false.
55146*/
55147SQLITE_PRIVATE int sqlite3BtreeLockTable(Btree *p, int iTab, u8 isWriteLock){
55148  int rc = SQLITE_OK;
55149  assert( p->inTrans!=TRANS_NONE );
55150  if( p->sharable ){
55151    u8 lockType = READ_LOCK + isWriteLock;
55152    assert( READ_LOCK+1==WRITE_LOCK );
55153    assert( isWriteLock==0 || isWriteLock==1 );
55154
55155    sqlite3BtreeEnter(p);
55156    rc = querySharedCacheTableLock(p, iTab, lockType);
55157    if( rc==SQLITE_OK ){
55158      rc = setSharedCacheTableLock(p, iTab, lockType);
55159    }
55160    sqlite3BtreeLeave(p);
55161  }
55162  return rc;
55163}
55164#endif
55165
55166#ifndef SQLITE_OMIT_INCRBLOB
55167/*
55168** Argument pCsr must be a cursor opened for writing on an
55169** INTKEY table currently pointing at a valid table entry.
55170** This function modifies the data stored as part of that entry.
55171**
55172** Only the data content may only be modified, it is not possible to
55173** change the length of the data stored. If this function is called with
55174** parameters that attempt to write past the end of the existing data,
55175** no modifications are made and SQLITE_CORRUPT is returned.
55176*/
55177SQLITE_PRIVATE int sqlite3BtreePutData(BtCursor *pCsr, u32 offset, u32 amt, void *z){
55178  int rc;
55179  assert( cursorHoldsMutex(pCsr) );
55180  assert( sqlite3_mutex_held(pCsr->pBtree->db->mutex) );
55181  assert( pCsr->isIncrblobHandle );
55182
55183  rc = restoreCursorPosition(pCsr);
55184  if( rc!=SQLITE_OK ){
55185    return rc;
55186  }
55187  assert( pCsr->eState!=CURSOR_REQUIRESEEK );
55188  if( pCsr->eState!=CURSOR_VALID ){
55189    return SQLITE_ABORT;
55190  }
55191
55192  /* Check some assumptions:
55193  **   (a) the cursor is open for writing,
55194  **   (b) there is a read/write transaction open,
55195  **   (c) the connection holds a write-lock on the table (if required),
55196  **   (d) there are no conflicting read-locks, and
55197  **   (e) the cursor points at a valid row of an intKey table.
55198  */
55199  if( !pCsr->wrFlag ){
55200    return SQLITE_READONLY;
55201  }
55202  assert( !pCsr->pBt->readOnly && pCsr->pBt->inTransaction==TRANS_WRITE );
55203  assert( hasSharedCacheTableLock(pCsr->pBtree, pCsr->pgnoRoot, 0, 2) );
55204  assert( !hasReadConflicts(pCsr->pBtree, pCsr->pgnoRoot) );
55205  assert( pCsr->apPage[pCsr->iPage]->intKey );
55206
55207  return accessPayload(pCsr, offset, amt, (unsigned char *)z, 1);
55208}
55209
55210/*
55211** Set a flag on this cursor to cache the locations of pages from the
55212** overflow list for the current row. This is used by cursors opened
55213** for incremental blob IO only.
55214**
55215** This function sets a flag only. The actual page location cache
55216** (stored in BtCursor.aOverflow[]) is allocated and used by function
55217** accessPayload() (the worker function for sqlite3BtreeData() and
55218** sqlite3BtreePutData()).
55219*/
55220SQLITE_PRIVATE void sqlite3BtreeCacheOverflow(BtCursor *pCur){
55221  assert( cursorHoldsMutex(pCur) );
55222  assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
55223  invalidateOverflowCache(pCur);
55224  pCur->isIncrblobHandle = 1;
55225}
55226#endif
55227
55228/*
55229** Set both the "read version" (single byte at byte offset 18) and
55230** "write version" (single byte at byte offset 19) fields in the database
55231** header to iVersion.
55232*/
55233SQLITE_PRIVATE int sqlite3BtreeSetVersion(Btree *pBtree, int iVersion){
55234  BtShared *pBt = pBtree->pBt;
55235  int rc;                         /* Return code */
55236
55237  assert( pBtree->inTrans==TRANS_NONE );
55238  assert( iVersion==1 || iVersion==2 );
55239
55240  /* If setting the version fields to 1, do not automatically open the
55241  ** WAL connection, even if the version fields are currently set to 2.
55242  */
55243  pBt->doNotUseWAL = (u8)(iVersion==1);
55244
55245  rc = sqlite3BtreeBeginTrans(pBtree, 0);
55246  if( rc==SQLITE_OK ){
55247    u8 *aData = pBt->pPage1->aData;
55248    if( aData[18]!=(u8)iVersion || aData[19]!=(u8)iVersion ){
55249      rc = sqlite3BtreeBeginTrans(pBtree, 2);
55250      if( rc==SQLITE_OK ){
55251        rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
55252        if( rc==SQLITE_OK ){
55253          aData[18] = (u8)iVersion;
55254          aData[19] = (u8)iVersion;
55255        }
55256      }
55257    }
55258  }
55259
55260  pBt->doNotUseWAL = 0;
55261  return rc;
55262}
55263
55264/************** End of btree.c ***********************************************/
55265/************** Begin file backup.c ******************************************/
55266/*
55267** 2009 January 28
55268**
55269** The author disclaims copyright to this source code.  In place of
55270** a legal notice, here is a blessing:
55271**
55272**    May you do good and not evil.
55273**    May you find forgiveness for yourself and forgive others.
55274**    May you share freely, never taking more than you give.
55275**
55276*************************************************************************
55277** This file contains the implementation of the sqlite3_backup_XXX()
55278** API functions and the related features.
55279*/
55280
55281/* Macro to find the minimum of two numeric values.
55282*/
55283#ifndef MIN
55284# define MIN(x,y) ((x)<(y)?(x):(y))
55285#endif
55286
55287/*
55288** Structure allocated for each backup operation.
55289*/
55290struct sqlite3_backup {
55291  sqlite3* pDestDb;        /* Destination database handle */
55292  Btree *pDest;            /* Destination b-tree file */
55293  u32 iDestSchema;         /* Original schema cookie in destination */
55294  int bDestLocked;         /* True once a write-transaction is open on pDest */
55295
55296  Pgno iNext;              /* Page number of the next source page to copy */
55297  sqlite3* pSrcDb;         /* Source database handle */
55298  Btree *pSrc;             /* Source b-tree file */
55299
55300  int rc;                  /* Backup process error code */
55301
55302  /* These two variables are set by every call to backup_step(). They are
55303  ** read by calls to backup_remaining() and backup_pagecount().
55304  */
55305  Pgno nRemaining;         /* Number of pages left to copy */
55306  Pgno nPagecount;         /* Total number of pages to copy */
55307
55308  int isAttached;          /* True once backup has been registered with pager */
55309  sqlite3_backup *pNext;   /* Next backup associated with source pager */
55310};
55311
55312/*
55313** THREAD SAFETY NOTES:
55314**
55315**   Once it has been created using backup_init(), a single sqlite3_backup
55316**   structure may be accessed via two groups of thread-safe entry points:
55317**
55318**     * Via the sqlite3_backup_XXX() API function backup_step() and
55319**       backup_finish(). Both these functions obtain the source database
55320**       handle mutex and the mutex associated with the source BtShared
55321**       structure, in that order.
55322**
55323**     * Via the BackupUpdate() and BackupRestart() functions, which are
55324**       invoked by the pager layer to report various state changes in
55325**       the page cache associated with the source database. The mutex
55326**       associated with the source database BtShared structure will always
55327**       be held when either of these functions are invoked.
55328**
55329**   The other sqlite3_backup_XXX() API functions, backup_remaining() and
55330**   backup_pagecount() are not thread-safe functions. If they are called
55331**   while some other thread is calling backup_step() or backup_finish(),
55332**   the values returned may be invalid. There is no way for a call to
55333**   BackupUpdate() or BackupRestart() to interfere with backup_remaining()
55334**   or backup_pagecount().
55335**
55336**   Depending on the SQLite configuration, the database handles and/or
55337**   the Btree objects may have their own mutexes that require locking.
55338**   Non-sharable Btrees (in-memory databases for example), do not have
55339**   associated mutexes.
55340*/
55341
55342/*
55343** Return a pointer corresponding to database zDb (i.e. "main", "temp")
55344** in connection handle pDb. If such a database cannot be found, return
55345** a NULL pointer and write an error message to pErrorDb.
55346**
55347** If the "temp" database is requested, it may need to be opened by this
55348** function. If an error occurs while doing so, return 0 and write an
55349** error message to pErrorDb.
55350*/
55351static Btree *findBtree(sqlite3 *pErrorDb, sqlite3 *pDb, const char *zDb){
55352  int i = sqlite3FindDbName(pDb, zDb);
55353
55354  if( i==1 ){
55355    Parse *pParse;
55356    int rc = 0;
55357    pParse = sqlite3StackAllocZero(pErrorDb, sizeof(*pParse));
55358    if( pParse==0 ){
55359      sqlite3Error(pErrorDb, SQLITE_NOMEM, "out of memory");
55360      rc = SQLITE_NOMEM;
55361    }else{
55362      pParse->db = pDb;
55363      if( sqlite3OpenTempDatabase(pParse) ){
55364        sqlite3Error(pErrorDb, pParse->rc, "%s", pParse->zErrMsg);
55365        rc = SQLITE_ERROR;
55366      }
55367      sqlite3DbFree(pErrorDb, pParse->zErrMsg);
55368      sqlite3StackFree(pErrorDb, pParse);
55369    }
55370    if( rc ){
55371      return 0;
55372    }
55373  }
55374
55375  if( i<0 ){
55376    sqlite3Error(pErrorDb, SQLITE_ERROR, "unknown database %s", zDb);
55377    return 0;
55378  }
55379
55380  return pDb->aDb[i].pBt;
55381}
55382
55383/*
55384** Attempt to set the page size of the destination to match the page size
55385** of the source.
55386*/
55387static int setDestPgsz(sqlite3_backup *p){
55388  int rc;
55389  rc = sqlite3BtreeSetPageSize(p->pDest,sqlite3BtreeGetPageSize(p->pSrc),-1,0);
55390  return rc;
55391}
55392
55393/*
55394** Create an sqlite3_backup process to copy the contents of zSrcDb from
55395** connection handle pSrcDb to zDestDb in pDestDb. If successful, return
55396** a pointer to the new sqlite3_backup object.
55397**
55398** If an error occurs, NULL is returned and an error code and error message
55399** stored in database handle pDestDb.
55400*/
55401SQLITE_API sqlite3_backup *sqlite3_backup_init(
55402  sqlite3* pDestDb,                     /* Database to write to */
55403  const char *zDestDb,                  /* Name of database within pDestDb */
55404  sqlite3* pSrcDb,                      /* Database connection to read from */
55405  const char *zSrcDb                    /* Name of database within pSrcDb */
55406){
55407  sqlite3_backup *p;                    /* Value to return */
55408
55409  /* Lock the source database handle. The destination database
55410  ** handle is not locked in this routine, but it is locked in
55411  ** sqlite3_backup_step(). The user is required to ensure that no
55412  ** other thread accesses the destination handle for the duration
55413  ** of the backup operation.  Any attempt to use the destination
55414  ** database connection while a backup is in progress may cause
55415  ** a malfunction or a deadlock.
55416  */
55417  sqlite3_mutex_enter(pSrcDb->mutex);
55418  sqlite3_mutex_enter(pDestDb->mutex);
55419
55420  if( pSrcDb==pDestDb ){
55421    sqlite3Error(
55422        pDestDb, SQLITE_ERROR, "source and destination must be distinct"
55423    );
55424    p = 0;
55425  }else {
55426    /* Allocate space for a new sqlite3_backup object...
55427    ** EVIDENCE-OF: R-64852-21591 The sqlite3_backup object is created by a
55428    ** call to sqlite3_backup_init() and is destroyed by a call to
55429    ** sqlite3_backup_finish(). */
55430    p = (sqlite3_backup *)sqlite3_malloc(sizeof(sqlite3_backup));
55431    if( !p ){
55432      sqlite3Error(pDestDb, SQLITE_NOMEM, 0);
55433    }
55434  }
55435
55436  /* If the allocation succeeded, populate the new object. */
55437  if( p ){
55438    memset(p, 0, sizeof(sqlite3_backup));
55439    p->pSrc = findBtree(pDestDb, pSrcDb, zSrcDb);
55440    p->pDest = findBtree(pDestDb, pDestDb, zDestDb);
55441    p->pDestDb = pDestDb;
55442    p->pSrcDb = pSrcDb;
55443    p->iNext = 1;
55444    p->isAttached = 0;
55445
55446    if( 0==p->pSrc || 0==p->pDest || setDestPgsz(p)==SQLITE_NOMEM ){
55447      /* One (or both) of the named databases did not exist or an OOM
55448      ** error was hit.  The error has already been written into the
55449      ** pDestDb handle.  All that is left to do here is free the
55450      ** sqlite3_backup structure.
55451      */
55452      sqlite3_free(p);
55453      p = 0;
55454    }
55455  }
55456  if( p ){
55457    p->pSrc->nBackup++;
55458  }
55459
55460  sqlite3_mutex_leave(pDestDb->mutex);
55461  sqlite3_mutex_leave(pSrcDb->mutex);
55462  return p;
55463}
55464
55465/*
55466** Argument rc is an SQLite error code. Return true if this error is
55467** considered fatal if encountered during a backup operation. All errors
55468** are considered fatal except for SQLITE_BUSY and SQLITE_LOCKED.
55469*/
55470static int isFatalError(int rc){
55471  return (rc!=SQLITE_OK && rc!=SQLITE_BUSY && ALWAYS(rc!=SQLITE_LOCKED));
55472}
55473
55474/*
55475** Parameter zSrcData points to a buffer containing the data for
55476** page iSrcPg from the source database. Copy this data into the
55477** destination database.
55478*/
55479static int backupOnePage(sqlite3_backup *p, Pgno iSrcPg, const u8 *zSrcData){
55480  Pager * const pDestPager = sqlite3BtreePager(p->pDest);
55481  const int nSrcPgsz = sqlite3BtreeGetPageSize(p->pSrc);
55482  int nDestPgsz = sqlite3BtreeGetPageSize(p->pDest);
55483  const int nCopy = MIN(nSrcPgsz, nDestPgsz);
55484  const i64 iEnd = (i64)iSrcPg*(i64)nSrcPgsz;
55485#ifdef SQLITE_HAS_CODEC
55486  int nSrcReserve = sqlite3BtreeGetReserve(p->pSrc);
55487  int nDestReserve = sqlite3BtreeGetReserve(p->pDest);
55488#endif
55489
55490  int rc = SQLITE_OK;
55491  i64 iOff;
55492
55493  assert( p->bDestLocked );
55494  assert( !isFatalError(p->rc) );
55495  assert( iSrcPg!=PENDING_BYTE_PAGE(p->pSrc->pBt) );
55496  assert( zSrcData );
55497
55498  /* Catch the case where the destination is an in-memory database and the
55499  ** page sizes of the source and destination differ.
55500  */
55501  if( nSrcPgsz!=nDestPgsz && sqlite3PagerIsMemdb(pDestPager) ){
55502    rc = SQLITE_READONLY;
55503  }
55504
55505#ifdef SQLITE_HAS_CODEC
55506  /* Backup is not possible if the page size of the destination is changing
55507  ** and a codec is in use.
55508  */
55509  if( nSrcPgsz!=nDestPgsz && sqlite3PagerGetCodec(pDestPager)!=0 ){
55510    rc = SQLITE_READONLY;
55511  }
55512
55513  /* Backup is not possible if the number of bytes of reserve space differ
55514  ** between source and destination.  If there is a difference, try to
55515  ** fix the destination to agree with the source.  If that is not possible,
55516  ** then the backup cannot proceed.
55517  */
55518  if( nSrcReserve!=nDestReserve ){
55519    u32 newPgsz = nSrcPgsz;
55520    rc = sqlite3PagerSetPagesize(pDestPager, &newPgsz, nSrcReserve);
55521    if( rc==SQLITE_OK && newPgsz!=nSrcPgsz ) rc = SQLITE_READONLY;
55522  }
55523#endif
55524
55525  /* This loop runs once for each destination page spanned by the source
55526  ** page. For each iteration, variable iOff is set to the byte offset
55527  ** of the destination page.
55528  */
55529  for(iOff=iEnd-(i64)nSrcPgsz; rc==SQLITE_OK && iOff<iEnd; iOff+=nDestPgsz){
55530    DbPage *pDestPg = 0;
55531    Pgno iDest = (Pgno)(iOff/nDestPgsz)+1;
55532    if( iDest==PENDING_BYTE_PAGE(p->pDest->pBt) ) continue;
55533    if( SQLITE_OK==(rc = sqlite3PagerGet(pDestPager, iDest, &pDestPg))
55534     && SQLITE_OK==(rc = sqlite3PagerWrite(pDestPg))
55535    ){
55536      const u8 *zIn = &zSrcData[iOff%nSrcPgsz];
55537      u8 *zDestData = sqlite3PagerGetData(pDestPg);
55538      u8 *zOut = &zDestData[iOff%nDestPgsz];
55539
55540      /* Copy the data from the source page into the destination page.
55541      ** Then clear the Btree layer MemPage.isInit flag. Both this module
55542      ** and the pager code use this trick (clearing the first byte
55543      ** of the page 'extra' space to invalidate the Btree layers
55544      ** cached parse of the page). MemPage.isInit is marked
55545      ** "MUST BE FIRST" for this purpose.
55546      */
55547      memcpy(zOut, zIn, nCopy);
55548      ((u8 *)sqlite3PagerGetExtra(pDestPg))[0] = 0;
55549    }
55550    sqlite3PagerUnref(pDestPg);
55551  }
55552
55553  return rc;
55554}
55555
55556/*
55557** If pFile is currently larger than iSize bytes, then truncate it to
55558** exactly iSize bytes. If pFile is not larger than iSize bytes, then
55559** this function is a no-op.
55560**
55561** Return SQLITE_OK if everything is successful, or an SQLite error
55562** code if an error occurs.
55563*/
55564static int backupTruncateFile(sqlite3_file *pFile, i64 iSize){
55565  i64 iCurrent;
55566  int rc = sqlite3OsFileSize(pFile, &iCurrent);
55567  if( rc==SQLITE_OK && iCurrent>iSize ){
55568    rc = sqlite3OsTruncate(pFile, iSize);
55569  }
55570  return rc;
55571}
55572
55573/*
55574** Register this backup object with the associated source pager for
55575** callbacks when pages are changed or the cache invalidated.
55576*/
55577static void attachBackupObject(sqlite3_backup *p){
55578  sqlite3_backup **pp;
55579  assert( sqlite3BtreeHoldsMutex(p->pSrc) );
55580  pp = sqlite3PagerBackupPtr(sqlite3BtreePager(p->pSrc));
55581  p->pNext = *pp;
55582  *pp = p;
55583  p->isAttached = 1;
55584}
55585
55586/*
55587** Copy nPage pages from the source b-tree to the destination.
55588*/
55589SQLITE_API int sqlite3_backup_step(sqlite3_backup *p, int nPage){
55590  int rc;
55591  int destMode;       /* Destination journal mode */
55592  int pgszSrc = 0;    /* Source page size */
55593  int pgszDest = 0;   /* Destination page size */
55594
55595  sqlite3_mutex_enter(p->pSrcDb->mutex);
55596  sqlite3BtreeEnter(p->pSrc);
55597  if( p->pDestDb ){
55598    sqlite3_mutex_enter(p->pDestDb->mutex);
55599  }
55600
55601  rc = p->rc;
55602  if( !isFatalError(rc) ){
55603    Pager * const pSrcPager = sqlite3BtreePager(p->pSrc);     /* Source pager */
55604    Pager * const pDestPager = sqlite3BtreePager(p->pDest);   /* Dest pager */
55605    int ii;                            /* Iterator variable */
55606    int nSrcPage = -1;                 /* Size of source db in pages */
55607    int bCloseTrans = 0;               /* True if src db requires unlocking */
55608
55609    /* If the source pager is currently in a write-transaction, return
55610    ** SQLITE_BUSY immediately.
55611    */
55612    if( p->pDestDb && p->pSrc->pBt->inTransaction==TRANS_WRITE ){
55613      rc = SQLITE_BUSY;
55614    }else{
55615      rc = SQLITE_OK;
55616    }
55617
55618    /* Lock the destination database, if it is not locked already. */
55619    if( SQLITE_OK==rc && p->bDestLocked==0
55620     && SQLITE_OK==(rc = sqlite3BtreeBeginTrans(p->pDest, 2))
55621    ){
55622      p->bDestLocked = 1;
55623      sqlite3BtreeGetMeta(p->pDest, BTREE_SCHEMA_VERSION, &p->iDestSchema);
55624    }
55625
55626    /* If there is no open read-transaction on the source database, open
55627    ** one now. If a transaction is opened here, then it will be closed
55628    ** before this function exits.
55629    */
55630    if( rc==SQLITE_OK && 0==sqlite3BtreeIsInReadTrans(p->pSrc) ){
55631      rc = sqlite3BtreeBeginTrans(p->pSrc, 0);
55632      bCloseTrans = 1;
55633    }
55634
55635    /* Do not allow backup if the destination database is in WAL mode
55636    ** and the page sizes are different between source and destination */
55637    pgszSrc = sqlite3BtreeGetPageSize(p->pSrc);
55638    pgszDest = sqlite3BtreeGetPageSize(p->pDest);
55639    destMode = sqlite3PagerGetJournalMode(sqlite3BtreePager(p->pDest));
55640    if( SQLITE_OK==rc && destMode==PAGER_JOURNALMODE_WAL && pgszSrc!=pgszDest ){
55641      rc = SQLITE_READONLY;
55642    }
55643
55644    /* Now that there is a read-lock on the source database, query the
55645    ** source pager for the number of pages in the database.
55646    */
55647    nSrcPage = (int)sqlite3BtreeLastPage(p->pSrc);
55648    assert( nSrcPage>=0 );
55649    for(ii=0; (nPage<0 || ii<nPage) && p->iNext<=(Pgno)nSrcPage && !rc; ii++){
55650      const Pgno iSrcPg = p->iNext;                 /* Source page number */
55651      if( iSrcPg!=PENDING_BYTE_PAGE(p->pSrc->pBt) ){
55652        DbPage *pSrcPg;                             /* Source page object */
55653        rc = sqlite3PagerGet(pSrcPager, iSrcPg, &pSrcPg);
55654        if( rc==SQLITE_OK ){
55655          rc = backupOnePage(p, iSrcPg, sqlite3PagerGetData(pSrcPg));
55656          sqlite3PagerUnref(pSrcPg);
55657        }
55658      }
55659      p->iNext++;
55660    }
55661    if( rc==SQLITE_OK ){
55662      p->nPagecount = nSrcPage;
55663      p->nRemaining = nSrcPage+1-p->iNext;
55664      if( p->iNext>(Pgno)nSrcPage ){
55665        rc = SQLITE_DONE;
55666      }else if( !p->isAttached ){
55667        attachBackupObject(p);
55668      }
55669    }
55670
55671    /* Update the schema version field in the destination database. This
55672    ** is to make sure that the schema-version really does change in
55673    ** the case where the source and destination databases have the
55674    ** same schema version.
55675    */
55676    if( rc==SQLITE_DONE
55677     && (rc = sqlite3BtreeUpdateMeta(p->pDest,1,p->iDestSchema+1))==SQLITE_OK
55678    ){
55679      int nDestTruncate;
55680
55681      if( p->pDestDb ){
55682        sqlite3ResetInternalSchema(p->pDestDb, -1);
55683      }
55684
55685      /* Set nDestTruncate to the final number of pages in the destination
55686      ** database. The complication here is that the destination page
55687      ** size may be different to the source page size.
55688      **
55689      ** If the source page size is smaller than the destination page size,
55690      ** round up. In this case the call to sqlite3OsTruncate() below will
55691      ** fix the size of the file. However it is important to call
55692      ** sqlite3PagerTruncateImage() here so that any pages in the
55693      ** destination file that lie beyond the nDestTruncate page mark are
55694      ** journalled by PagerCommitPhaseOne() before they are destroyed
55695      ** by the file truncation.
55696      */
55697      assert( pgszSrc==sqlite3BtreeGetPageSize(p->pSrc) );
55698      assert( pgszDest==sqlite3BtreeGetPageSize(p->pDest) );
55699      if( pgszSrc<pgszDest ){
55700        int ratio = pgszDest/pgszSrc;
55701        nDestTruncate = (nSrcPage+ratio-1)/ratio;
55702        if( nDestTruncate==(int)PENDING_BYTE_PAGE(p->pDest->pBt) ){
55703          nDestTruncate--;
55704        }
55705      }else{
55706        nDestTruncate = nSrcPage * (pgszSrc/pgszDest);
55707      }
55708      sqlite3PagerTruncateImage(pDestPager, nDestTruncate);
55709
55710      if( pgszSrc<pgszDest ){
55711        /* If the source page-size is smaller than the destination page-size,
55712        ** two extra things may need to happen:
55713        **
55714        **   * The destination may need to be truncated, and
55715        **
55716        **   * Data stored on the pages immediately following the
55717        **     pending-byte page in the source database may need to be
55718        **     copied into the destination database.
55719        */
55720        const i64 iSize = (i64)pgszSrc * (i64)nSrcPage;
55721        sqlite3_file * const pFile = sqlite3PagerFile(pDestPager);
55722        i64 iOff;
55723        i64 iEnd;
55724
55725        assert( pFile );
55726        assert( (i64)nDestTruncate*(i64)pgszDest >= iSize || (
55727              nDestTruncate==(int)(PENDING_BYTE_PAGE(p->pDest->pBt)-1)
55728           && iSize>=PENDING_BYTE && iSize<=PENDING_BYTE+pgszDest
55729        ));
55730
55731        /* This call ensures that all data required to recreate the original
55732        ** database has been stored in the journal for pDestPager and the
55733        ** journal synced to disk. So at this point we may safely modify
55734        ** the database file in any way, knowing that if a power failure
55735        ** occurs, the original database will be reconstructed from the
55736        ** journal file.  */
55737        rc = sqlite3PagerCommitPhaseOne(pDestPager, 0, 1);
55738
55739        /* Write the extra pages and truncate the database file as required. */
55740        iEnd = MIN(PENDING_BYTE + pgszDest, iSize);
55741        for(
55742          iOff=PENDING_BYTE+pgszSrc;
55743          rc==SQLITE_OK && iOff<iEnd;
55744          iOff+=pgszSrc
55745        ){
55746          PgHdr *pSrcPg = 0;
55747          const Pgno iSrcPg = (Pgno)((iOff/pgszSrc)+1);
55748          rc = sqlite3PagerGet(pSrcPager, iSrcPg, &pSrcPg);
55749          if( rc==SQLITE_OK ){
55750            u8 *zData = sqlite3PagerGetData(pSrcPg);
55751            rc = sqlite3OsWrite(pFile, zData, pgszSrc, iOff);
55752          }
55753          sqlite3PagerUnref(pSrcPg);
55754        }
55755        if( rc==SQLITE_OK ){
55756          rc = backupTruncateFile(pFile, iSize);
55757        }
55758
55759        /* Sync the database file to disk. */
55760        if( rc==SQLITE_OK ){
55761          rc = sqlite3PagerSync(pDestPager);
55762        }
55763      }else{
55764        rc = sqlite3PagerCommitPhaseOne(pDestPager, 0, 0);
55765      }
55766
55767      /* Finish committing the transaction to the destination database. */
55768      if( SQLITE_OK==rc
55769       && SQLITE_OK==(rc = sqlite3BtreeCommitPhaseTwo(p->pDest, 0))
55770      ){
55771        rc = SQLITE_DONE;
55772      }
55773    }
55774
55775    /* If bCloseTrans is true, then this function opened a read transaction
55776    ** on the source database. Close the read transaction here. There is
55777    ** no need to check the return values of the btree methods here, as
55778    ** "committing" a read-only transaction cannot fail.
55779    */
55780    if( bCloseTrans ){
55781      TESTONLY( int rc2 );
55782      TESTONLY( rc2  = ) sqlite3BtreeCommitPhaseOne(p->pSrc, 0);
55783      TESTONLY( rc2 |= ) sqlite3BtreeCommitPhaseTwo(p->pSrc, 0);
55784      assert( rc2==SQLITE_OK );
55785    }
55786
55787    if( rc==SQLITE_IOERR_NOMEM ){
55788      rc = SQLITE_NOMEM;
55789    }
55790    p->rc = rc;
55791  }
55792  if( p->pDestDb ){
55793    sqlite3_mutex_leave(p->pDestDb->mutex);
55794  }
55795  sqlite3BtreeLeave(p->pSrc);
55796  sqlite3_mutex_leave(p->pSrcDb->mutex);
55797  return rc;
55798}
55799
55800/*
55801** Release all resources associated with an sqlite3_backup* handle.
55802*/
55803SQLITE_API int sqlite3_backup_finish(sqlite3_backup *p){
55804  sqlite3_backup **pp;                 /* Ptr to head of pagers backup list */
55805  sqlite3_mutex *mutex;                /* Mutex to protect source database */
55806  int rc;                              /* Value to return */
55807
55808  /* Enter the mutexes */
55809  if( p==0 ) return SQLITE_OK;
55810  sqlite3_mutex_enter(p->pSrcDb->mutex);
55811  sqlite3BtreeEnter(p->pSrc);
55812  mutex = p->pSrcDb->mutex;
55813  if( p->pDestDb ){
55814    sqlite3_mutex_enter(p->pDestDb->mutex);
55815  }
55816
55817  /* Detach this backup from the source pager. */
55818  if( p->pDestDb ){
55819    p->pSrc->nBackup--;
55820  }
55821  if( p->isAttached ){
55822    pp = sqlite3PagerBackupPtr(sqlite3BtreePager(p->pSrc));
55823    while( *pp!=p ){
55824      pp = &(*pp)->pNext;
55825    }
55826    *pp = p->pNext;
55827  }
55828
55829  /* If a transaction is still open on the Btree, roll it back. */
55830  sqlite3BtreeRollback(p->pDest);
55831
55832  /* Set the error code of the destination database handle. */
55833  rc = (p->rc==SQLITE_DONE) ? SQLITE_OK : p->rc;
55834  sqlite3Error(p->pDestDb, rc, 0);
55835
55836  /* Exit the mutexes and free the backup context structure. */
55837  if( p->pDestDb ){
55838    sqlite3_mutex_leave(p->pDestDb->mutex);
55839  }
55840  sqlite3BtreeLeave(p->pSrc);
55841  if( p->pDestDb ){
55842    /* EVIDENCE-OF: R-64852-21591 The sqlite3_backup object is created by a
55843    ** call to sqlite3_backup_init() and is destroyed by a call to
55844    ** sqlite3_backup_finish(). */
55845    sqlite3_free(p);
55846  }
55847  sqlite3_mutex_leave(mutex);
55848  return rc;
55849}
55850
55851/*
55852** Return the number of pages still to be backed up as of the most recent
55853** call to sqlite3_backup_step().
55854*/
55855SQLITE_API int sqlite3_backup_remaining(sqlite3_backup *p){
55856  return p->nRemaining;
55857}
55858
55859/*
55860** Return the total number of pages in the source database as of the most
55861** recent call to sqlite3_backup_step().
55862*/
55863SQLITE_API int sqlite3_backup_pagecount(sqlite3_backup *p){
55864  return p->nPagecount;
55865}
55866
55867/*
55868** This function is called after the contents of page iPage of the
55869** source database have been modified. If page iPage has already been
55870** copied into the destination database, then the data written to the
55871** destination is now invalidated. The destination copy of iPage needs
55872** to be updated with the new data before the backup operation is
55873** complete.
55874**
55875** It is assumed that the mutex associated with the BtShared object
55876** corresponding to the source database is held when this function is
55877** called.
55878*/
55879SQLITE_PRIVATE void sqlite3BackupUpdate(sqlite3_backup *pBackup, Pgno iPage, const u8 *aData){
55880  sqlite3_backup *p;                   /* Iterator variable */
55881  for(p=pBackup; p; p=p->pNext){
55882    assert( sqlite3_mutex_held(p->pSrc->pBt->mutex) );
55883    if( !isFatalError(p->rc) && iPage<p->iNext ){
55884      /* The backup process p has already copied page iPage. But now it
55885      ** has been modified by a transaction on the source pager. Copy
55886      ** the new data into the backup.
55887      */
55888      int rc;
55889      assert( p->pDestDb );
55890      sqlite3_mutex_enter(p->pDestDb->mutex);
55891      rc = backupOnePage(p, iPage, aData);
55892      sqlite3_mutex_leave(p->pDestDb->mutex);
55893      assert( rc!=SQLITE_BUSY && rc!=SQLITE_LOCKED );
55894      if( rc!=SQLITE_OK ){
55895        p->rc = rc;
55896      }
55897    }
55898  }
55899}
55900
55901/*
55902** Restart the backup process. This is called when the pager layer
55903** detects that the database has been modified by an external database
55904** connection. In this case there is no way of knowing which of the
55905** pages that have been copied into the destination database are still
55906** valid and which are not, so the entire process needs to be restarted.
55907**
55908** It is assumed that the mutex associated with the BtShared object
55909** corresponding to the source database is held when this function is
55910** called.
55911*/
55912SQLITE_PRIVATE void sqlite3BackupRestart(sqlite3_backup *pBackup){
55913  sqlite3_backup *p;                   /* Iterator variable */
55914  for(p=pBackup; p; p=p->pNext){
55915    assert( sqlite3_mutex_held(p->pSrc->pBt->mutex) );
55916    p->iNext = 1;
55917  }
55918}
55919
55920#ifndef SQLITE_OMIT_VACUUM
55921/*
55922** Copy the complete content of pBtFrom into pBtTo.  A transaction
55923** must be active for both files.
55924**
55925** The size of file pTo may be reduced by this operation. If anything
55926** goes wrong, the transaction on pTo is rolled back. If successful, the
55927** transaction is committed before returning.
55928*/
55929SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *pTo, Btree *pFrom){
55930  int rc;
55931  sqlite3_backup b;
55932  sqlite3BtreeEnter(pTo);
55933  sqlite3BtreeEnter(pFrom);
55934
55935  /* Set up an sqlite3_backup object. sqlite3_backup.pDestDb must be set
55936  ** to 0. This is used by the implementations of sqlite3_backup_step()
55937  ** and sqlite3_backup_finish() to detect that they are being called
55938  ** from this function, not directly by the user.
55939  */
55940  memset(&b, 0, sizeof(b));
55941  b.pSrcDb = pFrom->db;
55942  b.pSrc = pFrom;
55943  b.pDest = pTo;
55944  b.iNext = 1;
55945
55946  /* 0x7FFFFFFF is the hard limit for the number of pages in a database
55947  ** file. By passing this as the number of pages to copy to
55948  ** sqlite3_backup_step(), we can guarantee that the copy finishes
55949  ** within a single call (unless an error occurs). The assert() statement
55950  ** checks this assumption - (p->rc) should be set to either SQLITE_DONE
55951  ** or an error code.
55952  */
55953  sqlite3_backup_step(&b, 0x7FFFFFFF);
55954  assert( b.rc!=SQLITE_OK );
55955  rc = sqlite3_backup_finish(&b);
55956  if( rc==SQLITE_OK ){
55957    pTo->pBt->pageSizeFixed = 0;
55958  }
55959
55960  sqlite3BtreeLeave(pFrom);
55961  sqlite3BtreeLeave(pTo);
55962  return rc;
55963}
55964#endif /* SQLITE_OMIT_VACUUM */
55965
55966/************** End of backup.c **********************************************/
55967/************** Begin file vdbemem.c *****************************************/
55968/*
55969** 2004 May 26
55970**
55971** The author disclaims copyright to this source code.  In place of
55972** a legal notice, here is a blessing:
55973**
55974**    May you do good and not evil.
55975**    May you find forgiveness for yourself and forgive others.
55976**    May you share freely, never taking more than you give.
55977**
55978*************************************************************************
55979**
55980** This file contains code use to manipulate "Mem" structure.  A "Mem"
55981** stores a single value in the VDBE.  Mem is an opaque structure visible
55982** only within the VDBE.  Interface routines refer to a Mem using the
55983** name sqlite_value
55984*/
55985
55986/*
55987** Call sqlite3VdbeMemExpandBlob() on the supplied value (type Mem*)
55988** P if required.
55989*/
55990#define expandBlob(P) (((P)->flags&MEM_Zero)?sqlite3VdbeMemExpandBlob(P):0)
55991
55992/*
55993** If pMem is an object with a valid string representation, this routine
55994** ensures the internal encoding for the string representation is
55995** 'desiredEnc', one of SQLITE_UTF8, SQLITE_UTF16LE or SQLITE_UTF16BE.
55996**
55997** If pMem is not a string object, or the encoding of the string
55998** representation is already stored using the requested encoding, then this
55999** routine is a no-op.
56000**
56001** SQLITE_OK is returned if the conversion is successful (or not required).
56002** SQLITE_NOMEM may be returned if a malloc() fails during conversion
56003** between formats.
56004*/
56005SQLITE_PRIVATE int sqlite3VdbeChangeEncoding(Mem *pMem, int desiredEnc){
56006  int rc;
56007  assert( (pMem->flags&MEM_RowSet)==0 );
56008  assert( desiredEnc==SQLITE_UTF8 || desiredEnc==SQLITE_UTF16LE
56009           || desiredEnc==SQLITE_UTF16BE );
56010  if( !(pMem->flags&MEM_Str) || pMem->enc==desiredEnc ){
56011    return SQLITE_OK;
56012  }
56013  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
56014#ifdef SQLITE_OMIT_UTF16
56015  return SQLITE_ERROR;
56016#else
56017
56018  /* MemTranslate() may return SQLITE_OK or SQLITE_NOMEM. If NOMEM is returned,
56019  ** then the encoding of the value may not have changed.
56020  */
56021  rc = sqlite3VdbeMemTranslate(pMem, (u8)desiredEnc);
56022  assert(rc==SQLITE_OK    || rc==SQLITE_NOMEM);
56023  assert(rc==SQLITE_OK    || pMem->enc!=desiredEnc);
56024  assert(rc==SQLITE_NOMEM || pMem->enc==desiredEnc);
56025  return rc;
56026#endif
56027}
56028
56029/*
56030** Make sure pMem->z points to a writable allocation of at least
56031** n bytes.
56032**
56033** If the memory cell currently contains string or blob data
56034** and the third argument passed to this function is true, the
56035** current content of the cell is preserved. Otherwise, it may
56036** be discarded.
56037**
56038** This function sets the MEM_Dyn flag and clears any xDel callback.
56039** It also clears MEM_Ephem and MEM_Static. If the preserve flag is
56040** not set, Mem.n is zeroed.
56041*/
56042SQLITE_PRIVATE int sqlite3VdbeMemGrow(Mem *pMem, int n, int preserve){
56043  assert( 1 >=
56044    ((pMem->zMalloc && pMem->zMalloc==pMem->z) ? 1 : 0) +
56045    (((pMem->flags&MEM_Dyn)&&pMem->xDel) ? 1 : 0) +
56046    ((pMem->flags&MEM_Ephem) ? 1 : 0) +
56047    ((pMem->flags&MEM_Static) ? 1 : 0)
56048  );
56049  assert( (pMem->flags&MEM_RowSet)==0 );
56050
56051  if( n<32 ) n = 32;
56052  if( sqlite3DbMallocSize(pMem->db, pMem->zMalloc)<n ){
56053    if( preserve && pMem->z==pMem->zMalloc ){
56054      pMem->z = pMem->zMalloc = sqlite3DbReallocOrFree(pMem->db, pMem->z, n);
56055      preserve = 0;
56056    }else{
56057      sqlite3DbFree(pMem->db, pMem->zMalloc);
56058      pMem->zMalloc = sqlite3DbMallocRaw(pMem->db, n);
56059    }
56060  }
56061
56062  if( pMem->z && preserve && pMem->zMalloc && pMem->z!=pMem->zMalloc ){
56063    memcpy(pMem->zMalloc, pMem->z, pMem->n);
56064  }
56065  if( pMem->flags&MEM_Dyn && pMem->xDel ){
56066    pMem->xDel((void *)(pMem->z));
56067  }
56068
56069  pMem->z = pMem->zMalloc;
56070  if( pMem->z==0 ){
56071    pMem->flags = MEM_Null;
56072  }else{
56073    pMem->flags &= ~(MEM_Ephem|MEM_Static);
56074  }
56075  pMem->xDel = 0;
56076  return (pMem->z ? SQLITE_OK : SQLITE_NOMEM);
56077}
56078
56079/*
56080** Make the given Mem object MEM_Dyn.  In other words, make it so
56081** that any TEXT or BLOB content is stored in memory obtained from
56082** malloc().  In this way, we know that the memory is safe to be
56083** overwritten or altered.
56084**
56085** Return SQLITE_OK on success or SQLITE_NOMEM if malloc fails.
56086*/
56087SQLITE_PRIVATE int sqlite3VdbeMemMakeWriteable(Mem *pMem){
56088  int f;
56089  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
56090  assert( (pMem->flags&MEM_RowSet)==0 );
56091  expandBlob(pMem);
56092  f = pMem->flags;
56093  if( (f&(MEM_Str|MEM_Blob)) && pMem->z!=pMem->zMalloc ){
56094    if( sqlite3VdbeMemGrow(pMem, pMem->n + 2, 1) ){
56095      return SQLITE_NOMEM;
56096    }
56097    pMem->z[pMem->n] = 0;
56098    pMem->z[pMem->n+1] = 0;
56099    pMem->flags |= MEM_Term;
56100#ifdef SQLITE_DEBUG
56101    pMem->pScopyFrom = 0;
56102#endif
56103  }
56104
56105  return SQLITE_OK;
56106}
56107
56108/*
56109** If the given Mem* has a zero-filled tail, turn it into an ordinary
56110** blob stored in dynamically allocated space.
56111*/
56112#ifndef SQLITE_OMIT_INCRBLOB
56113SQLITE_PRIVATE int sqlite3VdbeMemExpandBlob(Mem *pMem){
56114  if( pMem->flags & MEM_Zero ){
56115    int nByte;
56116    assert( pMem->flags&MEM_Blob );
56117    assert( (pMem->flags&MEM_RowSet)==0 );
56118    assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
56119
56120    /* Set nByte to the number of bytes required to store the expanded blob. */
56121    nByte = pMem->n + pMem->u.nZero;
56122    if( nByte<=0 ){
56123      nByte = 1;
56124    }
56125    if( sqlite3VdbeMemGrow(pMem, nByte, 1) ){
56126      return SQLITE_NOMEM;
56127    }
56128
56129    memset(&pMem->z[pMem->n], 0, pMem->u.nZero);
56130    pMem->n += pMem->u.nZero;
56131    pMem->flags &= ~(MEM_Zero|MEM_Term);
56132  }
56133  return SQLITE_OK;
56134}
56135#endif
56136
56137
56138/*
56139** Make sure the given Mem is \u0000 terminated.
56140*/
56141SQLITE_PRIVATE int sqlite3VdbeMemNulTerminate(Mem *pMem){
56142  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
56143  if( (pMem->flags & MEM_Term)!=0 || (pMem->flags & MEM_Str)==0 ){
56144    return SQLITE_OK;   /* Nothing to do */
56145  }
56146  if( sqlite3VdbeMemGrow(pMem, pMem->n+2, 1) ){
56147    return SQLITE_NOMEM;
56148  }
56149  pMem->z[pMem->n] = 0;
56150  pMem->z[pMem->n+1] = 0;
56151  pMem->flags |= MEM_Term;
56152  return SQLITE_OK;
56153}
56154
56155/*
56156** Add MEM_Str to the set of representations for the given Mem.  Numbers
56157** are converted using sqlite3_snprintf().  Converting a BLOB to a string
56158** is a no-op.
56159**
56160** Existing representations MEM_Int and MEM_Real are *not* invalidated.
56161**
56162** A MEM_Null value will never be passed to this function. This function is
56163** used for converting values to text for returning to the user (i.e. via
56164** sqlite3_value_text()), or for ensuring that values to be used as btree
56165** keys are strings. In the former case a NULL pointer is returned the
56166** user and the later is an internal programming error.
56167*/
56168SQLITE_PRIVATE int sqlite3VdbeMemStringify(Mem *pMem, int enc){
56169  int rc = SQLITE_OK;
56170  int fg = pMem->flags;
56171  const int nByte = 32;
56172
56173  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
56174  assert( !(fg&MEM_Zero) );
56175  assert( !(fg&(MEM_Str|MEM_Blob)) );
56176  assert( fg&(MEM_Int|MEM_Real) );
56177  assert( (pMem->flags&MEM_RowSet)==0 );
56178  assert( EIGHT_BYTE_ALIGNMENT(pMem) );
56179
56180
56181  if( sqlite3VdbeMemGrow(pMem, nByte, 0) ){
56182    return SQLITE_NOMEM;
56183  }
56184
56185  /* For a Real or Integer, use sqlite3_mprintf() to produce the UTF-8
56186  ** string representation of the value. Then, if the required encoding
56187  ** is UTF-16le or UTF-16be do a translation.
56188  **
56189  ** FIX ME: It would be better if sqlite3_snprintf() could do UTF-16.
56190  */
56191  if( fg & MEM_Int ){
56192    sqlite3_snprintf(nByte, pMem->z, "%lld", pMem->u.i);
56193  }else{
56194    assert( fg & MEM_Real );
56195    sqlite3_snprintf(nByte, pMem->z, "%!.15g", pMem->r);
56196  }
56197  pMem->n = sqlite3Strlen30(pMem->z);
56198  pMem->enc = SQLITE_UTF8;
56199  pMem->flags |= MEM_Str|MEM_Term;
56200  sqlite3VdbeChangeEncoding(pMem, enc);
56201  return rc;
56202}
56203
56204/*
56205** Memory cell pMem contains the context of an aggregate function.
56206** This routine calls the finalize method for that function.  The
56207** result of the aggregate is stored back into pMem.
56208**
56209** Return SQLITE_ERROR if the finalizer reports an error.  SQLITE_OK
56210** otherwise.
56211*/
56212SQLITE_PRIVATE int sqlite3VdbeMemFinalize(Mem *pMem, FuncDef *pFunc){
56213  int rc = SQLITE_OK;
56214  if( ALWAYS(pFunc && pFunc->xFinalize) ){
56215    sqlite3_context ctx;
56216    assert( (pMem->flags & MEM_Null)!=0 || pFunc==pMem->u.pDef );
56217    assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
56218    memset(&ctx, 0, sizeof(ctx));
56219    ctx.s.flags = MEM_Null;
56220    ctx.s.db = pMem->db;
56221    ctx.pMem = pMem;
56222    ctx.pFunc = pFunc;
56223    pFunc->xFinalize(&ctx); /* IMP: R-24505-23230 */
56224    assert( 0==(pMem->flags&MEM_Dyn) && !pMem->xDel );
56225    sqlite3DbFree(pMem->db, pMem->zMalloc);
56226    memcpy(pMem, &ctx.s, sizeof(ctx.s));
56227    rc = ctx.isError;
56228  }
56229  return rc;
56230}
56231
56232/*
56233** If the memory cell contains a string value that must be freed by
56234** invoking an external callback, free it now. Calling this function
56235** does not free any Mem.zMalloc buffer.
56236*/
56237SQLITE_PRIVATE void sqlite3VdbeMemReleaseExternal(Mem *p){
56238  assert( p->db==0 || sqlite3_mutex_held(p->db->mutex) );
56239  testcase( p->flags & MEM_Agg );
56240  testcase( p->flags & MEM_Dyn );
56241  testcase( p->flags & MEM_RowSet );
56242  testcase( p->flags & MEM_Frame );
56243  if( p->flags&(MEM_Agg|MEM_Dyn|MEM_RowSet|MEM_Frame) ){
56244    if( p->flags&MEM_Agg ){
56245      sqlite3VdbeMemFinalize(p, p->u.pDef);
56246      assert( (p->flags & MEM_Agg)==0 );
56247      sqlite3VdbeMemRelease(p);
56248    }else if( p->flags&MEM_Dyn && p->xDel ){
56249      assert( (p->flags&MEM_RowSet)==0 );
56250      p->xDel((void *)p->z);
56251      p->xDel = 0;
56252    }else if( p->flags&MEM_RowSet ){
56253      sqlite3RowSetClear(p->u.pRowSet);
56254    }else if( p->flags&MEM_Frame ){
56255      sqlite3VdbeMemSetNull(p);
56256    }
56257  }
56258}
56259
56260/*
56261** Release any memory held by the Mem. This may leave the Mem in an
56262** inconsistent state, for example with (Mem.z==0) and
56263** (Mem.type==SQLITE_TEXT).
56264*/
56265SQLITE_PRIVATE void sqlite3VdbeMemRelease(Mem *p){
56266  sqlite3VdbeMemReleaseExternal(p);
56267  sqlite3DbFree(p->db, p->zMalloc);
56268  p->z = 0;
56269  p->zMalloc = 0;
56270  p->xDel = 0;
56271}
56272
56273/*
56274** Convert a 64-bit IEEE double into a 64-bit signed integer.
56275** If the double is too large, return 0x8000000000000000.
56276**
56277** Most systems appear to do this simply by assigning
56278** variables and without the extra range tests.  But
56279** there are reports that windows throws an expection
56280** if the floating point value is out of range. (See ticket #2880.)
56281** Because we do not completely understand the problem, we will
56282** take the conservative approach and always do range tests
56283** before attempting the conversion.
56284*/
56285static i64 doubleToInt64(double r){
56286#ifdef SQLITE_OMIT_FLOATING_POINT
56287  /* When floating-point is omitted, double and int64 are the same thing */
56288  return r;
56289#else
56290  /*
56291  ** Many compilers we encounter do not define constants for the
56292  ** minimum and maximum 64-bit integers, or they define them
56293  ** inconsistently.  And many do not understand the "LL" notation.
56294  ** So we define our own static constants here using nothing
56295  ** larger than a 32-bit integer constant.
56296  */
56297  static const i64 maxInt = LARGEST_INT64;
56298  static const i64 minInt = SMALLEST_INT64;
56299
56300  if( r<(double)minInt ){
56301    return minInt;
56302  }else if( r>(double)maxInt ){
56303    /* minInt is correct here - not maxInt.  It turns out that assigning
56304    ** a very large positive number to an integer results in a very large
56305    ** negative integer.  This makes no sense, but it is what x86 hardware
56306    ** does so for compatibility we will do the same in software. */
56307    return minInt;
56308  }else{
56309    return (i64)r;
56310  }
56311#endif
56312}
56313
56314/*
56315** Return some kind of integer value which is the best we can do
56316** at representing the value that *pMem describes as an integer.
56317** If pMem is an integer, then the value is exact.  If pMem is
56318** a floating-point then the value returned is the integer part.
56319** If pMem is a string or blob, then we make an attempt to convert
56320** it into a integer and return that.  If pMem represents an
56321** an SQL-NULL value, return 0.
56322**
56323** If pMem represents a string value, its encoding might be changed.
56324*/
56325SQLITE_PRIVATE i64 sqlite3VdbeIntValue(Mem *pMem){
56326  int flags;
56327  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
56328  assert( EIGHT_BYTE_ALIGNMENT(pMem) );
56329  flags = pMem->flags;
56330  if( flags & MEM_Int ){
56331    return pMem->u.i;
56332  }else if( flags & MEM_Real ){
56333    return doubleToInt64(pMem->r);
56334  }else if( flags & (MEM_Str|MEM_Blob) ){
56335    i64 value = 0;
56336    assert( pMem->z || pMem->n==0 );
56337    testcase( pMem->z==0 );
56338    sqlite3Atoi64(pMem->z, &value, pMem->n, pMem->enc);
56339    return value;
56340  }else{
56341    return 0;
56342  }
56343}
56344
56345/*
56346** Return the best representation of pMem that we can get into a
56347** double.  If pMem is already a double or an integer, return its
56348** value.  If it is a string or blob, try to convert it to a double.
56349** If it is a NULL, return 0.0.
56350*/
56351SQLITE_PRIVATE double sqlite3VdbeRealValue(Mem *pMem){
56352  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
56353  assert( EIGHT_BYTE_ALIGNMENT(pMem) );
56354  if( pMem->flags & MEM_Real ){
56355    return pMem->r;
56356  }else if( pMem->flags & MEM_Int ){
56357    return (double)pMem->u.i;
56358  }else if( pMem->flags & (MEM_Str|MEM_Blob) ){
56359    /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
56360    double val = (double)0;
56361    sqlite3AtoF(pMem->z, &val, pMem->n, pMem->enc);
56362    return val;
56363  }else{
56364    /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
56365    return (double)0;
56366  }
56367}
56368
56369/*
56370** The MEM structure is already a MEM_Real.  Try to also make it a
56371** MEM_Int if we can.
56372*/
56373SQLITE_PRIVATE void sqlite3VdbeIntegerAffinity(Mem *pMem){
56374  assert( pMem->flags & MEM_Real );
56375  assert( (pMem->flags & MEM_RowSet)==0 );
56376  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
56377  assert( EIGHT_BYTE_ALIGNMENT(pMem) );
56378
56379  pMem->u.i = doubleToInt64(pMem->r);
56380
56381  /* Only mark the value as an integer if
56382  **
56383  **    (1) the round-trip conversion real->int->real is a no-op, and
56384  **    (2) The integer is neither the largest nor the smallest
56385  **        possible integer (ticket #3922)
56386  **
56387  ** The second and third terms in the following conditional enforces
56388  ** the second condition under the assumption that addition overflow causes
56389  ** values to wrap around.  On x86 hardware, the third term is always
56390  ** true and could be omitted.  But we leave it in because other
56391  ** architectures might behave differently.
56392  */
56393  if( pMem->r==(double)pMem->u.i && pMem->u.i>SMALLEST_INT64
56394      && ALWAYS(pMem->u.i<LARGEST_INT64) ){
56395    pMem->flags |= MEM_Int;
56396  }
56397}
56398
56399/*
56400** Convert pMem to type integer.  Invalidate any prior representations.
56401*/
56402SQLITE_PRIVATE int sqlite3VdbeMemIntegerify(Mem *pMem){
56403  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
56404  assert( (pMem->flags & MEM_RowSet)==0 );
56405  assert( EIGHT_BYTE_ALIGNMENT(pMem) );
56406
56407  pMem->u.i = sqlite3VdbeIntValue(pMem);
56408  MemSetTypeFlag(pMem, MEM_Int);
56409  return SQLITE_OK;
56410}
56411
56412/*
56413** Convert pMem so that it is of type MEM_Real.
56414** Invalidate any prior representations.
56415*/
56416SQLITE_PRIVATE int sqlite3VdbeMemRealify(Mem *pMem){
56417  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
56418  assert( EIGHT_BYTE_ALIGNMENT(pMem) );
56419
56420  pMem->r = sqlite3VdbeRealValue(pMem);
56421  MemSetTypeFlag(pMem, MEM_Real);
56422  return SQLITE_OK;
56423}
56424
56425/*
56426** Convert pMem so that it has types MEM_Real or MEM_Int or both.
56427** Invalidate any prior representations.
56428**
56429** Every effort is made to force the conversion, even if the input
56430** is a string that does not look completely like a number.  Convert
56431** as much of the string as we can and ignore the rest.
56432*/
56433SQLITE_PRIVATE int sqlite3VdbeMemNumerify(Mem *pMem){
56434  if( (pMem->flags & (MEM_Int|MEM_Real|MEM_Null))==0 ){
56435    assert( (pMem->flags & (MEM_Blob|MEM_Str))!=0 );
56436    assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
56437    if( 0==sqlite3Atoi64(pMem->z, &pMem->u.i, pMem->n, pMem->enc) ){
56438      MemSetTypeFlag(pMem, MEM_Int);
56439    }else{
56440      pMem->r = sqlite3VdbeRealValue(pMem);
56441      MemSetTypeFlag(pMem, MEM_Real);
56442      sqlite3VdbeIntegerAffinity(pMem);
56443    }
56444  }
56445  assert( (pMem->flags & (MEM_Int|MEM_Real|MEM_Null))!=0 );
56446  pMem->flags &= ~(MEM_Str|MEM_Blob);
56447  return SQLITE_OK;
56448}
56449
56450/*
56451** Delete any previous value and set the value stored in *pMem to NULL.
56452*/
56453SQLITE_PRIVATE void sqlite3VdbeMemSetNull(Mem *pMem){
56454  if( pMem->flags & MEM_Frame ){
56455    VdbeFrame *pFrame = pMem->u.pFrame;
56456    pFrame->pParent = pFrame->v->pDelFrame;
56457    pFrame->v->pDelFrame = pFrame;
56458  }
56459  if( pMem->flags & MEM_RowSet ){
56460    sqlite3RowSetClear(pMem->u.pRowSet);
56461  }
56462  MemSetTypeFlag(pMem, MEM_Null);
56463  pMem->type = SQLITE_NULL;
56464}
56465
56466/*
56467** Delete any previous value and set the value to be a BLOB of length
56468** n containing all zeros.
56469*/
56470SQLITE_PRIVATE void sqlite3VdbeMemSetZeroBlob(Mem *pMem, int n){
56471  sqlite3VdbeMemRelease(pMem);
56472  pMem->flags = MEM_Blob|MEM_Zero;
56473  pMem->type = SQLITE_BLOB;
56474  pMem->n = 0;
56475  if( n<0 ) n = 0;
56476  pMem->u.nZero = n;
56477  pMem->enc = SQLITE_UTF8;
56478
56479#ifdef SQLITE_OMIT_INCRBLOB
56480  sqlite3VdbeMemGrow(pMem, n, 0);
56481  if( pMem->z ){
56482    pMem->n = n;
56483    memset(pMem->z, 0, n);
56484  }
56485#endif
56486}
56487
56488/*
56489** Delete any previous value and set the value stored in *pMem to val,
56490** manifest type INTEGER.
56491*/
56492SQLITE_PRIVATE void sqlite3VdbeMemSetInt64(Mem *pMem, i64 val){
56493  sqlite3VdbeMemRelease(pMem);
56494  pMem->u.i = val;
56495  pMem->flags = MEM_Int;
56496  pMem->type = SQLITE_INTEGER;
56497}
56498
56499#ifndef SQLITE_OMIT_FLOATING_POINT
56500/*
56501** Delete any previous value and set the value stored in *pMem to val,
56502** manifest type REAL.
56503*/
56504SQLITE_PRIVATE void sqlite3VdbeMemSetDouble(Mem *pMem, double val){
56505  if( sqlite3IsNaN(val) ){
56506    sqlite3VdbeMemSetNull(pMem);
56507  }else{
56508    sqlite3VdbeMemRelease(pMem);
56509    pMem->r = val;
56510    pMem->flags = MEM_Real;
56511    pMem->type = SQLITE_FLOAT;
56512  }
56513}
56514#endif
56515
56516/*
56517** Delete any previous value and set the value of pMem to be an
56518** empty boolean index.
56519*/
56520SQLITE_PRIVATE void sqlite3VdbeMemSetRowSet(Mem *pMem){
56521  sqlite3 *db = pMem->db;
56522  assert( db!=0 );
56523  assert( (pMem->flags & MEM_RowSet)==0 );
56524  sqlite3VdbeMemRelease(pMem);
56525  pMem->zMalloc = sqlite3DbMallocRaw(db, 64);
56526  if( db->mallocFailed ){
56527    pMem->flags = MEM_Null;
56528  }else{
56529    assert( pMem->zMalloc );
56530    pMem->u.pRowSet = sqlite3RowSetInit(db, pMem->zMalloc,
56531                                       sqlite3DbMallocSize(db, pMem->zMalloc));
56532    assert( pMem->u.pRowSet!=0 );
56533    pMem->flags = MEM_RowSet;
56534  }
56535}
56536
56537/*
56538** Return true if the Mem object contains a TEXT or BLOB that is
56539** too large - whose size exceeds SQLITE_MAX_LENGTH.
56540*/
56541SQLITE_PRIVATE int sqlite3VdbeMemTooBig(Mem *p){
56542  assert( p->db!=0 );
56543  if( p->flags & (MEM_Str|MEM_Blob) ){
56544    int n = p->n;
56545    if( p->flags & MEM_Zero ){
56546      n += p->u.nZero;
56547    }
56548    return n>p->db->aLimit[SQLITE_LIMIT_LENGTH];
56549  }
56550  return 0;
56551}
56552
56553#ifdef SQLITE_DEBUG
56554/*
56555** This routine prepares a memory cell for modication by breaking
56556** its link to a shallow copy and by marking any current shallow
56557** copies of this cell as invalid.
56558**
56559** This is used for testing and debugging only - to make sure shallow
56560** copies are not misused.
56561*/
56562SQLITE_PRIVATE void sqlite3VdbeMemPrepareToChange(Vdbe *pVdbe, Mem *pMem){
56563  int i;
56564  Mem *pX;
56565  for(i=1, pX=&pVdbe->aMem[1]; i<=pVdbe->nMem; i++, pX++){
56566    if( pX->pScopyFrom==pMem ){
56567      pX->flags |= MEM_Invalid;
56568      pX->pScopyFrom = 0;
56569    }
56570  }
56571  pMem->pScopyFrom = 0;
56572}
56573#endif /* SQLITE_DEBUG */
56574
56575/*
56576** Size of struct Mem not including the Mem.zMalloc member.
56577*/
56578#define MEMCELLSIZE (size_t)(&(((Mem *)0)->zMalloc))
56579
56580/*
56581** Make an shallow copy of pFrom into pTo.  Prior contents of
56582** pTo are freed.  The pFrom->z field is not duplicated.  If
56583** pFrom->z is used, then pTo->z points to the same thing as pFrom->z
56584** and flags gets srcType (either MEM_Ephem or MEM_Static).
56585*/
56586SQLITE_PRIVATE void sqlite3VdbeMemShallowCopy(Mem *pTo, const Mem *pFrom, int srcType){
56587  assert( (pFrom->flags & MEM_RowSet)==0 );
56588  sqlite3VdbeMemReleaseExternal(pTo);
56589  memcpy(pTo, pFrom, MEMCELLSIZE);
56590  pTo->xDel = 0;
56591  if( (pFrom->flags&MEM_Static)==0 ){
56592    pTo->flags &= ~(MEM_Dyn|MEM_Static|MEM_Ephem);
56593    assert( srcType==MEM_Ephem || srcType==MEM_Static );
56594    pTo->flags |= srcType;
56595  }
56596}
56597
56598/*
56599** Make a full copy of pFrom into pTo.  Prior contents of pTo are
56600** freed before the copy is made.
56601*/
56602SQLITE_PRIVATE int sqlite3VdbeMemCopy(Mem *pTo, const Mem *pFrom){
56603  int rc = SQLITE_OK;
56604
56605  assert( (pFrom->flags & MEM_RowSet)==0 );
56606  sqlite3VdbeMemReleaseExternal(pTo);
56607  memcpy(pTo, pFrom, MEMCELLSIZE);
56608  pTo->flags &= ~MEM_Dyn;
56609
56610  if( pTo->flags&(MEM_Str|MEM_Blob) ){
56611    if( 0==(pFrom->flags&MEM_Static) ){
56612      pTo->flags |= MEM_Ephem;
56613      rc = sqlite3VdbeMemMakeWriteable(pTo);
56614    }
56615  }
56616
56617  return rc;
56618}
56619
56620/*
56621** Transfer the contents of pFrom to pTo. Any existing value in pTo is
56622** freed. If pFrom contains ephemeral data, a copy is made.
56623**
56624** pFrom contains an SQL NULL when this routine returns.
56625*/
56626SQLITE_PRIVATE void sqlite3VdbeMemMove(Mem *pTo, Mem *pFrom){
56627  assert( pFrom->db==0 || sqlite3_mutex_held(pFrom->db->mutex) );
56628  assert( pTo->db==0 || sqlite3_mutex_held(pTo->db->mutex) );
56629  assert( pFrom->db==0 || pTo->db==0 || pFrom->db==pTo->db );
56630
56631  sqlite3VdbeMemRelease(pTo);
56632  memcpy(pTo, pFrom, sizeof(Mem));
56633  pFrom->flags = MEM_Null;
56634  pFrom->xDel = 0;
56635  pFrom->zMalloc = 0;
56636}
56637
56638/*
56639** Change the value of a Mem to be a string or a BLOB.
56640**
56641** The memory management strategy depends on the value of the xDel
56642** parameter. If the value passed is SQLITE_TRANSIENT, then the
56643** string is copied into a (possibly existing) buffer managed by the
56644** Mem structure. Otherwise, any existing buffer is freed and the
56645** pointer copied.
56646**
56647** If the string is too large (if it exceeds the SQLITE_LIMIT_LENGTH
56648** size limit) then no memory allocation occurs.  If the string can be
56649** stored without allocating memory, then it is.  If a memory allocation
56650** is required to store the string, then value of pMem is unchanged.  In
56651** either case, SQLITE_TOOBIG is returned.
56652*/
56653SQLITE_PRIVATE int sqlite3VdbeMemSetStr(
56654  Mem *pMem,          /* Memory cell to set to string value */
56655  const char *z,      /* String pointer */
56656  int n,              /* Bytes in string, or negative */
56657  u8 enc,             /* Encoding of z.  0 for BLOBs */
56658  void (*xDel)(void*) /* Destructor function */
56659){
56660  int nByte = n;      /* New value for pMem->n */
56661  int iLimit;         /* Maximum allowed string or blob size */
56662  u16 flags = 0;      /* New value for pMem->flags */
56663
56664  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
56665  assert( (pMem->flags & MEM_RowSet)==0 );
56666
56667  /* If z is a NULL pointer, set pMem to contain an SQL NULL. */
56668  if( !z ){
56669    sqlite3VdbeMemSetNull(pMem);
56670    return SQLITE_OK;
56671  }
56672
56673  if( pMem->db ){
56674    iLimit = pMem->db->aLimit[SQLITE_LIMIT_LENGTH];
56675  }else{
56676    iLimit = SQLITE_MAX_LENGTH;
56677  }
56678  flags = (enc==0?MEM_Blob:MEM_Str);
56679  if( nByte<0 ){
56680    assert( enc!=0 );
56681    if( enc==SQLITE_UTF8 ){
56682      for(nByte=0; nByte<=iLimit && z[nByte]; nByte++){}
56683    }else{
56684      for(nByte=0; nByte<=iLimit && (z[nByte] | z[nByte+1]); nByte+=2){}
56685    }
56686    flags |= MEM_Term;
56687  }
56688
56689  /* The following block sets the new values of Mem.z and Mem.xDel. It
56690  ** also sets a flag in local variable "flags" to indicate the memory
56691  ** management (one of MEM_Dyn or MEM_Static).
56692  */
56693  if( xDel==SQLITE_TRANSIENT ){
56694    int nAlloc = nByte;
56695    if( flags&MEM_Term ){
56696      nAlloc += (enc==SQLITE_UTF8?1:2);
56697    }
56698    if( nByte>iLimit ){
56699      return SQLITE_TOOBIG;
56700    }
56701    if( sqlite3VdbeMemGrow(pMem, nAlloc, 0) ){
56702      return SQLITE_NOMEM;
56703    }
56704    memcpy(pMem->z, z, nAlloc);
56705  }else if( xDel==SQLITE_DYNAMIC ){
56706    sqlite3VdbeMemRelease(pMem);
56707    pMem->zMalloc = pMem->z = (char *)z;
56708    pMem->xDel = 0;
56709  }else{
56710    sqlite3VdbeMemRelease(pMem);
56711    pMem->z = (char *)z;
56712    pMem->xDel = xDel;
56713    flags |= ((xDel==SQLITE_STATIC)?MEM_Static:MEM_Dyn);
56714  }
56715
56716  pMem->n = nByte;
56717  pMem->flags = flags;
56718  pMem->enc = (enc==0 ? SQLITE_UTF8 : enc);
56719  pMem->type = (enc==0 ? SQLITE_BLOB : SQLITE_TEXT);
56720
56721#ifndef SQLITE_OMIT_UTF16
56722  if( pMem->enc!=SQLITE_UTF8 && sqlite3VdbeMemHandleBom(pMem) ){
56723    return SQLITE_NOMEM;
56724  }
56725#endif
56726
56727  if( nByte>iLimit ){
56728    return SQLITE_TOOBIG;
56729  }
56730
56731  return SQLITE_OK;
56732}
56733
56734/*
56735** Compare the values contained by the two memory cells, returning
56736** negative, zero or positive if pMem1 is less than, equal to, or greater
56737** than pMem2. Sorting order is NULL's first, followed by numbers (integers
56738** and reals) sorted numerically, followed by text ordered by the collating
56739** sequence pColl and finally blob's ordered by memcmp().
56740**
56741** Two NULL values are considered equal by this function.
56742*/
56743SQLITE_PRIVATE int sqlite3MemCompare(const Mem *pMem1, const Mem *pMem2, const CollSeq *pColl){
56744  int rc;
56745  int f1, f2;
56746  int combined_flags;
56747
56748  f1 = pMem1->flags;
56749  f2 = pMem2->flags;
56750  combined_flags = f1|f2;
56751  assert( (combined_flags & MEM_RowSet)==0 );
56752
56753  /* If one value is NULL, it is less than the other. If both values
56754  ** are NULL, return 0.
56755  */
56756  if( combined_flags&MEM_Null ){
56757    return (f2&MEM_Null) - (f1&MEM_Null);
56758  }
56759
56760  /* If one value is a number and the other is not, the number is less.
56761  ** If both are numbers, compare as reals if one is a real, or as integers
56762  ** if both values are integers.
56763  */
56764  if( combined_flags&(MEM_Int|MEM_Real) ){
56765    if( !(f1&(MEM_Int|MEM_Real)) ){
56766      return 1;
56767    }
56768    if( !(f2&(MEM_Int|MEM_Real)) ){
56769      return -1;
56770    }
56771    if( (f1 & f2 & MEM_Int)==0 ){
56772      double r1, r2;
56773      if( (f1&MEM_Real)==0 ){
56774        r1 = (double)pMem1->u.i;
56775      }else{
56776        r1 = pMem1->r;
56777      }
56778      if( (f2&MEM_Real)==0 ){
56779        r2 = (double)pMem2->u.i;
56780      }else{
56781        r2 = pMem2->r;
56782      }
56783      if( r1<r2 ) return -1;
56784      if( r1>r2 ) return 1;
56785      return 0;
56786    }else{
56787      assert( f1&MEM_Int );
56788      assert( f2&MEM_Int );
56789      if( pMem1->u.i < pMem2->u.i ) return -1;
56790      if( pMem1->u.i > pMem2->u.i ) return 1;
56791      return 0;
56792    }
56793  }
56794
56795  /* If one value is a string and the other is a blob, the string is less.
56796  ** If both are strings, compare using the collating functions.
56797  */
56798  if( combined_flags&MEM_Str ){
56799    if( (f1 & MEM_Str)==0 ){
56800      return 1;
56801    }
56802    if( (f2 & MEM_Str)==0 ){
56803      return -1;
56804    }
56805
56806    assert( pMem1->enc==pMem2->enc );
56807    assert( pMem1->enc==SQLITE_UTF8 ||
56808            pMem1->enc==SQLITE_UTF16LE || pMem1->enc==SQLITE_UTF16BE );
56809
56810    /* The collation sequence must be defined at this point, even if
56811    ** the user deletes the collation sequence after the vdbe program is
56812    ** compiled (this was not always the case).
56813    */
56814    assert( !pColl || pColl->xCmp );
56815
56816    if( pColl ){
56817      if( pMem1->enc==pColl->enc ){
56818        /* The strings are already in the correct encoding.  Call the
56819        ** comparison function directly */
56820        return pColl->xCmp(pColl->pUser,pMem1->n,pMem1->z,pMem2->n,pMem2->z);
56821      }else{
56822        const void *v1, *v2;
56823        int n1, n2;
56824        Mem c1;
56825        Mem c2;
56826        memset(&c1, 0, sizeof(c1));
56827        memset(&c2, 0, sizeof(c2));
56828        sqlite3VdbeMemShallowCopy(&c1, pMem1, MEM_Ephem);
56829        sqlite3VdbeMemShallowCopy(&c2, pMem2, MEM_Ephem);
56830        v1 = sqlite3ValueText((sqlite3_value*)&c1, pColl->enc);
56831        n1 = v1==0 ? 0 : c1.n;
56832        v2 = sqlite3ValueText((sqlite3_value*)&c2, pColl->enc);
56833        n2 = v2==0 ? 0 : c2.n;
56834        rc = pColl->xCmp(pColl->pUser, n1, v1, n2, v2);
56835        sqlite3VdbeMemRelease(&c1);
56836        sqlite3VdbeMemRelease(&c2);
56837        return rc;
56838      }
56839    }
56840    /* If a NULL pointer was passed as the collate function, fall through
56841    ** to the blob case and use memcmp().  */
56842  }
56843
56844  /* Both values must be blobs.  Compare using memcmp().  */
56845  rc = memcmp(pMem1->z, pMem2->z, (pMem1->n>pMem2->n)?pMem2->n:pMem1->n);
56846  if( rc==0 ){
56847    rc = pMem1->n - pMem2->n;
56848  }
56849  return rc;
56850}
56851
56852/*
56853** Move data out of a btree key or data field and into a Mem structure.
56854** The data or key is taken from the entry that pCur is currently pointing
56855** to.  offset and amt determine what portion of the data or key to retrieve.
56856** key is true to get the key or false to get data.  The result is written
56857** into the pMem element.
56858**
56859** The pMem structure is assumed to be uninitialized.  Any prior content
56860** is overwritten without being freed.
56861**
56862** If this routine fails for any reason (malloc returns NULL or unable
56863** to read from the disk) then the pMem is left in an inconsistent state.
56864*/
56865SQLITE_PRIVATE int sqlite3VdbeMemFromBtree(
56866  BtCursor *pCur,   /* Cursor pointing at record to retrieve. */
56867  int offset,       /* Offset from the start of data to return bytes from. */
56868  int amt,          /* Number of bytes to return. */
56869  int key,          /* If true, retrieve from the btree key, not data. */
56870  Mem *pMem         /* OUT: Return data in this Mem structure. */
56871){
56872  char *zData;        /* Data from the btree layer */
56873  int available = 0;  /* Number of bytes available on the local btree page */
56874  int rc = SQLITE_OK; /* Return code */
56875
56876  assert( sqlite3BtreeCursorIsValid(pCur) );
56877
56878  /* Note: the calls to BtreeKeyFetch() and DataFetch() below assert()
56879  ** that both the BtShared and database handle mutexes are held. */
56880  assert( (pMem->flags & MEM_RowSet)==0 );
56881  if( key ){
56882    zData = (char *)sqlite3BtreeKeyFetch(pCur, &available);
56883  }else{
56884    zData = (char *)sqlite3BtreeDataFetch(pCur, &available);
56885  }
56886  assert( zData!=0 );
56887
56888  if( offset+amt<=available && (pMem->flags&MEM_Dyn)==0 ){
56889    sqlite3VdbeMemRelease(pMem);
56890    pMem->z = &zData[offset];
56891    pMem->flags = MEM_Blob|MEM_Ephem;
56892  }else if( SQLITE_OK==(rc = sqlite3VdbeMemGrow(pMem, amt+2, 0)) ){
56893    pMem->flags = MEM_Blob|MEM_Dyn|MEM_Term;
56894    pMem->enc = 0;
56895    pMem->type = SQLITE_BLOB;
56896    if( key ){
56897      rc = sqlite3BtreeKey(pCur, offset, amt, pMem->z);
56898    }else{
56899      rc = sqlite3BtreeData(pCur, offset, amt, pMem->z);
56900    }
56901    pMem->z[amt] = 0;
56902    pMem->z[amt+1] = 0;
56903    if( rc!=SQLITE_OK ){
56904      sqlite3VdbeMemRelease(pMem);
56905    }
56906  }
56907  pMem->n = amt;
56908
56909  return rc;
56910}
56911
56912/* This function is only available internally, it is not part of the
56913** external API. It works in a similar way to sqlite3_value_text(),
56914** except the data returned is in the encoding specified by the second
56915** parameter, which must be one of SQLITE_UTF16BE, SQLITE_UTF16LE or
56916** SQLITE_UTF8.
56917**
56918** (2006-02-16:)  The enc value can be or-ed with SQLITE_UTF16_ALIGNED.
56919** If that is the case, then the result must be aligned on an even byte
56920** boundary.
56921*/
56922SQLITE_PRIVATE const void *sqlite3ValueText(sqlite3_value* pVal, u8 enc){
56923  if( !pVal ) return 0;
56924
56925  assert( pVal->db==0 || sqlite3_mutex_held(pVal->db->mutex) );
56926  assert( (enc&3)==(enc&~SQLITE_UTF16_ALIGNED) );
56927  assert( (pVal->flags & MEM_RowSet)==0 );
56928
56929  if( pVal->flags&MEM_Null ){
56930    return 0;
56931  }
56932  assert( (MEM_Blob>>3) == MEM_Str );
56933  pVal->flags |= (pVal->flags & MEM_Blob)>>3;
56934  expandBlob(pVal);
56935  if( pVal->flags&MEM_Str ){
56936    sqlite3VdbeChangeEncoding(pVal, enc & ~SQLITE_UTF16_ALIGNED);
56937    if( (enc & SQLITE_UTF16_ALIGNED)!=0 && 1==(1&SQLITE_PTR_TO_INT(pVal->z)) ){
56938      assert( (pVal->flags & (MEM_Ephem|MEM_Static))!=0 );
56939      if( sqlite3VdbeMemMakeWriteable(pVal)!=SQLITE_OK ){
56940        return 0;
56941      }
56942    }
56943    sqlite3VdbeMemNulTerminate(pVal); /* IMP: R-59893-45467 */
56944  }else{
56945    assert( (pVal->flags&MEM_Blob)==0 );
56946    sqlite3VdbeMemStringify(pVal, enc);
56947    assert( 0==(1&SQLITE_PTR_TO_INT(pVal->z)) );
56948  }
56949  assert(pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) || pVal->db==0
56950              || pVal->db->mallocFailed );
56951  if( pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) ){
56952    return pVal->z;
56953  }else{
56954    return 0;
56955  }
56956}
56957
56958/*
56959** Create a new sqlite3_value object.
56960*/
56961SQLITE_PRIVATE sqlite3_value *sqlite3ValueNew(sqlite3 *db){
56962  Mem *p = sqlite3DbMallocZero(db, sizeof(*p));
56963  if( p ){
56964    p->flags = MEM_Null;
56965    p->type = SQLITE_NULL;
56966    p->db = db;
56967  }
56968  return p;
56969}
56970
56971/*
56972** Create a new sqlite3_value object, containing the value of pExpr.
56973**
56974** This only works for very simple expressions that consist of one constant
56975** token (i.e. "5", "5.1", "'a string'"). If the expression can
56976** be converted directly into a value, then the value is allocated and
56977** a pointer written to *ppVal. The caller is responsible for deallocating
56978** the value by passing it to sqlite3ValueFree() later on. If the expression
56979** cannot be converted to a value, then *ppVal is set to NULL.
56980*/
56981SQLITE_PRIVATE int sqlite3ValueFromExpr(
56982  sqlite3 *db,              /* The database connection */
56983  Expr *pExpr,              /* The expression to evaluate */
56984  u8 enc,                   /* Encoding to use */
56985  u8 affinity,              /* Affinity to use */
56986  sqlite3_value **ppVal     /* Write the new value here */
56987){
56988  int op;
56989  char *zVal = 0;
56990  sqlite3_value *pVal = 0;
56991  int negInt = 1;
56992  const char *zNeg = "";
56993
56994  if( !pExpr ){
56995    *ppVal = 0;
56996    return SQLITE_OK;
56997  }
56998  op = pExpr->op;
56999
57000  /* op can only be TK_REGISTER if we have compiled with SQLITE_ENABLE_STAT2.
57001  ** The ifdef here is to enable us to achieve 100% branch test coverage even
57002  ** when SQLITE_ENABLE_STAT2 is omitted.
57003  */
57004#ifdef SQLITE_ENABLE_STAT2
57005  if( op==TK_REGISTER ) op = pExpr->op2;
57006#else
57007  if( NEVER(op==TK_REGISTER) ) op = pExpr->op2;
57008#endif
57009
57010  /* Handle negative integers in a single step.  This is needed in the
57011  ** case when the value is -9223372036854775808.
57012  */
57013  if( op==TK_UMINUS
57014   && (pExpr->pLeft->op==TK_INTEGER || pExpr->pLeft->op==TK_FLOAT) ){
57015    pExpr = pExpr->pLeft;
57016    op = pExpr->op;
57017    negInt = -1;
57018    zNeg = "-";
57019  }
57020
57021  if( op==TK_STRING || op==TK_FLOAT || op==TK_INTEGER ){
57022    pVal = sqlite3ValueNew(db);
57023    if( pVal==0 ) goto no_mem;
57024    if( ExprHasProperty(pExpr, EP_IntValue) ){
57025      sqlite3VdbeMemSetInt64(pVal, (i64)pExpr->u.iValue*negInt);
57026    }else{
57027      zVal = sqlite3MPrintf(db, "%s%s", zNeg, pExpr->u.zToken);
57028      if( zVal==0 ) goto no_mem;
57029      sqlite3ValueSetStr(pVal, -1, zVal, SQLITE_UTF8, SQLITE_DYNAMIC);
57030      if( op==TK_FLOAT ) pVal->type = SQLITE_FLOAT;
57031    }
57032    if( (op==TK_INTEGER || op==TK_FLOAT ) && affinity==SQLITE_AFF_NONE ){
57033      sqlite3ValueApplyAffinity(pVal, SQLITE_AFF_NUMERIC, SQLITE_UTF8);
57034    }else{
57035      sqlite3ValueApplyAffinity(pVal, affinity, SQLITE_UTF8);
57036    }
57037    if( pVal->flags & (MEM_Int|MEM_Real) ) pVal->flags &= ~MEM_Str;
57038    if( enc!=SQLITE_UTF8 ){
57039      sqlite3VdbeChangeEncoding(pVal, enc);
57040    }
57041  }else if( op==TK_UMINUS ) {
57042    /* This branch happens for multiple negative signs.  Ex: -(-5) */
57043    if( SQLITE_OK==sqlite3ValueFromExpr(db,pExpr->pLeft,enc,affinity,&pVal) ){
57044      sqlite3VdbeMemNumerify(pVal);
57045      if( pVal->u.i==SMALLEST_INT64 ){
57046        pVal->flags &= MEM_Int;
57047        pVal->flags |= MEM_Real;
57048        pVal->r = (double)LARGEST_INT64;
57049      }else{
57050        pVal->u.i = -pVal->u.i;
57051      }
57052      pVal->r = -pVal->r;
57053      sqlite3ValueApplyAffinity(pVal, affinity, enc);
57054    }
57055  }else if( op==TK_NULL ){
57056    pVal = sqlite3ValueNew(db);
57057    if( pVal==0 ) goto no_mem;
57058  }
57059#ifndef SQLITE_OMIT_BLOB_LITERAL
57060  else if( op==TK_BLOB ){
57061    int nVal;
57062    assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );
57063    assert( pExpr->u.zToken[1]=='\'' );
57064    pVal = sqlite3ValueNew(db);
57065    if( !pVal ) goto no_mem;
57066    zVal = &pExpr->u.zToken[2];
57067    nVal = sqlite3Strlen30(zVal)-1;
57068    assert( zVal[nVal]=='\'' );
57069    sqlite3VdbeMemSetStr(pVal, sqlite3HexToBlob(db, zVal, nVal), nVal/2,
57070                         0, SQLITE_DYNAMIC);
57071  }
57072#endif
57073
57074  if( pVal ){
57075    sqlite3VdbeMemStoreType(pVal);
57076  }
57077  *ppVal = pVal;
57078  return SQLITE_OK;
57079
57080no_mem:
57081  db->mallocFailed = 1;
57082  sqlite3DbFree(db, zVal);
57083  sqlite3ValueFree(pVal);
57084  *ppVal = 0;
57085  return SQLITE_NOMEM;
57086}
57087
57088/*
57089** Change the string value of an sqlite3_value object
57090*/
57091SQLITE_PRIVATE void sqlite3ValueSetStr(
57092  sqlite3_value *v,     /* Value to be set */
57093  int n,                /* Length of string z */
57094  const void *z,        /* Text of the new string */
57095  u8 enc,               /* Encoding to use */
57096  void (*xDel)(void*)   /* Destructor for the string */
57097){
57098  if( v ) sqlite3VdbeMemSetStr((Mem *)v, z, n, enc, xDel);
57099}
57100
57101/*
57102** Free an sqlite3_value object
57103*/
57104SQLITE_PRIVATE void sqlite3ValueFree(sqlite3_value *v){
57105  if( !v ) return;
57106  sqlite3VdbeMemRelease((Mem *)v);
57107  sqlite3DbFree(((Mem*)v)->db, v);
57108}
57109
57110/*
57111** Return the number of bytes in the sqlite3_value object assuming
57112** that it uses the encoding "enc"
57113*/
57114SQLITE_PRIVATE int sqlite3ValueBytes(sqlite3_value *pVal, u8 enc){
57115  Mem *p = (Mem*)pVal;
57116  if( (p->flags & MEM_Blob)!=0 || sqlite3ValueText(pVal, enc) ){
57117    if( p->flags & MEM_Zero ){
57118      return p->n + p->u.nZero;
57119    }else{
57120      return p->n;
57121    }
57122  }
57123  return 0;
57124}
57125
57126/************** End of vdbemem.c *********************************************/
57127/************** Begin file vdbeaux.c *****************************************/
57128/*
57129** 2003 September 6
57130**
57131** The author disclaims copyright to this source code.  In place of
57132** a legal notice, here is a blessing:
57133**
57134**    May you do good and not evil.
57135**    May you find forgiveness for yourself and forgive others.
57136**    May you share freely, never taking more than you give.
57137**
57138*************************************************************************
57139** This file contains code used for creating, destroying, and populating
57140** a VDBE (or an "sqlite3_stmt" as it is known to the outside world.)  Prior
57141** to version 2.8.7, all this code was combined into the vdbe.c source file.
57142** But that file was getting too big so this subroutines were split out.
57143*/
57144
57145
57146
57147/*
57148** When debugging the code generator in a symbolic debugger, one can
57149** set the sqlite3VdbeAddopTrace to 1 and all opcodes will be printed
57150** as they are added to the instruction stream.
57151*/
57152#ifdef SQLITE_DEBUG
57153SQLITE_PRIVATE int sqlite3VdbeAddopTrace = 0;
57154#endif
57155
57156
57157/*
57158** Create a new virtual database engine.
57159*/
57160SQLITE_PRIVATE Vdbe *sqlite3VdbeCreate(sqlite3 *db){
57161  Vdbe *p;
57162  p = sqlite3DbMallocZero(db, sizeof(Vdbe) );
57163  if( p==0 ) return 0;
57164  p->db = db;
57165  if( db->pVdbe ){
57166    db->pVdbe->pPrev = p;
57167  }
57168  p->pNext = db->pVdbe;
57169  p->pPrev = 0;
57170  db->pVdbe = p;
57171  p->magic = VDBE_MAGIC_INIT;
57172  return p;
57173}
57174
57175/*
57176** Remember the SQL string for a prepared statement.
57177*/
57178SQLITE_PRIVATE void sqlite3VdbeSetSql(Vdbe *p, const char *z, int n, int isPrepareV2){
57179  assert( isPrepareV2==1 || isPrepareV2==0 );
57180  if( p==0 ) return;
57181#ifdef SQLITE_OMIT_TRACE
57182  if( !isPrepareV2 ) return;
57183#endif
57184  assert( p->zSql==0 );
57185  p->zSql = sqlite3DbStrNDup(p->db, z, n);
57186  p->isPrepareV2 = (u8)isPrepareV2;
57187}
57188
57189/*
57190** Return the SQL associated with a prepared statement
57191*/
57192SQLITE_API const char *sqlite3_sql(sqlite3_stmt *pStmt){
57193  Vdbe *p = (Vdbe *)pStmt;
57194  return (p && p->isPrepareV2) ? p->zSql : 0;
57195}
57196
57197/*
57198** Swap all content between two VDBE structures.
57199*/
57200SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe *pA, Vdbe *pB){
57201  Vdbe tmp, *pTmp;
57202  char *zTmp;
57203  tmp = *pA;
57204  *pA = *pB;
57205  *pB = tmp;
57206  pTmp = pA->pNext;
57207  pA->pNext = pB->pNext;
57208  pB->pNext = pTmp;
57209  pTmp = pA->pPrev;
57210  pA->pPrev = pB->pPrev;
57211  pB->pPrev = pTmp;
57212  zTmp = pA->zSql;
57213  pA->zSql = pB->zSql;
57214  pB->zSql = zTmp;
57215  pB->isPrepareV2 = pA->isPrepareV2;
57216}
57217
57218#ifdef SQLITE_DEBUG
57219/*
57220** Turn tracing on or off
57221*/
57222SQLITE_PRIVATE void sqlite3VdbeTrace(Vdbe *p, FILE *trace){
57223  p->trace = trace;
57224}
57225#endif
57226
57227/*
57228** Resize the Vdbe.aOp array so that it is at least one op larger than
57229** it was.
57230**
57231** If an out-of-memory error occurs while resizing the array, return
57232** SQLITE_NOMEM. In this case Vdbe.aOp and Vdbe.nOpAlloc remain
57233** unchanged (this is so that any opcodes already allocated can be
57234** correctly deallocated along with the rest of the Vdbe).
57235*/
57236static int growOpArray(Vdbe *p){
57237  VdbeOp *pNew;
57238  int nNew = (p->nOpAlloc ? p->nOpAlloc*2 : (int)(1024/sizeof(Op)));
57239  pNew = sqlite3DbRealloc(p->db, p->aOp, nNew*sizeof(Op));
57240  if( pNew ){
57241    p->nOpAlloc = sqlite3DbMallocSize(p->db, pNew)/sizeof(Op);
57242    p->aOp = pNew;
57243  }
57244  return (pNew ? SQLITE_OK : SQLITE_NOMEM);
57245}
57246
57247/*
57248** Add a new instruction to the list of instructions current in the
57249** VDBE.  Return the address of the new instruction.
57250**
57251** Parameters:
57252**
57253**    p               Pointer to the VDBE
57254**
57255**    op              The opcode for this instruction
57256**
57257**    p1, p2, p3      Operands
57258**
57259** Use the sqlite3VdbeResolveLabel() function to fix an address and
57260** the sqlite3VdbeChangeP4() function to change the value of the P4
57261** operand.
57262*/
57263SQLITE_PRIVATE int sqlite3VdbeAddOp3(Vdbe *p, int op, int p1, int p2, int p3){
57264  int i;
57265  VdbeOp *pOp;
57266
57267  i = p->nOp;
57268  assert( p->magic==VDBE_MAGIC_INIT );
57269  assert( op>0 && op<0xff );
57270  if( p->nOpAlloc<=i ){
57271    if( growOpArray(p) ){
57272      return 1;
57273    }
57274  }
57275  p->nOp++;
57276  pOp = &p->aOp[i];
57277  pOp->opcode = (u8)op;
57278  pOp->p5 = 0;
57279  pOp->p1 = p1;
57280  pOp->p2 = p2;
57281  pOp->p3 = p3;
57282  pOp->p4.p = 0;
57283  pOp->p4type = P4_NOTUSED;
57284  p->expired = 0;
57285  if( op==OP_ParseSchema ){
57286    /* Any program that uses the OP_ParseSchema opcode needs to lock
57287    ** all btrees. */
57288    int j;
57289    for(j=0; j<p->db->nDb; j++) sqlite3VdbeUsesBtree(p, j);
57290  }
57291#ifdef SQLITE_DEBUG
57292  pOp->zComment = 0;
57293  if( sqlite3VdbeAddopTrace ) sqlite3VdbePrintOp(0, i, &p->aOp[i]);
57294#endif
57295#ifdef VDBE_PROFILE
57296  pOp->cycles = 0;
57297  pOp->cnt = 0;
57298#endif
57299  return i;
57300}
57301SQLITE_PRIVATE int sqlite3VdbeAddOp0(Vdbe *p, int op){
57302  return sqlite3VdbeAddOp3(p, op, 0, 0, 0);
57303}
57304SQLITE_PRIVATE int sqlite3VdbeAddOp1(Vdbe *p, int op, int p1){
57305  return sqlite3VdbeAddOp3(p, op, p1, 0, 0);
57306}
57307SQLITE_PRIVATE int sqlite3VdbeAddOp2(Vdbe *p, int op, int p1, int p2){
57308  return sqlite3VdbeAddOp3(p, op, p1, p2, 0);
57309}
57310
57311
57312/*
57313** Add an opcode that includes the p4 value as a pointer.
57314*/
57315SQLITE_PRIVATE int sqlite3VdbeAddOp4(
57316  Vdbe *p,            /* Add the opcode to this VM */
57317  int op,             /* The new opcode */
57318  int p1,             /* The P1 operand */
57319  int p2,             /* The P2 operand */
57320  int p3,             /* The P3 operand */
57321  const char *zP4,    /* The P4 operand */
57322  int p4type          /* P4 operand type */
57323){
57324  int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3);
57325  sqlite3VdbeChangeP4(p, addr, zP4, p4type);
57326  return addr;
57327}
57328
57329/*
57330** Add an opcode that includes the p4 value as an integer.
57331*/
57332SQLITE_PRIVATE int sqlite3VdbeAddOp4Int(
57333  Vdbe *p,            /* Add the opcode to this VM */
57334  int op,             /* The new opcode */
57335  int p1,             /* The P1 operand */
57336  int p2,             /* The P2 operand */
57337  int p3,             /* The P3 operand */
57338  int p4              /* The P4 operand as an integer */
57339){
57340  int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3);
57341  sqlite3VdbeChangeP4(p, addr, SQLITE_INT_TO_PTR(p4), P4_INT32);
57342  return addr;
57343}
57344
57345/*
57346** Create a new symbolic label for an instruction that has yet to be
57347** coded.  The symbolic label is really just a negative number.  The
57348** label can be used as the P2 value of an operation.  Later, when
57349** the label is resolved to a specific address, the VDBE will scan
57350** through its operation list and change all values of P2 which match
57351** the label into the resolved address.
57352**
57353** The VDBE knows that a P2 value is a label because labels are
57354** always negative and P2 values are suppose to be non-negative.
57355** Hence, a negative P2 value is a label that has yet to be resolved.
57356**
57357** Zero is returned if a malloc() fails.
57358*/
57359SQLITE_PRIVATE int sqlite3VdbeMakeLabel(Vdbe *p){
57360  int i;
57361  i = p->nLabel++;
57362  assert( p->magic==VDBE_MAGIC_INIT );
57363  if( i>=p->nLabelAlloc ){
57364    int n = p->nLabelAlloc*2 + 5;
57365    p->aLabel = sqlite3DbReallocOrFree(p->db, p->aLabel,
57366                                       n*sizeof(p->aLabel[0]));
57367    p->nLabelAlloc = sqlite3DbMallocSize(p->db, p->aLabel)/sizeof(p->aLabel[0]);
57368  }
57369  if( p->aLabel ){
57370    p->aLabel[i] = -1;
57371  }
57372  return -1-i;
57373}
57374
57375/*
57376** Resolve label "x" to be the address of the next instruction to
57377** be inserted.  The parameter "x" must have been obtained from
57378** a prior call to sqlite3VdbeMakeLabel().
57379*/
57380SQLITE_PRIVATE void sqlite3VdbeResolveLabel(Vdbe *p, int x){
57381  int j = -1-x;
57382  assert( p->magic==VDBE_MAGIC_INIT );
57383  assert( j>=0 && j<p->nLabel );
57384  if( p->aLabel ){
57385    p->aLabel[j] = p->nOp;
57386  }
57387}
57388
57389/*
57390** Mark the VDBE as one that can only be run one time.
57391*/
57392SQLITE_PRIVATE void sqlite3VdbeRunOnlyOnce(Vdbe *p){
57393  p->runOnlyOnce = 1;
57394}
57395
57396#ifdef SQLITE_DEBUG /* sqlite3AssertMayAbort() logic */
57397
57398/*
57399** The following type and function are used to iterate through all opcodes
57400** in a Vdbe main program and each of the sub-programs (triggers) it may
57401** invoke directly or indirectly. It should be used as follows:
57402**
57403**   Op *pOp;
57404**   VdbeOpIter sIter;
57405**
57406**   memset(&sIter, 0, sizeof(sIter));
57407**   sIter.v = v;                            // v is of type Vdbe*
57408**   while( (pOp = opIterNext(&sIter)) ){
57409**     // Do something with pOp
57410**   }
57411**   sqlite3DbFree(v->db, sIter.apSub);
57412**
57413*/
57414typedef struct VdbeOpIter VdbeOpIter;
57415struct VdbeOpIter {
57416  Vdbe *v;                   /* Vdbe to iterate through the opcodes of */
57417  SubProgram **apSub;        /* Array of subprograms */
57418  int nSub;                  /* Number of entries in apSub */
57419  int iAddr;                 /* Address of next instruction to return */
57420  int iSub;                  /* 0 = main program, 1 = first sub-program etc. */
57421};
57422static Op *opIterNext(VdbeOpIter *p){
57423  Vdbe *v = p->v;
57424  Op *pRet = 0;
57425  Op *aOp;
57426  int nOp;
57427
57428  if( p->iSub<=p->nSub ){
57429
57430    if( p->iSub==0 ){
57431      aOp = v->aOp;
57432      nOp = v->nOp;
57433    }else{
57434      aOp = p->apSub[p->iSub-1]->aOp;
57435      nOp = p->apSub[p->iSub-1]->nOp;
57436    }
57437    assert( p->iAddr<nOp );
57438
57439    pRet = &aOp[p->iAddr];
57440    p->iAddr++;
57441    if( p->iAddr==nOp ){
57442      p->iSub++;
57443      p->iAddr = 0;
57444    }
57445
57446    if( pRet->p4type==P4_SUBPROGRAM ){
57447      int nByte = (p->nSub+1)*sizeof(SubProgram*);
57448      int j;
57449      for(j=0; j<p->nSub; j++){
57450        if( p->apSub[j]==pRet->p4.pProgram ) break;
57451      }
57452      if( j==p->nSub ){
57453        p->apSub = sqlite3DbReallocOrFree(v->db, p->apSub, nByte);
57454        if( !p->apSub ){
57455          pRet = 0;
57456        }else{
57457          p->apSub[p->nSub++] = pRet->p4.pProgram;
57458        }
57459      }
57460    }
57461  }
57462
57463  return pRet;
57464}
57465
57466/*
57467** Check if the program stored in the VM associated with pParse may
57468** throw an ABORT exception (causing the statement, but not entire transaction
57469** to be rolled back). This condition is true if the main program or any
57470** sub-programs contains any of the following:
57471**
57472**   *  OP_Halt with P1=SQLITE_CONSTRAINT and P2=OE_Abort.
57473**   *  OP_HaltIfNull with P1=SQLITE_CONSTRAINT and P2=OE_Abort.
57474**   *  OP_Destroy
57475**   *  OP_VUpdate
57476**   *  OP_VRename
57477**   *  OP_FkCounter with P2==0 (immediate foreign key constraint)
57478**
57479** Then check that the value of Parse.mayAbort is true if an
57480** ABORT may be thrown, or false otherwise. Return true if it does
57481** match, or false otherwise. This function is intended to be used as
57482** part of an assert statement in the compiler. Similar to:
57483**
57484**   assert( sqlite3VdbeAssertMayAbort(pParse->pVdbe, pParse->mayAbort) );
57485*/
57486SQLITE_PRIVATE int sqlite3VdbeAssertMayAbort(Vdbe *v, int mayAbort){
57487  int hasAbort = 0;
57488  Op *pOp;
57489  VdbeOpIter sIter;
57490  memset(&sIter, 0, sizeof(sIter));
57491  sIter.v = v;
57492
57493  while( (pOp = opIterNext(&sIter))!=0 ){
57494    int opcode = pOp->opcode;
57495    if( opcode==OP_Destroy || opcode==OP_VUpdate || opcode==OP_VRename
57496#ifndef SQLITE_OMIT_FOREIGN_KEY
57497     || (opcode==OP_FkCounter && pOp->p1==0 && pOp->p2==1)
57498#endif
57499     || ((opcode==OP_Halt || opcode==OP_HaltIfNull)
57500      && (pOp->p1==SQLITE_CONSTRAINT && pOp->p2==OE_Abort))
57501    ){
57502      hasAbort = 1;
57503      break;
57504    }
57505  }
57506  sqlite3DbFree(v->db, sIter.apSub);
57507
57508  /* Return true if hasAbort==mayAbort. Or if a malloc failure occured.
57509  ** If malloc failed, then the while() loop above may not have iterated
57510  ** through all opcodes and hasAbort may be set incorrectly. Return
57511  ** true for this case to prevent the assert() in the callers frame
57512  ** from failing.  */
57513  return ( v->db->mallocFailed || hasAbort==mayAbort );
57514}
57515#endif /* SQLITE_DEBUG - the sqlite3AssertMayAbort() function */
57516
57517/*
57518** Loop through the program looking for P2 values that are negative
57519** on jump instructions.  Each such value is a label.  Resolve the
57520** label by setting the P2 value to its correct non-zero value.
57521**
57522** This routine is called once after all opcodes have been inserted.
57523**
57524** Variable *pMaxFuncArgs is set to the maximum value of any P2 argument
57525** to an OP_Function, OP_AggStep or OP_VFilter opcode. This is used by
57526** sqlite3VdbeMakeReady() to size the Vdbe.apArg[] array.
57527**
57528** The Op.opflags field is set on all opcodes.
57529*/
57530static void resolveP2Values(Vdbe *p, int *pMaxFuncArgs){
57531  int i;
57532  int nMaxArgs = *pMaxFuncArgs;
57533  Op *pOp;
57534  int *aLabel = p->aLabel;
57535  p->readOnly = 1;
57536  for(pOp=p->aOp, i=p->nOp-1; i>=0; i--, pOp++){
57537    u8 opcode = pOp->opcode;
57538
57539    pOp->opflags = sqlite3OpcodeProperty[opcode];
57540    if( opcode==OP_Function || opcode==OP_AggStep ){
57541      if( pOp->p5>nMaxArgs ) nMaxArgs = pOp->p5;
57542    }else if( (opcode==OP_Transaction && pOp->p2!=0) || opcode==OP_Vacuum ){
57543      p->readOnly = 0;
57544#ifndef SQLITE_OMIT_VIRTUALTABLE
57545    }else if( opcode==OP_VUpdate ){
57546      if( pOp->p2>nMaxArgs ) nMaxArgs = pOp->p2;
57547    }else if( opcode==OP_VFilter ){
57548      int n;
57549      assert( p->nOp - i >= 3 );
57550      assert( pOp[-1].opcode==OP_Integer );
57551      n = pOp[-1].p1;
57552      if( n>nMaxArgs ) nMaxArgs = n;
57553#endif
57554    }
57555
57556    if( (pOp->opflags & OPFLG_JUMP)!=0 && pOp->p2<0 ){
57557      assert( -1-pOp->p2<p->nLabel );
57558      pOp->p2 = aLabel[-1-pOp->p2];
57559    }
57560  }
57561  sqlite3DbFree(p->db, p->aLabel);
57562  p->aLabel = 0;
57563
57564  *pMaxFuncArgs = nMaxArgs;
57565}
57566
57567/*
57568** Return the address of the next instruction to be inserted.
57569*/
57570SQLITE_PRIVATE int sqlite3VdbeCurrentAddr(Vdbe *p){
57571  assert( p->magic==VDBE_MAGIC_INIT );
57572  return p->nOp;
57573}
57574
57575/*
57576** This function returns a pointer to the array of opcodes associated with
57577** the Vdbe passed as the first argument. It is the callers responsibility
57578** to arrange for the returned array to be eventually freed using the
57579** vdbeFreeOpArray() function.
57580**
57581** Before returning, *pnOp is set to the number of entries in the returned
57582** array. Also, *pnMaxArg is set to the larger of its current value and
57583** the number of entries in the Vdbe.apArg[] array required to execute the
57584** returned program.
57585*/
57586SQLITE_PRIVATE VdbeOp *sqlite3VdbeTakeOpArray(Vdbe *p, int *pnOp, int *pnMaxArg){
57587  VdbeOp *aOp = p->aOp;
57588  assert( aOp && !p->db->mallocFailed );
57589
57590  /* Check that sqlite3VdbeUsesBtree() was not called on this VM */
57591  assert( p->btreeMask==0 );
57592
57593  resolveP2Values(p, pnMaxArg);
57594  *pnOp = p->nOp;
57595  p->aOp = 0;
57596  return aOp;
57597}
57598
57599/*
57600** Add a whole list of operations to the operation stack.  Return the
57601** address of the first operation added.
57602*/
57603SQLITE_PRIVATE int sqlite3VdbeAddOpList(Vdbe *p, int nOp, VdbeOpList const *aOp){
57604  int addr;
57605  assert( p->magic==VDBE_MAGIC_INIT );
57606  if( p->nOp + nOp > p->nOpAlloc && growOpArray(p) ){
57607    return 0;
57608  }
57609  addr = p->nOp;
57610  if( ALWAYS(nOp>0) ){
57611    int i;
57612    VdbeOpList const *pIn = aOp;
57613    for(i=0; i<nOp; i++, pIn++){
57614      int p2 = pIn->p2;
57615      VdbeOp *pOut = &p->aOp[i+addr];
57616      pOut->opcode = pIn->opcode;
57617      pOut->p1 = pIn->p1;
57618      if( p2<0 && (sqlite3OpcodeProperty[pOut->opcode] & OPFLG_JUMP)!=0 ){
57619        pOut->p2 = addr + ADDR(p2);
57620      }else{
57621        pOut->p2 = p2;
57622      }
57623      pOut->p3 = pIn->p3;
57624      pOut->p4type = P4_NOTUSED;
57625      pOut->p4.p = 0;
57626      pOut->p5 = 0;
57627#ifdef SQLITE_DEBUG
57628      pOut->zComment = 0;
57629      if( sqlite3VdbeAddopTrace ){
57630        sqlite3VdbePrintOp(0, i+addr, &p->aOp[i+addr]);
57631      }
57632#endif
57633    }
57634    p->nOp += nOp;
57635  }
57636  return addr;
57637}
57638
57639/*
57640** Change the value of the P1 operand for a specific instruction.
57641** This routine is useful when a large program is loaded from a
57642** static array using sqlite3VdbeAddOpList but we want to make a
57643** few minor changes to the program.
57644*/
57645SQLITE_PRIVATE void sqlite3VdbeChangeP1(Vdbe *p, int addr, int val){
57646  assert( p!=0 );
57647  assert( addr>=0 );
57648  if( p->nOp>addr ){
57649    p->aOp[addr].p1 = val;
57650  }
57651}
57652
57653/*
57654** Change the value of the P2 operand for a specific instruction.
57655** This routine is useful for setting a jump destination.
57656*/
57657SQLITE_PRIVATE void sqlite3VdbeChangeP2(Vdbe *p, int addr, int val){
57658  assert( p!=0 );
57659  assert( addr>=0 );
57660  if( p->nOp>addr ){
57661    p->aOp[addr].p2 = val;
57662  }
57663}
57664
57665/*
57666** Change the value of the P3 operand for a specific instruction.
57667*/
57668SQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe *p, int addr, int val){
57669  assert( p!=0 );
57670  assert( addr>=0 );
57671  if( p->nOp>addr ){
57672    p->aOp[addr].p3 = val;
57673  }
57674}
57675
57676/*
57677** Change the value of the P5 operand for the most recently
57678** added operation.
57679*/
57680SQLITE_PRIVATE void sqlite3VdbeChangeP5(Vdbe *p, u8 val){
57681  assert( p!=0 );
57682  if( p->aOp ){
57683    assert( p->nOp>0 );
57684    p->aOp[p->nOp-1].p5 = val;
57685  }
57686}
57687
57688/*
57689** Change the P2 operand of instruction addr so that it points to
57690** the address of the next instruction to be coded.
57691*/
57692SQLITE_PRIVATE void sqlite3VdbeJumpHere(Vdbe *p, int addr){
57693  assert( addr>=0 );
57694  sqlite3VdbeChangeP2(p, addr, p->nOp);
57695}
57696
57697
57698/*
57699** If the input FuncDef structure is ephemeral, then free it.  If
57700** the FuncDef is not ephermal, then do nothing.
57701*/
57702static void freeEphemeralFunction(sqlite3 *db, FuncDef *pDef){
57703  if( ALWAYS(pDef) && (pDef->flags & SQLITE_FUNC_EPHEM)!=0 ){
57704    sqlite3DbFree(db, pDef);
57705  }
57706}
57707
57708static void vdbeFreeOpArray(sqlite3 *, Op *, int);
57709
57710/*
57711** Delete a P4 value if necessary.
57712*/
57713static void freeP4(sqlite3 *db, int p4type, void *p4){
57714  if( p4 ){
57715    assert( db );
57716    switch( p4type ){
57717      case P4_REAL:
57718      case P4_INT64:
57719      case P4_DYNAMIC:
57720      case P4_KEYINFO:
57721      case P4_INTARRAY:
57722      case P4_KEYINFO_HANDOFF: {
57723        sqlite3DbFree(db, p4);
57724        break;
57725      }
57726      case P4_MPRINTF: {
57727        if( db->pnBytesFreed==0 ) sqlite3_free(p4);
57728        break;
57729      }
57730      case P4_VDBEFUNC: {
57731        VdbeFunc *pVdbeFunc = (VdbeFunc *)p4;
57732        freeEphemeralFunction(db, pVdbeFunc->pFunc);
57733        if( db->pnBytesFreed==0 ) sqlite3VdbeDeleteAuxData(pVdbeFunc, 0);
57734        sqlite3DbFree(db, pVdbeFunc);
57735        break;
57736      }
57737      case P4_FUNCDEF: {
57738        freeEphemeralFunction(db, (FuncDef*)p4);
57739        break;
57740      }
57741      case P4_MEM: {
57742        if( db->pnBytesFreed==0 ){
57743          sqlite3ValueFree((sqlite3_value*)p4);
57744        }else{
57745          Mem *p = (Mem*)p4;
57746          sqlite3DbFree(db, p->zMalloc);
57747          sqlite3DbFree(db, p);
57748        }
57749        break;
57750      }
57751      case P4_VTAB : {
57752        if( db->pnBytesFreed==0 ) sqlite3VtabUnlock((VTable *)p4);
57753        break;
57754      }
57755    }
57756  }
57757}
57758
57759/*
57760** Free the space allocated for aOp and any p4 values allocated for the
57761** opcodes contained within. If aOp is not NULL it is assumed to contain
57762** nOp entries.
57763*/
57764static void vdbeFreeOpArray(sqlite3 *db, Op *aOp, int nOp){
57765  if( aOp ){
57766    Op *pOp;
57767    for(pOp=aOp; pOp<&aOp[nOp]; pOp++){
57768      freeP4(db, pOp->p4type, pOp->p4.p);
57769#ifdef SQLITE_DEBUG
57770      sqlite3DbFree(db, pOp->zComment);
57771#endif
57772    }
57773  }
57774  sqlite3DbFree(db, aOp);
57775}
57776
57777/*
57778** Link the SubProgram object passed as the second argument into the linked
57779** list at Vdbe.pSubProgram. This list is used to delete all sub-program
57780** objects when the VM is no longer required.
57781*/
57782SQLITE_PRIVATE void sqlite3VdbeLinkSubProgram(Vdbe *pVdbe, SubProgram *p){
57783  p->pNext = pVdbe->pProgram;
57784  pVdbe->pProgram = p;
57785}
57786
57787/*
57788** Change N opcodes starting at addr to No-ops.
57789*/
57790SQLITE_PRIVATE void sqlite3VdbeChangeToNoop(Vdbe *p, int addr, int N){
57791  if( p->aOp ){
57792    VdbeOp *pOp = &p->aOp[addr];
57793    sqlite3 *db = p->db;
57794    while( N-- ){
57795      freeP4(db, pOp->p4type, pOp->p4.p);
57796      memset(pOp, 0, sizeof(pOp[0]));
57797      pOp->opcode = OP_Noop;
57798      pOp++;
57799    }
57800  }
57801}
57802
57803/*
57804** Change the value of the P4 operand for a specific instruction.
57805** This routine is useful when a large program is loaded from a
57806** static array using sqlite3VdbeAddOpList but we want to make a
57807** few minor changes to the program.
57808**
57809** If n>=0 then the P4 operand is dynamic, meaning that a copy of
57810** the string is made into memory obtained from sqlite3_malloc().
57811** A value of n==0 means copy bytes of zP4 up to and including the
57812** first null byte.  If n>0 then copy n+1 bytes of zP4.
57813**
57814** If n==P4_KEYINFO it means that zP4 is a pointer to a KeyInfo structure.
57815** A copy is made of the KeyInfo structure into memory obtained from
57816** sqlite3_malloc, to be freed when the Vdbe is finalized.
57817** n==P4_KEYINFO_HANDOFF indicates that zP4 points to a KeyInfo structure
57818** stored in memory that the caller has obtained from sqlite3_malloc. The
57819** caller should not free the allocation, it will be freed when the Vdbe is
57820** finalized.
57821**
57822** Other values of n (P4_STATIC, P4_COLLSEQ etc.) indicate that zP4 points
57823** to a string or structure that is guaranteed to exist for the lifetime of
57824** the Vdbe. In these cases we can just copy the pointer.
57825**
57826** If addr<0 then change P4 on the most recently inserted instruction.
57827*/
57828SQLITE_PRIVATE void sqlite3VdbeChangeP4(Vdbe *p, int addr, const char *zP4, int n){
57829  Op *pOp;
57830  sqlite3 *db;
57831  assert( p!=0 );
57832  db = p->db;
57833  assert( p->magic==VDBE_MAGIC_INIT );
57834  if( p->aOp==0 || db->mallocFailed ){
57835    if ( n!=P4_KEYINFO && n!=P4_VTAB ) {
57836      freeP4(db, n, (void*)*(char**)&zP4);
57837    }
57838    return;
57839  }
57840  assert( p->nOp>0 );
57841  assert( addr<p->nOp );
57842  if( addr<0 ){
57843    addr = p->nOp - 1;
57844  }
57845  pOp = &p->aOp[addr];
57846  freeP4(db, pOp->p4type, pOp->p4.p);
57847  pOp->p4.p = 0;
57848  if( n==P4_INT32 ){
57849    /* Note: this cast is safe, because the origin data point was an int
57850    ** that was cast to a (const char *). */
57851    pOp->p4.i = SQLITE_PTR_TO_INT(zP4);
57852    pOp->p4type = P4_INT32;
57853  }else if( zP4==0 ){
57854    pOp->p4.p = 0;
57855    pOp->p4type = P4_NOTUSED;
57856  }else if( n==P4_KEYINFO ){
57857    KeyInfo *pKeyInfo;
57858    int nField, nByte;
57859
57860    nField = ((KeyInfo*)zP4)->nField;
57861    nByte = sizeof(*pKeyInfo) + (nField-1)*sizeof(pKeyInfo->aColl[0]) + nField;
57862    pKeyInfo = sqlite3DbMallocRaw(0, nByte);
57863    pOp->p4.pKeyInfo = pKeyInfo;
57864    if( pKeyInfo ){
57865      u8 *aSortOrder;
57866      memcpy((char*)pKeyInfo, zP4, nByte - nField);
57867      aSortOrder = pKeyInfo->aSortOrder;
57868      if( aSortOrder ){
57869        pKeyInfo->aSortOrder = (unsigned char*)&pKeyInfo->aColl[nField];
57870        memcpy(pKeyInfo->aSortOrder, aSortOrder, nField);
57871      }
57872      pOp->p4type = P4_KEYINFO;
57873    }else{
57874      p->db->mallocFailed = 1;
57875      pOp->p4type = P4_NOTUSED;
57876    }
57877  }else if( n==P4_KEYINFO_HANDOFF ){
57878    pOp->p4.p = (void*)zP4;
57879    pOp->p4type = P4_KEYINFO;
57880  }else if( n==P4_VTAB ){
57881    pOp->p4.p = (void*)zP4;
57882    pOp->p4type = P4_VTAB;
57883    sqlite3VtabLock((VTable *)zP4);
57884    assert( ((VTable *)zP4)->db==p->db );
57885  }else if( n<0 ){
57886    pOp->p4.p = (void*)zP4;
57887    pOp->p4type = (signed char)n;
57888  }else{
57889    if( n==0 ) n = sqlite3Strlen30(zP4);
57890    pOp->p4.z = sqlite3DbStrNDup(p->db, zP4, n);
57891    pOp->p4type = P4_DYNAMIC;
57892  }
57893}
57894
57895#ifndef NDEBUG
57896/*
57897** Change the comment on the the most recently coded instruction.  Or
57898** insert a No-op and add the comment to that new instruction.  This
57899** makes the code easier to read during debugging.  None of this happens
57900** in a production build.
57901*/
57902SQLITE_PRIVATE void sqlite3VdbeComment(Vdbe *p, const char *zFormat, ...){
57903  va_list ap;
57904  if( !p ) return;
57905  assert( p->nOp>0 || p->aOp==0 );
57906  assert( p->aOp==0 || p->aOp[p->nOp-1].zComment==0 || p->db->mallocFailed );
57907  if( p->nOp ){
57908    char **pz = &p->aOp[p->nOp-1].zComment;
57909    va_start(ap, zFormat);
57910    sqlite3DbFree(p->db, *pz);
57911    *pz = sqlite3VMPrintf(p->db, zFormat, ap);
57912    va_end(ap);
57913  }
57914}
57915SQLITE_PRIVATE void sqlite3VdbeNoopComment(Vdbe *p, const char *zFormat, ...){
57916  va_list ap;
57917  if( !p ) return;
57918  sqlite3VdbeAddOp0(p, OP_Noop);
57919  assert( p->nOp>0 || p->aOp==0 );
57920  assert( p->aOp==0 || p->aOp[p->nOp-1].zComment==0 || p->db->mallocFailed );
57921  if( p->nOp ){
57922    char **pz = &p->aOp[p->nOp-1].zComment;
57923    va_start(ap, zFormat);
57924    sqlite3DbFree(p->db, *pz);
57925    *pz = sqlite3VMPrintf(p->db, zFormat, ap);
57926    va_end(ap);
57927  }
57928}
57929#endif  /* NDEBUG */
57930
57931/*
57932** Return the opcode for a given address.  If the address is -1, then
57933** return the most recently inserted opcode.
57934**
57935** If a memory allocation error has occurred prior to the calling of this
57936** routine, then a pointer to a dummy VdbeOp will be returned.  That opcode
57937** is readable but not writable, though it is cast to a writable value.
57938** The return of a dummy opcode allows the call to continue functioning
57939** after a OOM fault without having to check to see if the return from
57940** this routine is a valid pointer.  But because the dummy.opcode is 0,
57941** dummy will never be written to.  This is verified by code inspection and
57942** by running with Valgrind.
57943**
57944** About the #ifdef SQLITE_OMIT_TRACE:  Normally, this routine is never called
57945** unless p->nOp>0.  This is because in the absense of SQLITE_OMIT_TRACE,
57946** an OP_Trace instruction is always inserted by sqlite3VdbeGet() as soon as
57947** a new VDBE is created.  So we are free to set addr to p->nOp-1 without
57948** having to double-check to make sure that the result is non-negative. But
57949** if SQLITE_OMIT_TRACE is defined, the OP_Trace is omitted and we do need to
57950** check the value of p->nOp-1 before continuing.
57951*/
57952SQLITE_PRIVATE VdbeOp *sqlite3VdbeGetOp(Vdbe *p, int addr){
57953  /* C89 specifies that the constant "dummy" will be initialized to all
57954  ** zeros, which is correct.  MSVC generates a warning, nevertheless. */
57955  static const VdbeOp dummy;  /* Ignore the MSVC warning about no initializer */
57956  assert( p->magic==VDBE_MAGIC_INIT );
57957  if( addr<0 ){
57958#ifdef SQLITE_OMIT_TRACE
57959    if( p->nOp==0 ) return (VdbeOp*)&dummy;
57960#endif
57961    addr = p->nOp - 1;
57962  }
57963  assert( (addr>=0 && addr<p->nOp) || p->db->mallocFailed );
57964  if( p->db->mallocFailed ){
57965    return (VdbeOp*)&dummy;
57966  }else{
57967    return &p->aOp[addr];
57968  }
57969}
57970
57971#if !defined(SQLITE_OMIT_EXPLAIN) || !defined(NDEBUG) \
57972     || defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
57973/*
57974** Compute a string that describes the P4 parameter for an opcode.
57975** Use zTemp for any required temporary buffer space.
57976*/
57977static char *displayP4(Op *pOp, char *zTemp, int nTemp){
57978  char *zP4 = zTemp;
57979  assert( nTemp>=20 );
57980  switch( pOp->p4type ){
57981    case P4_KEYINFO_STATIC:
57982    case P4_KEYINFO: {
57983      int i, j;
57984      KeyInfo *pKeyInfo = pOp->p4.pKeyInfo;
57985      sqlite3_snprintf(nTemp, zTemp, "keyinfo(%d", pKeyInfo->nField);
57986      i = sqlite3Strlen30(zTemp);
57987      for(j=0; j<pKeyInfo->nField; j++){
57988        CollSeq *pColl = pKeyInfo->aColl[j];
57989        if( pColl ){
57990          int n = sqlite3Strlen30(pColl->zName);
57991          if( i+n>nTemp-6 ){
57992            memcpy(&zTemp[i],",...",4);
57993            break;
57994          }
57995          zTemp[i++] = ',';
57996          if( pKeyInfo->aSortOrder && pKeyInfo->aSortOrder[j] ){
57997            zTemp[i++] = '-';
57998          }
57999          memcpy(&zTemp[i], pColl->zName,n+1);
58000          i += n;
58001        }else if( i+4<nTemp-6 ){
58002          memcpy(&zTemp[i],",nil",4);
58003          i += 4;
58004        }
58005      }
58006      zTemp[i++] = ')';
58007      zTemp[i] = 0;
58008      assert( i<nTemp );
58009      break;
58010    }
58011    case P4_COLLSEQ: {
58012      CollSeq *pColl = pOp->p4.pColl;
58013      sqlite3_snprintf(nTemp, zTemp, "collseq(%.20s)", pColl->zName);
58014      break;
58015    }
58016    case P4_FUNCDEF: {
58017      FuncDef *pDef = pOp->p4.pFunc;
58018      sqlite3_snprintf(nTemp, zTemp, "%s(%d)", pDef->zName, pDef->nArg);
58019      break;
58020    }
58021    case P4_INT64: {
58022      sqlite3_snprintf(nTemp, zTemp, "%lld", *pOp->p4.pI64);
58023      break;
58024    }
58025    case P4_INT32: {
58026      sqlite3_snprintf(nTemp, zTemp, "%d", pOp->p4.i);
58027      break;
58028    }
58029    case P4_REAL: {
58030      sqlite3_snprintf(nTemp, zTemp, "%.16g", *pOp->p4.pReal);
58031      break;
58032    }
58033    case P4_MEM: {
58034      Mem *pMem = pOp->p4.pMem;
58035      assert( (pMem->flags & MEM_Null)==0 );
58036      if( pMem->flags & MEM_Str ){
58037        zP4 = pMem->z;
58038      }else if( pMem->flags & MEM_Int ){
58039        sqlite3_snprintf(nTemp, zTemp, "%lld", pMem->u.i);
58040      }else if( pMem->flags & MEM_Real ){
58041        sqlite3_snprintf(nTemp, zTemp, "%.16g", pMem->r);
58042      }else{
58043        assert( pMem->flags & MEM_Blob );
58044        zP4 = "(blob)";
58045      }
58046      break;
58047    }
58048#ifndef SQLITE_OMIT_VIRTUALTABLE
58049    case P4_VTAB: {
58050      sqlite3_vtab *pVtab = pOp->p4.pVtab->pVtab;
58051      sqlite3_snprintf(nTemp, zTemp, "vtab:%p:%p", pVtab, pVtab->pModule);
58052      break;
58053    }
58054#endif
58055    case P4_INTARRAY: {
58056      sqlite3_snprintf(nTemp, zTemp, "intarray");
58057      break;
58058    }
58059    case P4_SUBPROGRAM: {
58060      sqlite3_snprintf(nTemp, zTemp, "program");
58061      break;
58062    }
58063    default: {
58064      zP4 = pOp->p4.z;
58065      if( zP4==0 ){
58066        zP4 = zTemp;
58067        zTemp[0] = 0;
58068      }
58069    }
58070  }
58071  assert( zP4!=0 );
58072  return zP4;
58073}
58074#endif
58075
58076/*
58077** Declare to the Vdbe that the BTree object at db->aDb[i] is used.
58078**
58079** The prepared statements need to know in advance the complete set of
58080** attached databases that they will be using.  A mask of these databases
58081** is maintained in p->btreeMask and is used for locking and other purposes.
58082*/
58083SQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe *p, int i){
58084  assert( i>=0 && i<p->db->nDb && i<(int)sizeof(yDbMask)*8 );
58085  assert( i<(int)sizeof(p->btreeMask)*8 );
58086  p->btreeMask |= ((yDbMask)1)<<i;
58087  if( i!=1 && sqlite3BtreeSharable(p->db->aDb[i].pBt) ){
58088    p->lockMask |= ((yDbMask)1)<<i;
58089  }
58090}
58091
58092#if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0
58093/*
58094** If SQLite is compiled to support shared-cache mode and to be threadsafe,
58095** this routine obtains the mutex associated with each BtShared structure
58096** that may be accessed by the VM passed as an argument. In doing so it also
58097** sets the BtShared.db member of each of the BtShared structures, ensuring
58098** that the correct busy-handler callback is invoked if required.
58099**
58100** If SQLite is not threadsafe but does support shared-cache mode, then
58101** sqlite3BtreeEnter() is invoked to set the BtShared.db variables
58102** of all of BtShared structures accessible via the database handle
58103** associated with the VM.
58104**
58105** If SQLite is not threadsafe and does not support shared-cache mode, this
58106** function is a no-op.
58107**
58108** The p->btreeMask field is a bitmask of all btrees that the prepared
58109** statement p will ever use.  Let N be the number of bits in p->btreeMask
58110** corresponding to btrees that use shared cache.  Then the runtime of
58111** this routine is N*N.  But as N is rarely more than 1, this should not
58112** be a problem.
58113*/
58114SQLITE_PRIVATE void sqlite3VdbeEnter(Vdbe *p){
58115  int i;
58116  yDbMask mask;
58117  sqlite3 *db;
58118  Db *aDb;
58119  int nDb;
58120  if( p->lockMask==0 ) return;  /* The common case */
58121  db = p->db;
58122  aDb = db->aDb;
58123  nDb = db->nDb;
58124  for(i=0, mask=1; i<nDb; i++, mask += mask){
58125    if( i!=1 && (mask & p->lockMask)!=0 && ALWAYS(aDb[i].pBt!=0) ){
58126      sqlite3BtreeEnter(aDb[i].pBt);
58127    }
58128  }
58129}
58130#endif
58131
58132#if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0
58133/*
58134** Unlock all of the btrees previously locked by a call to sqlite3VdbeEnter().
58135*/
58136SQLITE_PRIVATE void sqlite3VdbeLeave(Vdbe *p){
58137  int i;
58138  yDbMask mask;
58139  sqlite3 *db;
58140  Db *aDb;
58141  int nDb;
58142  if( p->lockMask==0 ) return;  /* The common case */
58143  db = p->db;
58144  aDb = db->aDb;
58145  nDb = db->nDb;
58146  for(i=0, mask=1; i<nDb; i++, mask += mask){
58147    if( i!=1 && (mask & p->lockMask)!=0 && ALWAYS(aDb[i].pBt!=0) ){
58148      sqlite3BtreeLeave(aDb[i].pBt);
58149    }
58150  }
58151}
58152#endif
58153
58154#if defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
58155/*
58156** Print a single opcode.  This routine is used for debugging only.
58157*/
58158SQLITE_PRIVATE void sqlite3VdbePrintOp(FILE *pOut, int pc, Op *pOp){
58159  char *zP4;
58160  char zPtr[50];
58161  static const char *zFormat1 = "%4d %-13s %4d %4d %4d %-4s %.2X %s\n";
58162  if( pOut==0 ) pOut = stdout;
58163  zP4 = displayP4(pOp, zPtr, sizeof(zPtr));
58164  fprintf(pOut, zFormat1, pc,
58165      sqlite3OpcodeName(pOp->opcode), pOp->p1, pOp->p2, pOp->p3, zP4, pOp->p5,
58166#ifdef SQLITE_DEBUG
58167      pOp->zComment ? pOp->zComment : ""
58168#else
58169      ""
58170#endif
58171  );
58172  fflush(pOut);
58173}
58174#endif
58175
58176/*
58177** Release an array of N Mem elements
58178*/
58179static void releaseMemArray(Mem *p, int N){
58180  if( p && N ){
58181    Mem *pEnd;
58182    sqlite3 *db = p->db;
58183    u8 malloc_failed = db->mallocFailed;
58184    if( db->pnBytesFreed ){
58185      for(pEnd=&p[N]; p<pEnd; p++){
58186        sqlite3DbFree(db, p->zMalloc);
58187      }
58188      return;
58189    }
58190    for(pEnd=&p[N]; p<pEnd; p++){
58191      assert( (&p[1])==pEnd || p[0].db==p[1].db );
58192
58193      /* This block is really an inlined version of sqlite3VdbeMemRelease()
58194      ** that takes advantage of the fact that the memory cell value is
58195      ** being set to NULL after releasing any dynamic resources.
58196      **
58197      ** The justification for duplicating code is that according to
58198      ** callgrind, this causes a certain test case to hit the CPU 4.7
58199      ** percent less (x86 linux, gcc version 4.1.2, -O6) than if
58200      ** sqlite3MemRelease() were called from here. With -O2, this jumps
58201      ** to 6.6 percent. The test case is inserting 1000 rows into a table
58202      ** with no indexes using a single prepared INSERT statement, bind()
58203      ** and reset(). Inserts are grouped into a transaction.
58204      */
58205      if( p->flags&(MEM_Agg|MEM_Dyn|MEM_Frame|MEM_RowSet) ){
58206        sqlite3VdbeMemRelease(p);
58207      }else if( p->zMalloc ){
58208        sqlite3DbFree(db, p->zMalloc);
58209        p->zMalloc = 0;
58210      }
58211
58212      p->flags = MEM_Null;
58213    }
58214    db->mallocFailed = malloc_failed;
58215  }
58216}
58217
58218/*
58219** Delete a VdbeFrame object and its contents. VdbeFrame objects are
58220** allocated by the OP_Program opcode in sqlite3VdbeExec().
58221*/
58222SQLITE_PRIVATE void sqlite3VdbeFrameDelete(VdbeFrame *p){
58223  int i;
58224  Mem *aMem = VdbeFrameMem(p);
58225  VdbeCursor **apCsr = (VdbeCursor **)&aMem[p->nChildMem];
58226  for(i=0; i<p->nChildCsr; i++){
58227    sqlite3VdbeFreeCursor(p->v, apCsr[i]);
58228  }
58229  releaseMemArray(aMem, p->nChildMem);
58230  sqlite3DbFree(p->v->db, p);
58231}
58232
58233#ifndef SQLITE_OMIT_EXPLAIN
58234/*
58235** Give a listing of the program in the virtual machine.
58236**
58237** The interface is the same as sqlite3VdbeExec().  But instead of
58238** running the code, it invokes the callback once for each instruction.
58239** This feature is used to implement "EXPLAIN".
58240**
58241** When p->explain==1, each instruction is listed.  When
58242** p->explain==2, only OP_Explain instructions are listed and these
58243** are shown in a different format.  p->explain==2 is used to implement
58244** EXPLAIN QUERY PLAN.
58245**
58246** When p->explain==1, first the main program is listed, then each of
58247** the trigger subprograms are listed one by one.
58248*/
58249SQLITE_PRIVATE int sqlite3VdbeList(
58250  Vdbe *p                   /* The VDBE */
58251){
58252  int nRow;                            /* Stop when row count reaches this */
58253  int nSub = 0;                        /* Number of sub-vdbes seen so far */
58254  SubProgram **apSub = 0;              /* Array of sub-vdbes */
58255  Mem *pSub = 0;                       /* Memory cell hold array of subprogs */
58256  sqlite3 *db = p->db;                 /* The database connection */
58257  int i;                               /* Loop counter */
58258  int rc = SQLITE_OK;                  /* Return code */
58259  Mem *pMem = p->pResultSet = &p->aMem[1];  /* First Mem of result set */
58260
58261  assert( p->explain );
58262  assert( p->magic==VDBE_MAGIC_RUN );
58263  assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY || p->rc==SQLITE_NOMEM );
58264
58265  /* Even though this opcode does not use dynamic strings for
58266  ** the result, result columns may become dynamic if the user calls
58267  ** sqlite3_column_text16(), causing a translation to UTF-16 encoding.
58268  */
58269  releaseMemArray(pMem, 8);
58270
58271  if( p->rc==SQLITE_NOMEM ){
58272    /* This happens if a malloc() inside a call to sqlite3_column_text() or
58273    ** sqlite3_column_text16() failed.  */
58274    db->mallocFailed = 1;
58275    return SQLITE_ERROR;
58276  }
58277
58278  /* When the number of output rows reaches nRow, that means the
58279  ** listing has finished and sqlite3_step() should return SQLITE_DONE.
58280  ** nRow is the sum of the number of rows in the main program, plus
58281  ** the sum of the number of rows in all trigger subprograms encountered
58282  ** so far.  The nRow value will increase as new trigger subprograms are
58283  ** encountered, but p->pc will eventually catch up to nRow.
58284  */
58285  nRow = p->nOp;
58286  if( p->explain==1 ){
58287    /* The first 8 memory cells are used for the result set.  So we will
58288    ** commandeer the 9th cell to use as storage for an array of pointers
58289    ** to trigger subprograms.  The VDBE is guaranteed to have at least 9
58290    ** cells.  */
58291    assert( p->nMem>9 );
58292    pSub = &p->aMem[9];
58293    if( pSub->flags&MEM_Blob ){
58294      /* On the first call to sqlite3_step(), pSub will hold a NULL.  It is
58295      ** initialized to a BLOB by the P4_SUBPROGRAM processing logic below */
58296      nSub = pSub->n/sizeof(Vdbe*);
58297      apSub = (SubProgram **)pSub->z;
58298    }
58299    for(i=0; i<nSub; i++){
58300      nRow += apSub[i]->nOp;
58301    }
58302  }
58303
58304  do{
58305    i = p->pc++;
58306  }while( i<nRow && p->explain==2 && p->aOp[i].opcode!=OP_Explain );
58307  if( i>=nRow ){
58308    p->rc = SQLITE_OK;
58309    rc = SQLITE_DONE;
58310  }else if( db->u1.isInterrupted ){
58311    p->rc = SQLITE_INTERRUPT;
58312    rc = SQLITE_ERROR;
58313    sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3ErrStr(p->rc));
58314  }else{
58315    char *z;
58316    Op *pOp;
58317    if( i<p->nOp ){
58318      /* The output line number is small enough that we are still in the
58319      ** main program. */
58320      pOp = &p->aOp[i];
58321    }else{
58322      /* We are currently listing subprograms.  Figure out which one and
58323      ** pick up the appropriate opcode. */
58324      int j;
58325      i -= p->nOp;
58326      for(j=0; i>=apSub[j]->nOp; j++){
58327        i -= apSub[j]->nOp;
58328      }
58329      pOp = &apSub[j]->aOp[i];
58330    }
58331    if( p->explain==1 ){
58332      pMem->flags = MEM_Int;
58333      pMem->type = SQLITE_INTEGER;
58334      pMem->u.i = i;                                /* Program counter */
58335      pMem++;
58336
58337      pMem->flags = MEM_Static|MEM_Str|MEM_Term;
58338      pMem->z = (char*)sqlite3OpcodeName(pOp->opcode);  /* Opcode */
58339      assert( pMem->z!=0 );
58340      pMem->n = sqlite3Strlen30(pMem->z);
58341      pMem->type = SQLITE_TEXT;
58342      pMem->enc = SQLITE_UTF8;
58343      pMem++;
58344
58345      /* When an OP_Program opcode is encounter (the only opcode that has
58346      ** a P4_SUBPROGRAM argument), expand the size of the array of subprograms
58347      ** kept in p->aMem[9].z to hold the new program - assuming this subprogram
58348      ** has not already been seen.
58349      */
58350      if( pOp->p4type==P4_SUBPROGRAM ){
58351        int nByte = (nSub+1)*sizeof(SubProgram*);
58352        int j;
58353        for(j=0; j<nSub; j++){
58354          if( apSub[j]==pOp->p4.pProgram ) break;
58355        }
58356        if( j==nSub && SQLITE_OK==sqlite3VdbeMemGrow(pSub, nByte, 1) ){
58357          apSub = (SubProgram **)pSub->z;
58358          apSub[nSub++] = pOp->p4.pProgram;
58359          pSub->flags |= MEM_Blob;
58360          pSub->n = nSub*sizeof(SubProgram*);
58361        }
58362      }
58363    }
58364
58365    pMem->flags = MEM_Int;
58366    pMem->u.i = pOp->p1;                          /* P1 */
58367    pMem->type = SQLITE_INTEGER;
58368    pMem++;
58369
58370    pMem->flags = MEM_Int;
58371    pMem->u.i = pOp->p2;                          /* P2 */
58372    pMem->type = SQLITE_INTEGER;
58373    pMem++;
58374
58375    pMem->flags = MEM_Int;
58376    pMem->u.i = pOp->p3;                          /* P3 */
58377    pMem->type = SQLITE_INTEGER;
58378    pMem++;
58379
58380    if( sqlite3VdbeMemGrow(pMem, 32, 0) ){            /* P4 */
58381      assert( p->db->mallocFailed );
58382      return SQLITE_ERROR;
58383    }
58384    pMem->flags = MEM_Dyn|MEM_Str|MEM_Term;
58385    z = displayP4(pOp, pMem->z, 32);
58386    if( z!=pMem->z ){
58387      sqlite3VdbeMemSetStr(pMem, z, -1, SQLITE_UTF8, 0);
58388    }else{
58389      assert( pMem->z!=0 );
58390      pMem->n = sqlite3Strlen30(pMem->z);
58391      pMem->enc = SQLITE_UTF8;
58392    }
58393    pMem->type = SQLITE_TEXT;
58394    pMem++;
58395
58396    if( p->explain==1 ){
58397      if( sqlite3VdbeMemGrow(pMem, 4, 0) ){
58398        assert( p->db->mallocFailed );
58399        return SQLITE_ERROR;
58400      }
58401      pMem->flags = MEM_Dyn|MEM_Str|MEM_Term;
58402      pMem->n = 2;
58403      sqlite3_snprintf(3, pMem->z, "%.2x", pOp->p5);   /* P5 */
58404      pMem->type = SQLITE_TEXT;
58405      pMem->enc = SQLITE_UTF8;
58406      pMem++;
58407
58408#ifdef SQLITE_DEBUG
58409      if( pOp->zComment ){
58410        pMem->flags = MEM_Str|MEM_Term;
58411        pMem->z = pOp->zComment;
58412        pMem->n = sqlite3Strlen30(pMem->z);
58413        pMem->enc = SQLITE_UTF8;
58414        pMem->type = SQLITE_TEXT;
58415      }else
58416#endif
58417      {
58418        pMem->flags = MEM_Null;                       /* Comment */
58419        pMem->type = SQLITE_NULL;
58420      }
58421    }
58422
58423    p->nResColumn = 8 - 4*(p->explain-1);
58424    p->rc = SQLITE_OK;
58425    rc = SQLITE_ROW;
58426  }
58427  return rc;
58428}
58429#endif /* SQLITE_OMIT_EXPLAIN */
58430
58431#ifdef SQLITE_DEBUG
58432/*
58433** Print the SQL that was used to generate a VDBE program.
58434*/
58435SQLITE_PRIVATE void sqlite3VdbePrintSql(Vdbe *p){
58436  int nOp = p->nOp;
58437  VdbeOp *pOp;
58438  if( nOp<1 ) return;
58439  pOp = &p->aOp[0];
58440  if( pOp->opcode==OP_Trace && pOp->p4.z!=0 ){
58441    const char *z = pOp->p4.z;
58442    while( sqlite3Isspace(*z) ) z++;
58443    printf("SQL: [%s]\n", z);
58444  }
58445}
58446#endif
58447
58448#if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
58449/*
58450** Print an IOTRACE message showing SQL content.
58451*/
58452SQLITE_PRIVATE void sqlite3VdbeIOTraceSql(Vdbe *p){
58453  int nOp = p->nOp;
58454  VdbeOp *pOp;
58455  if( sqlite3IoTrace==0 ) return;
58456  if( nOp<1 ) return;
58457  pOp = &p->aOp[0];
58458  if( pOp->opcode==OP_Trace && pOp->p4.z!=0 ){
58459    int i, j;
58460    char z[1000];
58461    sqlite3_snprintf(sizeof(z), z, "%s", pOp->p4.z);
58462    for(i=0; sqlite3Isspace(z[i]); i++){}
58463    for(j=0; z[i]; i++){
58464      if( sqlite3Isspace(z[i]) ){
58465        if( z[i-1]!=' ' ){
58466          z[j++] = ' ';
58467        }
58468      }else{
58469        z[j++] = z[i];
58470      }
58471    }
58472    z[j] = 0;
58473    sqlite3IoTrace("SQL %s\n", z);
58474  }
58475}
58476#endif /* !SQLITE_OMIT_TRACE && SQLITE_ENABLE_IOTRACE */
58477
58478/*
58479** Allocate space from a fixed size buffer and return a pointer to
58480** that space.  If insufficient space is available, return NULL.
58481**
58482** The pBuf parameter is the initial value of a pointer which will
58483** receive the new memory.  pBuf is normally NULL.  If pBuf is not
58484** NULL, it means that memory space has already been allocated and that
58485** this routine should not allocate any new memory.  When pBuf is not
58486** NULL simply return pBuf.  Only allocate new memory space when pBuf
58487** is NULL.
58488**
58489** nByte is the number of bytes of space needed.
58490**
58491** *ppFrom points to available space and pEnd points to the end of the
58492** available space.  When space is allocated, *ppFrom is advanced past
58493** the end of the allocated space.
58494**
58495** *pnByte is a counter of the number of bytes of space that have failed
58496** to allocate.  If there is insufficient space in *ppFrom to satisfy the
58497** request, then increment *pnByte by the amount of the request.
58498*/
58499static void *allocSpace(
58500  void *pBuf,          /* Where return pointer will be stored */
58501  int nByte,           /* Number of bytes to allocate */
58502  u8 **ppFrom,         /* IN/OUT: Allocate from *ppFrom */
58503  u8 *pEnd,            /* Pointer to 1 byte past the end of *ppFrom buffer */
58504  int *pnByte          /* If allocation cannot be made, increment *pnByte */
58505){
58506  assert( EIGHT_BYTE_ALIGNMENT(*ppFrom) );
58507  if( pBuf ) return pBuf;
58508  nByte = ROUND8(nByte);
58509  if( &(*ppFrom)[nByte] <= pEnd ){
58510    pBuf = (void*)*ppFrom;
58511    *ppFrom += nByte;
58512  }else{
58513    *pnByte += nByte;
58514  }
58515  return pBuf;
58516}
58517
58518/*
58519** Prepare a virtual machine for execution.  This involves things such
58520** as allocating stack space and initializing the program counter.
58521** After the VDBE has be prepped, it can be executed by one or more
58522** calls to sqlite3VdbeExec().
58523**
58524** This is the only way to move a VDBE from VDBE_MAGIC_INIT to
58525** VDBE_MAGIC_RUN.
58526**
58527** This function may be called more than once on a single virtual machine.
58528** The first call is made while compiling the SQL statement. Subsequent
58529** calls are made as part of the process of resetting a statement to be
58530** re-executed (from a call to sqlite3_reset()). The nVar, nMem, nCursor
58531** and isExplain parameters are only passed correct values the first time
58532** the function is called. On subsequent calls, from sqlite3_reset(), nVar
58533** is passed -1 and nMem, nCursor and isExplain are all passed zero.
58534*/
58535SQLITE_PRIVATE void sqlite3VdbeMakeReady(
58536  Vdbe *p,                       /* The VDBE */
58537  int nVar,                      /* Number of '?' see in the SQL statement */
58538  int nMem,                      /* Number of memory cells to allocate */
58539  int nCursor,                   /* Number of cursors to allocate */
58540  int nArg,                      /* Maximum number of args in SubPrograms */
58541  int isExplain,                 /* True if the EXPLAIN keywords is present */
58542  int usesStmtJournal            /* True to set Vdbe.usesStmtJournal */
58543){
58544  int n;
58545  sqlite3 *db = p->db;
58546
58547  assert( p!=0 );
58548  assert( p->magic==VDBE_MAGIC_INIT );
58549
58550  /* There should be at least one opcode.
58551  */
58552  assert( p->nOp>0 );
58553
58554  /* Set the magic to VDBE_MAGIC_RUN sooner rather than later. */
58555  p->magic = VDBE_MAGIC_RUN;
58556
58557  /* For each cursor required, also allocate a memory cell. Memory
58558  ** cells (nMem+1-nCursor)..nMem, inclusive, will never be used by
58559  ** the vdbe program. Instead they are used to allocate space for
58560  ** VdbeCursor/BtCursor structures. The blob of memory associated with
58561  ** cursor 0 is stored in memory cell nMem. Memory cell (nMem-1)
58562  ** stores the blob of memory associated with cursor 1, etc.
58563  **
58564  ** See also: allocateCursor().
58565  */
58566  nMem += nCursor;
58567
58568  /* Allocate space for memory registers, SQL variables, VDBE cursors and
58569  ** an array to marshal SQL function arguments in. This is only done the
58570  ** first time this function is called for a given VDBE, not when it is
58571  ** being called from sqlite3_reset() to reset the virtual machine.
58572  */
58573  if( nVar>=0 && ALWAYS(db->mallocFailed==0) ){
58574    u8 *zCsr = (u8 *)&p->aOp[p->nOp];       /* Memory avaliable for alloation */
58575    u8 *zEnd = (u8 *)&p->aOp[p->nOpAlloc];  /* First byte past available mem */
58576    int nByte;                              /* How much extra memory needed */
58577
58578    resolveP2Values(p, &nArg);
58579    p->usesStmtJournal = (u8)usesStmtJournal;
58580    if( isExplain && nMem<10 ){
58581      nMem = 10;
58582    }
58583    memset(zCsr, 0, zEnd-zCsr);
58584    zCsr += (zCsr - (u8*)0)&7;
58585    assert( EIGHT_BYTE_ALIGNMENT(zCsr) );
58586
58587    /* Memory for registers, parameters, cursor, etc, is allocated in two
58588    ** passes.  On the first pass, we try to reuse unused space at the
58589    ** end of the opcode array.  If we are unable to satisfy all memory
58590    ** requirements by reusing the opcode array tail, then the second
58591    ** pass will fill in the rest using a fresh allocation.
58592    **
58593    ** This two-pass approach that reuses as much memory as possible from
58594    ** the leftover space at the end of the opcode array can significantly
58595    ** reduce the amount of memory held by a prepared statement.
58596    */
58597    do {
58598      nByte = 0;
58599      p->aMem = allocSpace(p->aMem, nMem*sizeof(Mem), &zCsr, zEnd, &nByte);
58600      p->aVar = allocSpace(p->aVar, nVar*sizeof(Mem), &zCsr, zEnd, &nByte);
58601      p->apArg = allocSpace(p->apArg, nArg*sizeof(Mem*), &zCsr, zEnd, &nByte);
58602      p->azVar = allocSpace(p->azVar, nVar*sizeof(char*), &zCsr, zEnd, &nByte);
58603      p->apCsr = allocSpace(p->apCsr, nCursor*sizeof(VdbeCursor*),
58604                            &zCsr, zEnd, &nByte);
58605      if( nByte ){
58606        p->pFree = sqlite3DbMallocZero(db, nByte);
58607      }
58608      zCsr = p->pFree;
58609      zEnd = &zCsr[nByte];
58610    }while( nByte && !db->mallocFailed );
58611
58612    p->nCursor = (u16)nCursor;
58613    if( p->aVar ){
58614      p->nVar = (ynVar)nVar;
58615      for(n=0; n<nVar; n++){
58616        p->aVar[n].flags = MEM_Null;
58617        p->aVar[n].db = db;
58618      }
58619    }
58620    if( p->aMem ){
58621      p->aMem--;                      /* aMem[] goes from 1..nMem */
58622      p->nMem = nMem;                 /*       not from 0..nMem-1 */
58623      for(n=1; n<=nMem; n++){
58624        p->aMem[n].flags = MEM_Null;
58625        p->aMem[n].db = db;
58626      }
58627    }
58628  }
58629#ifdef SQLITE_DEBUG
58630  for(n=1; n<p->nMem; n++){
58631    assert( p->aMem[n].db==db );
58632  }
58633#endif
58634
58635  p->pc = -1;
58636  p->rc = SQLITE_OK;
58637  p->errorAction = OE_Abort;
58638  p->explain |= isExplain;
58639  p->magic = VDBE_MAGIC_RUN;
58640  p->nChange = 0;
58641  p->cacheCtr = 1;
58642  p->minWriteFileFormat = 255;
58643  p->iStatement = 0;
58644  p->nFkConstraint = 0;
58645#ifdef VDBE_PROFILE
58646  {
58647    int i;
58648    for(i=0; i<p->nOp; i++){
58649      p->aOp[i].cnt = 0;
58650      p->aOp[i].cycles = 0;
58651    }
58652  }
58653#endif
58654}
58655
58656/*
58657** Close a VDBE cursor and release all the resources that cursor
58658** happens to hold.
58659*/
58660SQLITE_PRIVATE void sqlite3VdbeFreeCursor(Vdbe *p, VdbeCursor *pCx){
58661  if( pCx==0 ){
58662    return;
58663  }
58664  if( pCx->pBt ){
58665    sqlite3BtreeClose(pCx->pBt);
58666    /* The pCx->pCursor will be close automatically, if it exists, by
58667    ** the call above. */
58668  }else if( pCx->pCursor ){
58669    sqlite3BtreeCloseCursor(pCx->pCursor);
58670  }
58671#ifndef SQLITE_OMIT_VIRTUALTABLE
58672  if( pCx->pVtabCursor ){
58673    sqlite3_vtab_cursor *pVtabCursor = pCx->pVtabCursor;
58674    const sqlite3_module *pModule = pCx->pModule;
58675    p->inVtabMethod = 1;
58676    pModule->xClose(pVtabCursor);
58677    p->inVtabMethod = 0;
58678  }
58679#endif
58680}
58681
58682/*
58683** Copy the values stored in the VdbeFrame structure to its Vdbe. This
58684** is used, for example, when a trigger sub-program is halted to restore
58685** control to the main program.
58686*/
58687SQLITE_PRIVATE int sqlite3VdbeFrameRestore(VdbeFrame *pFrame){
58688  Vdbe *v = pFrame->v;
58689  v->aOp = pFrame->aOp;
58690  v->nOp = pFrame->nOp;
58691  v->aMem = pFrame->aMem;
58692  v->nMem = pFrame->nMem;
58693  v->apCsr = pFrame->apCsr;
58694  v->nCursor = pFrame->nCursor;
58695  v->db->lastRowid = pFrame->lastRowid;
58696  v->nChange = pFrame->nChange;
58697  return pFrame->pc;
58698}
58699
58700/*
58701** Close all cursors.
58702**
58703** Also release any dynamic memory held by the VM in the Vdbe.aMem memory
58704** cell array. This is necessary as the memory cell array may contain
58705** pointers to VdbeFrame objects, which may in turn contain pointers to
58706** open cursors.
58707*/
58708static void closeAllCursors(Vdbe *p){
58709  if( p->pFrame ){
58710    VdbeFrame *pFrame;
58711    for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
58712    sqlite3VdbeFrameRestore(pFrame);
58713  }
58714  p->pFrame = 0;
58715  p->nFrame = 0;
58716
58717  if( p->apCsr ){
58718    int i;
58719    for(i=0; i<p->nCursor; i++){
58720      VdbeCursor *pC = p->apCsr[i];
58721      if( pC ){
58722        sqlite3VdbeFreeCursor(p, pC);
58723        p->apCsr[i] = 0;
58724      }
58725    }
58726  }
58727  if( p->aMem ){
58728    releaseMemArray(&p->aMem[1], p->nMem);
58729  }
58730  while( p->pDelFrame ){
58731    VdbeFrame *pDel = p->pDelFrame;
58732    p->pDelFrame = pDel->pParent;
58733    sqlite3VdbeFrameDelete(pDel);
58734  }
58735}
58736
58737/*
58738** Clean up the VM after execution.
58739**
58740** This routine will automatically close any cursors, lists, and/or
58741** sorters that were left open.  It also deletes the values of
58742** variables in the aVar[] array.
58743*/
58744static void Cleanup(Vdbe *p){
58745  sqlite3 *db = p->db;
58746
58747#ifdef SQLITE_DEBUG
58748  /* Execute assert() statements to ensure that the Vdbe.apCsr[] and
58749  ** Vdbe.aMem[] arrays have already been cleaned up.  */
58750  int i;
58751  for(i=0; i<p->nCursor; i++) assert( p->apCsr==0 || p->apCsr[i]==0 );
58752  for(i=1; i<=p->nMem; i++) assert( p->aMem==0 || p->aMem[i].flags==MEM_Null );
58753#endif
58754
58755  sqlite3DbFree(db, p->zErrMsg);
58756  p->zErrMsg = 0;
58757  p->pResultSet = 0;
58758}
58759
58760/*
58761** Set the number of result columns that will be returned by this SQL
58762** statement. This is now set at compile time, rather than during
58763** execution of the vdbe program so that sqlite3_column_count() can
58764** be called on an SQL statement before sqlite3_step().
58765*/
58766SQLITE_PRIVATE void sqlite3VdbeSetNumCols(Vdbe *p, int nResColumn){
58767  Mem *pColName;
58768  int n;
58769  sqlite3 *db = p->db;
58770
58771  releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
58772  sqlite3DbFree(db, p->aColName);
58773  n = nResColumn*COLNAME_N;
58774  p->nResColumn = (u16)nResColumn;
58775  p->aColName = pColName = (Mem*)sqlite3DbMallocZero(db, sizeof(Mem)*n );
58776  if( p->aColName==0 ) return;
58777  while( n-- > 0 ){
58778    pColName->flags = MEM_Null;
58779    pColName->db = p->db;
58780    pColName++;
58781  }
58782}
58783
58784/*
58785** Set the name of the idx'th column to be returned by the SQL statement.
58786** zName must be a pointer to a nul terminated string.
58787**
58788** This call must be made after a call to sqlite3VdbeSetNumCols().
58789**
58790** The final parameter, xDel, must be one of SQLITE_DYNAMIC, SQLITE_STATIC
58791** or SQLITE_TRANSIENT. If it is SQLITE_DYNAMIC, then the buffer pointed
58792** to by zName will be freed by sqlite3DbFree() when the vdbe is destroyed.
58793*/
58794SQLITE_PRIVATE int sqlite3VdbeSetColName(
58795  Vdbe *p,                         /* Vdbe being configured */
58796  int idx,                         /* Index of column zName applies to */
58797  int var,                         /* One of the COLNAME_* constants */
58798  const char *zName,               /* Pointer to buffer containing name */
58799  void (*xDel)(void*)              /* Memory management strategy for zName */
58800){
58801  int rc;
58802  Mem *pColName;
58803  assert( idx<p->nResColumn );
58804  assert( var<COLNAME_N );
58805  if( p->db->mallocFailed ){
58806    assert( !zName || xDel!=SQLITE_DYNAMIC );
58807    return SQLITE_NOMEM;
58808  }
58809  assert( p->aColName!=0 );
58810  pColName = &(p->aColName[idx+var*p->nResColumn]);
58811  rc = sqlite3VdbeMemSetStr(pColName, zName, -1, SQLITE_UTF8, xDel);
58812  assert( rc!=0 || !zName || (pColName->flags&MEM_Term)!=0 );
58813  return rc;
58814}
58815
58816/*
58817** A read or write transaction may or may not be active on database handle
58818** db. If a transaction is active, commit it. If there is a
58819** write-transaction spanning more than one database file, this routine
58820** takes care of the master journal trickery.
58821*/
58822static int vdbeCommit(sqlite3 *db, Vdbe *p){
58823  int i;
58824  int nTrans = 0;  /* Number of databases with an active write-transaction */
58825  int rc = SQLITE_OK;
58826  int needXcommit = 0;
58827
58828#ifdef SQLITE_OMIT_VIRTUALTABLE
58829  /* With this option, sqlite3VtabSync() is defined to be simply
58830  ** SQLITE_OK so p is not used.
58831  */
58832  UNUSED_PARAMETER(p);
58833#endif
58834
58835  /* Before doing anything else, call the xSync() callback for any
58836  ** virtual module tables written in this transaction. This has to
58837  ** be done before determining whether a master journal file is
58838  ** required, as an xSync() callback may add an attached database
58839  ** to the transaction.
58840  */
58841  rc = sqlite3VtabSync(db, &p->zErrMsg);
58842
58843  /* This loop determines (a) if the commit hook should be invoked and
58844  ** (b) how many database files have open write transactions, not
58845  ** including the temp database. (b) is important because if more than
58846  ** one database file has an open write transaction, a master journal
58847  ** file is required for an atomic commit.
58848  */
58849  for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
58850    Btree *pBt = db->aDb[i].pBt;
58851    if( sqlite3BtreeIsInTrans(pBt) ){
58852      needXcommit = 1;
58853      if( i!=1 ) nTrans++;
58854      rc = sqlite3PagerExclusiveLock(sqlite3BtreePager(pBt));
58855    }
58856  }
58857  if( rc!=SQLITE_OK ){
58858    return rc;
58859  }
58860
58861  /* If there are any write-transactions at all, invoke the commit hook */
58862  if( needXcommit && db->xCommitCallback ){
58863    rc = db->xCommitCallback(db->pCommitArg);
58864    if( rc ){
58865      return SQLITE_CONSTRAINT;
58866    }
58867  }
58868
58869  /* The simple case - no more than one database file (not counting the
58870  ** TEMP database) has a transaction active.   There is no need for the
58871  ** master-journal.
58872  **
58873  ** If the return value of sqlite3BtreeGetFilename() is a zero length
58874  ** string, it means the main database is :memory: or a temp file.  In
58875  ** that case we do not support atomic multi-file commits, so use the
58876  ** simple case then too.
58877  */
58878  if( 0==sqlite3Strlen30(sqlite3BtreeGetFilename(db->aDb[0].pBt))
58879   || nTrans<=1
58880  ){
58881    for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
58882      Btree *pBt = db->aDb[i].pBt;
58883      if( pBt ){
58884        rc = sqlite3BtreeCommitPhaseOne(pBt, 0);
58885      }
58886    }
58887
58888    /* Do the commit only if all databases successfully complete phase 1.
58889    ** If one of the BtreeCommitPhaseOne() calls fails, this indicates an
58890    ** IO error while deleting or truncating a journal file. It is unlikely,
58891    ** but could happen. In this case abandon processing and return the error.
58892    */
58893    for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
58894      Btree *pBt = db->aDb[i].pBt;
58895      if( pBt ){
58896        rc = sqlite3BtreeCommitPhaseTwo(pBt, 0);
58897      }
58898    }
58899    if( rc==SQLITE_OK ){
58900      sqlite3VtabCommit(db);
58901    }
58902  }
58903
58904  /* The complex case - There is a multi-file write-transaction active.
58905  ** This requires a master journal file to ensure the transaction is
58906  ** committed atomicly.
58907  */
58908#ifndef SQLITE_OMIT_DISKIO
58909  else{
58910    sqlite3_vfs *pVfs = db->pVfs;
58911    int needSync = 0;
58912    char *zMaster = 0;   /* File-name for the master journal */
58913    char const *zMainFile = sqlite3BtreeGetFilename(db->aDb[0].pBt);
58914    sqlite3_file *pMaster = 0;
58915    i64 offset = 0;
58916    int res;
58917
58918    /* Select a master journal file name */
58919    do {
58920      u32 iRandom;
58921      sqlite3DbFree(db, zMaster);
58922      sqlite3_randomness(sizeof(iRandom), &iRandom);
58923      zMaster = sqlite3MPrintf(db, "%s-mj%08X", zMainFile, iRandom&0x7fffffff);
58924      if( !zMaster ){
58925        return SQLITE_NOMEM;
58926      }
58927      rc = sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS, &res);
58928    }while( rc==SQLITE_OK && res );
58929    if( rc==SQLITE_OK ){
58930      /* Open the master journal. */
58931      rc = sqlite3OsOpenMalloc(pVfs, zMaster, &pMaster,
58932          SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|
58933          SQLITE_OPEN_EXCLUSIVE|SQLITE_OPEN_MASTER_JOURNAL, 0
58934      );
58935    }
58936    if( rc!=SQLITE_OK ){
58937      sqlite3DbFree(db, zMaster);
58938      return rc;
58939    }
58940
58941    /* Write the name of each database file in the transaction into the new
58942    ** master journal file. If an error occurs at this point close
58943    ** and delete the master journal file. All the individual journal files
58944    ** still have 'null' as the master journal pointer, so they will roll
58945    ** back independently if a failure occurs.
58946    */
58947    for(i=0; i<db->nDb; i++){
58948      Btree *pBt = db->aDb[i].pBt;
58949      if( sqlite3BtreeIsInTrans(pBt) ){
58950        char const *zFile = sqlite3BtreeGetJournalname(pBt);
58951        if( zFile==0 ){
58952          continue;  /* Ignore TEMP and :memory: databases */
58953        }
58954        assert( zFile[0]!=0 );
58955        if( !needSync && !sqlite3BtreeSyncDisabled(pBt) ){
58956          needSync = 1;
58957        }
58958        rc = sqlite3OsWrite(pMaster, zFile, sqlite3Strlen30(zFile)+1, offset);
58959        offset += sqlite3Strlen30(zFile)+1;
58960        if( rc!=SQLITE_OK ){
58961          sqlite3OsCloseFree(pMaster);
58962          sqlite3OsDelete(pVfs, zMaster, 0);
58963          sqlite3DbFree(db, zMaster);
58964          return rc;
58965        }
58966      }
58967    }
58968
58969    /* Sync the master journal file. If the IOCAP_SEQUENTIAL device
58970    ** flag is set this is not required.
58971    */
58972    if( needSync
58973     && 0==(sqlite3OsDeviceCharacteristics(pMaster)&SQLITE_IOCAP_SEQUENTIAL)
58974     && SQLITE_OK!=(rc = sqlite3OsSync(pMaster, SQLITE_SYNC_NORMAL))
58975    ){
58976      sqlite3OsCloseFree(pMaster);
58977      sqlite3OsDelete(pVfs, zMaster, 0);
58978      sqlite3DbFree(db, zMaster);
58979      return rc;
58980    }
58981
58982    /* Sync all the db files involved in the transaction. The same call
58983    ** sets the master journal pointer in each individual journal. If
58984    ** an error occurs here, do not delete the master journal file.
58985    **
58986    ** If the error occurs during the first call to
58987    ** sqlite3BtreeCommitPhaseOne(), then there is a chance that the
58988    ** master journal file will be orphaned. But we cannot delete it,
58989    ** in case the master journal file name was written into the journal
58990    ** file before the failure occurred.
58991    */
58992    for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
58993      Btree *pBt = db->aDb[i].pBt;
58994      if( pBt ){
58995        rc = sqlite3BtreeCommitPhaseOne(pBt, zMaster);
58996      }
58997    }
58998    sqlite3OsCloseFree(pMaster);
58999    assert( rc!=SQLITE_BUSY );
59000    if( rc!=SQLITE_OK ){
59001      sqlite3DbFree(db, zMaster);
59002      return rc;
59003    }
59004
59005    /* Delete the master journal file. This commits the transaction. After
59006    ** doing this the directory is synced again before any individual
59007    ** transaction files are deleted.
59008    */
59009    rc = sqlite3OsDelete(pVfs, zMaster, 1);
59010    sqlite3DbFree(db, zMaster);
59011    zMaster = 0;
59012    if( rc ){
59013      return rc;
59014    }
59015
59016    /* All files and directories have already been synced, so the following
59017    ** calls to sqlite3BtreeCommitPhaseTwo() are only closing files and
59018    ** deleting or truncating journals. If something goes wrong while
59019    ** this is happening we don't really care. The integrity of the
59020    ** transaction is already guaranteed, but some stray 'cold' journals
59021    ** may be lying around. Returning an error code won't help matters.
59022    */
59023    disable_simulated_io_errors();
59024    sqlite3BeginBenignMalloc();
59025    for(i=0; i<db->nDb; i++){
59026      Btree *pBt = db->aDb[i].pBt;
59027      if( pBt ){
59028        sqlite3BtreeCommitPhaseTwo(pBt, 1);
59029      }
59030    }
59031    sqlite3EndBenignMalloc();
59032    enable_simulated_io_errors();
59033
59034    sqlite3VtabCommit(db);
59035  }
59036#endif
59037
59038  return rc;
59039}
59040
59041/*
59042** This routine checks that the sqlite3.activeVdbeCnt count variable
59043** matches the number of vdbe's in the list sqlite3.pVdbe that are
59044** currently active. An assertion fails if the two counts do not match.
59045** This is an internal self-check only - it is not an essential processing
59046** step.
59047**
59048** This is a no-op if NDEBUG is defined.
59049*/
59050#ifndef NDEBUG
59051static void checkActiveVdbeCnt(sqlite3 *db){
59052  Vdbe *p;
59053  int cnt = 0;
59054  int nWrite = 0;
59055  p = db->pVdbe;
59056  while( p ){
59057    if( p->magic==VDBE_MAGIC_RUN && p->pc>=0 ){
59058      cnt++;
59059      if( p->readOnly==0 ) nWrite++;
59060    }
59061    p = p->pNext;
59062  }
59063  assert( cnt==db->activeVdbeCnt );
59064  assert( nWrite==db->writeVdbeCnt );
59065}
59066#else
59067#define checkActiveVdbeCnt(x)
59068#endif
59069
59070/*
59071** For every Btree that in database connection db which
59072** has been modified, "trip" or invalidate each cursor in
59073** that Btree might have been modified so that the cursor
59074** can never be used again.  This happens when a rollback
59075*** occurs.  We have to trip all the other cursors, even
59076** cursor from other VMs in different database connections,
59077** so that none of them try to use the data at which they
59078** were pointing and which now may have been changed due
59079** to the rollback.
59080**
59081** Remember that a rollback can delete tables complete and
59082** reorder rootpages.  So it is not sufficient just to save
59083** the state of the cursor.  We have to invalidate the cursor
59084** so that it is never used again.
59085*/
59086static void invalidateCursorsOnModifiedBtrees(sqlite3 *db){
59087  int i;
59088  for(i=0; i<db->nDb; i++){
59089    Btree *p = db->aDb[i].pBt;
59090    if( p && sqlite3BtreeIsInTrans(p) ){
59091      sqlite3BtreeTripAllCursors(p, SQLITE_ABORT);
59092    }
59093  }
59094}
59095
59096/*
59097** If the Vdbe passed as the first argument opened a statement-transaction,
59098** close it now. Argument eOp must be either SAVEPOINT_ROLLBACK or
59099** SAVEPOINT_RELEASE. If it is SAVEPOINT_ROLLBACK, then the statement
59100** transaction is rolled back. If eOp is SAVEPOINT_RELEASE, then the
59101** statement transaction is commtted.
59102**
59103** If an IO error occurs, an SQLITE_IOERR_XXX error code is returned.
59104** Otherwise SQLITE_OK.
59105*/
59106SQLITE_PRIVATE int sqlite3VdbeCloseStatement(Vdbe *p, int eOp){
59107  sqlite3 *const db = p->db;
59108  int rc = SQLITE_OK;
59109
59110  /* If p->iStatement is greater than zero, then this Vdbe opened a
59111  ** statement transaction that should be closed here. The only exception
59112  ** is that an IO error may have occured, causing an emergency rollback.
59113  ** In this case (db->nStatement==0), and there is nothing to do.
59114  */
59115  if( db->nStatement && p->iStatement ){
59116    int i;
59117    const int iSavepoint = p->iStatement-1;
59118
59119    assert( eOp==SAVEPOINT_ROLLBACK || eOp==SAVEPOINT_RELEASE);
59120    assert( db->nStatement>0 );
59121    assert( p->iStatement==(db->nStatement+db->nSavepoint) );
59122
59123    for(i=0; i<db->nDb; i++){
59124      int rc2 = SQLITE_OK;
59125      Btree *pBt = db->aDb[i].pBt;
59126      if( pBt ){
59127        if( eOp==SAVEPOINT_ROLLBACK ){
59128          rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_ROLLBACK, iSavepoint);
59129        }
59130        if( rc2==SQLITE_OK ){
59131          rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_RELEASE, iSavepoint);
59132        }
59133        if( rc==SQLITE_OK ){
59134          rc = rc2;
59135        }
59136      }
59137    }
59138    db->nStatement--;
59139    p->iStatement = 0;
59140
59141    /* If the statement transaction is being rolled back, also restore the
59142    ** database handles deferred constraint counter to the value it had when
59143    ** the statement transaction was opened.  */
59144    if( eOp==SAVEPOINT_ROLLBACK ){
59145      db->nDeferredCons = p->nStmtDefCons;
59146    }
59147  }
59148  return rc;
59149}
59150
59151/*
59152** This function is called when a transaction opened by the database
59153** handle associated with the VM passed as an argument is about to be
59154** committed. If there are outstanding deferred foreign key constraint
59155** violations, return SQLITE_ERROR. Otherwise, SQLITE_OK.
59156**
59157** If there are outstanding FK violations and this function returns
59158** SQLITE_ERROR, set the result of the VM to SQLITE_CONSTRAINT and write
59159** an error message to it. Then return SQLITE_ERROR.
59160*/
59161#ifndef SQLITE_OMIT_FOREIGN_KEY
59162SQLITE_PRIVATE int sqlite3VdbeCheckFk(Vdbe *p, int deferred){
59163  sqlite3 *db = p->db;
59164  if( (deferred && db->nDeferredCons>0) || (!deferred && p->nFkConstraint>0) ){
59165    p->rc = SQLITE_CONSTRAINT;
59166    p->errorAction = OE_Abort;
59167    sqlite3SetString(&p->zErrMsg, db, "foreign key constraint failed");
59168    return SQLITE_ERROR;
59169  }
59170  return SQLITE_OK;
59171}
59172#endif
59173
59174/*
59175** This routine is called the when a VDBE tries to halt.  If the VDBE
59176** has made changes and is in autocommit mode, then commit those
59177** changes.  If a rollback is needed, then do the rollback.
59178**
59179** This routine is the only way to move the state of a VM from
59180** SQLITE_MAGIC_RUN to SQLITE_MAGIC_HALT.  It is harmless to
59181** call this on a VM that is in the SQLITE_MAGIC_HALT state.
59182**
59183** Return an error code.  If the commit could not complete because of
59184** lock contention, return SQLITE_BUSY.  If SQLITE_BUSY is returned, it
59185** means the close did not happen and needs to be repeated.
59186*/
59187SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe *p){
59188  int rc;                         /* Used to store transient return codes */
59189  sqlite3 *db = p->db;
59190
59191  /* This function contains the logic that determines if a statement or
59192  ** transaction will be committed or rolled back as a result of the
59193  ** execution of this virtual machine.
59194  **
59195  ** If any of the following errors occur:
59196  **
59197  **     SQLITE_NOMEM
59198  **     SQLITE_IOERR
59199  **     SQLITE_FULL
59200  **     SQLITE_INTERRUPT
59201  **
59202  ** Then the internal cache might have been left in an inconsistent
59203  ** state.  We need to rollback the statement transaction, if there is
59204  ** one, or the complete transaction if there is no statement transaction.
59205  */
59206
59207  if( p->db->mallocFailed ){
59208    p->rc = SQLITE_NOMEM;
59209  }
59210  closeAllCursors(p);
59211  if( p->magic!=VDBE_MAGIC_RUN ){
59212    return SQLITE_OK;
59213  }
59214  checkActiveVdbeCnt(db);
59215
59216  /* No commit or rollback needed if the program never started */
59217  if( p->pc>=0 ){
59218    int mrc;   /* Primary error code from p->rc */
59219    int eStatementOp = 0;
59220    int isSpecialError;            /* Set to true if a 'special' error */
59221
59222    /* Lock all btrees used by the statement */
59223    sqlite3VdbeEnter(p);
59224
59225    /* Check for one of the special errors */
59226    mrc = p->rc & 0xff;
59227    assert( p->rc!=SQLITE_IOERR_BLOCKED );  /* This error no longer exists */
59228    isSpecialError = mrc==SQLITE_NOMEM || mrc==SQLITE_IOERR
59229                     || mrc==SQLITE_INTERRUPT || mrc==SQLITE_FULL;
59230    if( isSpecialError ){
59231      /* If the query was read-only and the error code is SQLITE_INTERRUPT,
59232      ** no rollback is necessary. Otherwise, at least a savepoint
59233      ** transaction must be rolled back to restore the database to a
59234      ** consistent state.
59235      **
59236      ** Even if the statement is read-only, it is important to perform
59237      ** a statement or transaction rollback operation. If the error
59238      ** occured while writing to the journal, sub-journal or database
59239      ** file as part of an effort to free up cache space (see function
59240      ** pagerStress() in pager.c), the rollback is required to restore
59241      ** the pager to a consistent state.
59242      */
59243      if( !p->readOnly || mrc!=SQLITE_INTERRUPT ){
59244        if( (mrc==SQLITE_NOMEM || mrc==SQLITE_FULL) && p->usesStmtJournal ){
59245          eStatementOp = SAVEPOINT_ROLLBACK;
59246        }else{
59247          /* We are forced to roll back the active transaction. Before doing
59248          ** so, abort any other statements this handle currently has active.
59249          */
59250          invalidateCursorsOnModifiedBtrees(db);
59251          sqlite3RollbackAll(db);
59252          sqlite3CloseSavepoints(db);
59253          db->autoCommit = 1;
59254        }
59255      }
59256    }
59257
59258    /* Check for immediate foreign key violations. */
59259    if( p->rc==SQLITE_OK ){
59260      sqlite3VdbeCheckFk(p, 0);
59261    }
59262
59263    /* If the auto-commit flag is set and this is the only active writer
59264    ** VM, then we do either a commit or rollback of the current transaction.
59265    **
59266    ** Note: This block also runs if one of the special errors handled
59267    ** above has occurred.
59268    */
59269    if( !sqlite3VtabInSync(db)
59270     && db->autoCommit
59271     && db->writeVdbeCnt==(p->readOnly==0)
59272    ){
59273      if( p->rc==SQLITE_OK || (p->errorAction==OE_Fail && !isSpecialError) ){
59274        rc = sqlite3VdbeCheckFk(p, 1);
59275        if( rc!=SQLITE_OK ){
59276          if( NEVER(p->readOnly) ){
59277            sqlite3VdbeLeave(p);
59278            return SQLITE_ERROR;
59279          }
59280          rc = SQLITE_CONSTRAINT;
59281        }else{
59282          /* The auto-commit flag is true, the vdbe program was successful
59283          ** or hit an 'OR FAIL' constraint and there are no deferred foreign
59284          ** key constraints to hold up the transaction. This means a commit
59285          ** is required. */
59286          rc = vdbeCommit(db, p);
59287        }
59288        if( rc==SQLITE_BUSY && p->readOnly ){
59289          sqlite3VdbeLeave(p);
59290          return SQLITE_BUSY;
59291        }else if( rc!=SQLITE_OK ){
59292          p->rc = rc;
59293          sqlite3RollbackAll(db);
59294        }else{
59295          db->nDeferredCons = 0;
59296          sqlite3CommitInternalChanges(db);
59297        }
59298      }else{
59299        sqlite3RollbackAll(db);
59300      }
59301      db->nStatement = 0;
59302    }else if( eStatementOp==0 ){
59303      if( p->rc==SQLITE_OK || p->errorAction==OE_Fail ){
59304        eStatementOp = SAVEPOINT_RELEASE;
59305      }else if( p->errorAction==OE_Abort ){
59306        eStatementOp = SAVEPOINT_ROLLBACK;
59307      }else{
59308        invalidateCursorsOnModifiedBtrees(db);
59309        sqlite3RollbackAll(db);
59310        sqlite3CloseSavepoints(db);
59311        db->autoCommit = 1;
59312      }
59313    }
59314
59315    /* If eStatementOp is non-zero, then a statement transaction needs to
59316    ** be committed or rolled back. Call sqlite3VdbeCloseStatement() to
59317    ** do so. If this operation returns an error, and the current statement
59318    ** error code is SQLITE_OK or SQLITE_CONSTRAINT, then promote the
59319    ** current statement error code.
59320    **
59321    ** Note that sqlite3VdbeCloseStatement() can only fail if eStatementOp
59322    ** is SAVEPOINT_ROLLBACK.  But if p->rc==SQLITE_OK then eStatementOp
59323    ** must be SAVEPOINT_RELEASE.  Hence the NEVER(p->rc==SQLITE_OK) in
59324    ** the following code.
59325    */
59326    if( eStatementOp ){
59327      rc = sqlite3VdbeCloseStatement(p, eStatementOp);
59328      if( rc ){
59329        assert( eStatementOp==SAVEPOINT_ROLLBACK );
59330        if( NEVER(p->rc==SQLITE_OK) || p->rc==SQLITE_CONSTRAINT ){
59331          p->rc = rc;
59332          sqlite3DbFree(db, p->zErrMsg);
59333          p->zErrMsg = 0;
59334        }
59335        invalidateCursorsOnModifiedBtrees(db);
59336        sqlite3RollbackAll(db);
59337        sqlite3CloseSavepoints(db);
59338        db->autoCommit = 1;
59339      }
59340    }
59341
59342    /* If this was an INSERT, UPDATE or DELETE and no statement transaction
59343    ** has been rolled back, update the database connection change-counter.
59344    */
59345    if( p->changeCntOn ){
59346      if( eStatementOp!=SAVEPOINT_ROLLBACK ){
59347        sqlite3VdbeSetChanges(db, p->nChange);
59348      }else{
59349        sqlite3VdbeSetChanges(db, 0);
59350      }
59351      p->nChange = 0;
59352    }
59353
59354    /* Rollback or commit any schema changes that occurred. */
59355    if( p->rc!=SQLITE_OK && db->flags&SQLITE_InternChanges ){
59356      sqlite3ResetInternalSchema(db, -1);
59357      db->flags = (db->flags | SQLITE_InternChanges);
59358    }
59359
59360    /* Release the locks */
59361    sqlite3VdbeLeave(p);
59362  }
59363
59364  /* We have successfully halted and closed the VM.  Record this fact. */
59365  if( p->pc>=0 ){
59366    db->activeVdbeCnt--;
59367    if( !p->readOnly ){
59368      db->writeVdbeCnt--;
59369    }
59370    assert( db->activeVdbeCnt>=db->writeVdbeCnt );
59371  }
59372  p->magic = VDBE_MAGIC_HALT;
59373  checkActiveVdbeCnt(db);
59374  if( p->db->mallocFailed ){
59375    p->rc = SQLITE_NOMEM;
59376  }
59377
59378  /* If the auto-commit flag is set to true, then any locks that were held
59379  ** by connection db have now been released. Call sqlite3ConnectionUnlocked()
59380  ** to invoke any required unlock-notify callbacks.
59381  */
59382  if( db->autoCommit ){
59383    sqlite3ConnectionUnlocked(db);
59384  }
59385
59386  assert( db->activeVdbeCnt>0 || db->autoCommit==0 || db->nStatement==0 );
59387  return (p->rc==SQLITE_BUSY ? SQLITE_BUSY : SQLITE_OK);
59388}
59389
59390
59391/*
59392** Each VDBE holds the result of the most recent sqlite3_step() call
59393** in p->rc.  This routine sets that result back to SQLITE_OK.
59394*/
59395SQLITE_PRIVATE void sqlite3VdbeResetStepResult(Vdbe *p){
59396  p->rc = SQLITE_OK;
59397}
59398
59399/*
59400** Clean up a VDBE after execution but do not delete the VDBE just yet.
59401** Write any error messages into *pzErrMsg.  Return the result code.
59402**
59403** After this routine is run, the VDBE should be ready to be executed
59404** again.
59405**
59406** To look at it another way, this routine resets the state of the
59407** virtual machine from VDBE_MAGIC_RUN or VDBE_MAGIC_HALT back to
59408** VDBE_MAGIC_INIT.
59409*/
59410SQLITE_PRIVATE int sqlite3VdbeReset(Vdbe *p){
59411  sqlite3 *db;
59412  db = p->db;
59413
59414  /* If the VM did not run to completion or if it encountered an
59415  ** error, then it might not have been halted properly.  So halt
59416  ** it now.
59417  */
59418  sqlite3VdbeHalt(p);
59419
59420  /* If the VDBE has be run even partially, then transfer the error code
59421  ** and error message from the VDBE into the main database structure.  But
59422  ** if the VDBE has just been set to run but has not actually executed any
59423  ** instructions yet, leave the main database error information unchanged.
59424  */
59425  if( p->pc>=0 ){
59426    if( p->zErrMsg ){
59427      sqlite3BeginBenignMalloc();
59428      sqlite3ValueSetStr(db->pErr,-1,p->zErrMsg,SQLITE_UTF8,SQLITE_TRANSIENT);
59429      sqlite3EndBenignMalloc();
59430      db->errCode = p->rc;
59431      sqlite3DbFree(db, p->zErrMsg);
59432      p->zErrMsg = 0;
59433    }else if( p->rc ){
59434      sqlite3Error(db, p->rc, 0);
59435    }else{
59436      sqlite3Error(db, SQLITE_OK, 0);
59437    }
59438    if( p->runOnlyOnce ) p->expired = 1;
59439  }else if( p->rc && p->expired ){
59440    /* The expired flag was set on the VDBE before the first call
59441    ** to sqlite3_step(). For consistency (since sqlite3_step() was
59442    ** called), set the database error in this case as well.
59443    */
59444    sqlite3Error(db, p->rc, 0);
59445    sqlite3ValueSetStr(db->pErr, -1, p->zErrMsg, SQLITE_UTF8, SQLITE_TRANSIENT);
59446    sqlite3DbFree(db, p->zErrMsg);
59447    p->zErrMsg = 0;
59448  }
59449
59450  /* Reclaim all memory used by the VDBE
59451  */
59452  Cleanup(p);
59453
59454  /* Save profiling information from this VDBE run.
59455  */
59456#ifdef VDBE_PROFILE
59457  {
59458    FILE *out = fopen("vdbe_profile.out", "a");
59459    if( out ){
59460      int i;
59461      fprintf(out, "---- ");
59462      for(i=0; i<p->nOp; i++){
59463        fprintf(out, "%02x", p->aOp[i].opcode);
59464      }
59465      fprintf(out, "\n");
59466      for(i=0; i<p->nOp; i++){
59467        fprintf(out, "%6d %10lld %8lld ",
59468           p->aOp[i].cnt,
59469           p->aOp[i].cycles,
59470           p->aOp[i].cnt>0 ? p->aOp[i].cycles/p->aOp[i].cnt : 0
59471        );
59472        sqlite3VdbePrintOp(out, i, &p->aOp[i]);
59473      }
59474      fclose(out);
59475    }
59476  }
59477#endif
59478  p->magic = VDBE_MAGIC_INIT;
59479  return p->rc & db->errMask;
59480}
59481
59482/*
59483** Clean up and delete a VDBE after execution.  Return an integer which is
59484** the result code.  Write any error message text into *pzErrMsg.
59485*/
59486SQLITE_PRIVATE int sqlite3VdbeFinalize(Vdbe *p){
59487  int rc = SQLITE_OK;
59488  if( p->magic==VDBE_MAGIC_RUN || p->magic==VDBE_MAGIC_HALT ){
59489    rc = sqlite3VdbeReset(p);
59490    assert( (rc & p->db->errMask)==rc );
59491  }
59492  sqlite3VdbeDelete(p);
59493  return rc;
59494}
59495
59496/*
59497** Call the destructor for each auxdata entry in pVdbeFunc for which
59498** the corresponding bit in mask is clear.  Auxdata entries beyond 31
59499** are always destroyed.  To destroy all auxdata entries, call this
59500** routine with mask==0.
59501*/
59502SQLITE_PRIVATE void sqlite3VdbeDeleteAuxData(VdbeFunc *pVdbeFunc, int mask){
59503  int i;
59504  for(i=0; i<pVdbeFunc->nAux; i++){
59505    struct AuxData *pAux = &pVdbeFunc->apAux[i];
59506    if( (i>31 || !(mask&(((u32)1)<<i))) && pAux->pAux ){
59507      if( pAux->xDelete ){
59508        pAux->xDelete(pAux->pAux);
59509      }
59510      pAux->pAux = 0;
59511    }
59512  }
59513}
59514
59515/*
59516** Free all memory associated with the Vdbe passed as the second argument.
59517** The difference between this function and sqlite3VdbeDelete() is that
59518** VdbeDelete() also unlinks the Vdbe from the list of VMs associated with
59519** the database connection.
59520*/
59521SQLITE_PRIVATE void sqlite3VdbeDeleteObject(sqlite3 *db, Vdbe *p){
59522  SubProgram *pSub, *pNext;
59523  assert( p->db==0 || p->db==db );
59524  releaseMemArray(p->aVar, p->nVar);
59525  releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
59526  for(pSub=p->pProgram; pSub; pSub=pNext){
59527    pNext = pSub->pNext;
59528    vdbeFreeOpArray(db, pSub->aOp, pSub->nOp);
59529    sqlite3DbFree(db, pSub);
59530  }
59531  vdbeFreeOpArray(db, p->aOp, p->nOp);
59532  sqlite3DbFree(db, p->aLabel);
59533  sqlite3DbFree(db, p->aColName);
59534  sqlite3DbFree(db, p->zSql);
59535  sqlite3DbFree(db, p->pFree);
59536  sqlite3DbFree(db, p);
59537}
59538
59539/*
59540** Delete an entire VDBE.
59541*/
59542SQLITE_PRIVATE void sqlite3VdbeDelete(Vdbe *p){
59543  sqlite3 *db;
59544
59545  if( NEVER(p==0) ) return;
59546  db = p->db;
59547  if( p->pPrev ){
59548    p->pPrev->pNext = p->pNext;
59549  }else{
59550    assert( db->pVdbe==p );
59551    db->pVdbe = p->pNext;
59552  }
59553  if( p->pNext ){
59554    p->pNext->pPrev = p->pPrev;
59555  }
59556  p->magic = VDBE_MAGIC_DEAD;
59557  p->db = 0;
59558  sqlite3VdbeDeleteObject(db, p);
59559}
59560
59561/*
59562** Make sure the cursor p is ready to read or write the row to which it
59563** was last positioned.  Return an error code if an OOM fault or I/O error
59564** prevents us from positioning the cursor to its correct position.
59565**
59566** If a MoveTo operation is pending on the given cursor, then do that
59567** MoveTo now.  If no move is pending, check to see if the row has been
59568** deleted out from under the cursor and if it has, mark the row as
59569** a NULL row.
59570**
59571** If the cursor is already pointing to the correct row and that row has
59572** not been deleted out from under the cursor, then this routine is a no-op.
59573*/
59574SQLITE_PRIVATE int sqlite3VdbeCursorMoveto(VdbeCursor *p){
59575  if( p->deferredMoveto ){
59576    int res, rc;
59577#ifdef SQLITE_TEST
59578    extern int sqlite3_search_count;
59579#endif
59580    assert( p->isTable );
59581    rc = sqlite3BtreeMovetoUnpacked(p->pCursor, 0, p->movetoTarget, 0, &res);
59582    if( rc ) return rc;
59583    p->lastRowid = p->movetoTarget;
59584    if( res!=0 ) return SQLITE_CORRUPT_BKPT;
59585    p->rowidIsValid = 1;
59586#ifdef SQLITE_TEST
59587    sqlite3_search_count++;
59588#endif
59589    p->deferredMoveto = 0;
59590    p->cacheStatus = CACHE_STALE;
59591  }else if( ALWAYS(p->pCursor) ){
59592    int hasMoved;
59593    int rc = sqlite3BtreeCursorHasMoved(p->pCursor, &hasMoved);
59594    if( rc ) return rc;
59595    if( hasMoved ){
59596      p->cacheStatus = CACHE_STALE;
59597      p->nullRow = 1;
59598    }
59599  }
59600  return SQLITE_OK;
59601}
59602
59603/*
59604** The following functions:
59605**
59606** sqlite3VdbeSerialType()
59607** sqlite3VdbeSerialTypeLen()
59608** sqlite3VdbeSerialLen()
59609** sqlite3VdbeSerialPut()
59610** sqlite3VdbeSerialGet()
59611**
59612** encapsulate the code that serializes values for storage in SQLite
59613** data and index records. Each serialized value consists of a
59614** 'serial-type' and a blob of data. The serial type is an 8-byte unsigned
59615** integer, stored as a varint.
59616**
59617** In an SQLite index record, the serial type is stored directly before
59618** the blob of data that it corresponds to. In a table record, all serial
59619** types are stored at the start of the record, and the blobs of data at
59620** the end. Hence these functions allow the caller to handle the
59621** serial-type and data blob seperately.
59622**
59623** The following table describes the various storage classes for data:
59624**
59625**   serial type        bytes of data      type
59626**   --------------     ---------------    ---------------
59627**      0                     0            NULL
59628**      1                     1            signed integer
59629**      2                     2            signed integer
59630**      3                     3            signed integer
59631**      4                     4            signed integer
59632**      5                     6            signed integer
59633**      6                     8            signed integer
59634**      7                     8            IEEE float
59635**      8                     0            Integer constant 0
59636**      9                     0            Integer constant 1
59637**     10,11                               reserved for expansion
59638**    N>=12 and even       (N-12)/2        BLOB
59639**    N>=13 and odd        (N-13)/2        text
59640**
59641** The 8 and 9 types were added in 3.3.0, file format 4.  Prior versions
59642** of SQLite will not understand those serial types.
59643*/
59644
59645/*
59646** Return the serial-type for the value stored in pMem.
59647*/
59648SQLITE_PRIVATE u32 sqlite3VdbeSerialType(Mem *pMem, int file_format){
59649  int flags = pMem->flags;
59650  int n;
59651
59652  if( flags&MEM_Null ){
59653    return 0;
59654  }
59655  if( flags&MEM_Int ){
59656    /* Figure out whether to use 1, 2, 4, 6 or 8 bytes. */
59657#   define MAX_6BYTE ((((i64)0x00008000)<<32)-1)
59658    i64 i = pMem->u.i;
59659    u64 u;
59660    if( file_format>=4 && (i&1)==i ){
59661      return 8+(u32)i;
59662    }
59663    if( i<0 ){
59664      if( i<(-MAX_6BYTE) ) return 6;
59665      /* Previous test prevents:  u = -(-9223372036854775808) */
59666      u = -i;
59667    }else{
59668      u = i;
59669    }
59670    if( u<=127 ) return 1;
59671    if( u<=32767 ) return 2;
59672    if( u<=8388607 ) return 3;
59673    if( u<=2147483647 ) return 4;
59674    if( u<=MAX_6BYTE ) return 5;
59675    return 6;
59676  }
59677  if( flags&MEM_Real ){
59678    return 7;
59679  }
59680  assert( pMem->db->mallocFailed || flags&(MEM_Str|MEM_Blob) );
59681  n = pMem->n;
59682  if( flags & MEM_Zero ){
59683    n += pMem->u.nZero;
59684  }
59685  assert( n>=0 );
59686  return ((n*2) + 12 + ((flags&MEM_Str)!=0));
59687}
59688
59689/*
59690** Return the length of the data corresponding to the supplied serial-type.
59691*/
59692SQLITE_PRIVATE u32 sqlite3VdbeSerialTypeLen(u32 serial_type){
59693  if( serial_type>=12 ){
59694    return (serial_type-12)/2;
59695  }else{
59696    static const u8 aSize[] = { 0, 1, 2, 3, 4, 6, 8, 8, 0, 0, 0, 0 };
59697    return aSize[serial_type];
59698  }
59699}
59700
59701/*
59702** If we are on an architecture with mixed-endian floating
59703** points (ex: ARM7) then swap the lower 4 bytes with the
59704** upper 4 bytes.  Return the result.
59705**
59706** For most architectures, this is a no-op.
59707**
59708** (later):  It is reported to me that the mixed-endian problem
59709** on ARM7 is an issue with GCC, not with the ARM7 chip.  It seems
59710** that early versions of GCC stored the two words of a 64-bit
59711** float in the wrong order.  And that error has been propagated
59712** ever since.  The blame is not necessarily with GCC, though.
59713** GCC might have just copying the problem from a prior compiler.
59714** I am also told that newer versions of GCC that follow a different
59715** ABI get the byte order right.
59716**
59717** Developers using SQLite on an ARM7 should compile and run their
59718** application using -DSQLITE_DEBUG=1 at least once.  With DEBUG
59719** enabled, some asserts below will ensure that the byte order of
59720** floating point values is correct.
59721**
59722** (2007-08-30)  Frank van Vugt has studied this problem closely
59723** and has send his findings to the SQLite developers.  Frank
59724** writes that some Linux kernels offer floating point hardware
59725** emulation that uses only 32-bit mantissas instead of a full
59726** 48-bits as required by the IEEE standard.  (This is the
59727** CONFIG_FPE_FASTFPE option.)  On such systems, floating point
59728** byte swapping becomes very complicated.  To avoid problems,
59729** the necessary byte swapping is carried out using a 64-bit integer
59730** rather than a 64-bit float.  Frank assures us that the code here
59731** works for him.  We, the developers, have no way to independently
59732** verify this, but Frank seems to know what he is talking about
59733** so we trust him.
59734*/
59735#ifdef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
59736static u64 floatSwap(u64 in){
59737  union {
59738    u64 r;
59739    u32 i[2];
59740  } u;
59741  u32 t;
59742
59743  u.r = in;
59744  t = u.i[0];
59745  u.i[0] = u.i[1];
59746  u.i[1] = t;
59747  return u.r;
59748}
59749# define swapMixedEndianFloat(X)  X = floatSwap(X)
59750#else
59751# define swapMixedEndianFloat(X)
59752#endif
59753
59754/*
59755** Write the serialized data blob for the value stored in pMem into
59756** buf. It is assumed that the caller has allocated sufficient space.
59757** Return the number of bytes written.
59758**
59759** nBuf is the amount of space left in buf[].  nBuf must always be
59760** large enough to hold the entire field.  Except, if the field is
59761** a blob with a zero-filled tail, then buf[] might be just the right
59762** size to hold everything except for the zero-filled tail.  If buf[]
59763** is only big enough to hold the non-zero prefix, then only write that
59764** prefix into buf[].  But if buf[] is large enough to hold both the
59765** prefix and the tail then write the prefix and set the tail to all
59766** zeros.
59767**
59768** Return the number of bytes actually written into buf[].  The number
59769** of bytes in the zero-filled tail is included in the return value only
59770** if those bytes were zeroed in buf[].
59771*/
59772SQLITE_PRIVATE u32 sqlite3VdbeSerialPut(u8 *buf, int nBuf, Mem *pMem, int file_format){
59773  u32 serial_type = sqlite3VdbeSerialType(pMem, file_format);
59774  u32 len;
59775
59776  /* Integer and Real */
59777  if( serial_type<=7 && serial_type>0 ){
59778    u64 v;
59779    u32 i;
59780    if( serial_type==7 ){
59781      assert( sizeof(v)==sizeof(pMem->r) );
59782      memcpy(&v, &pMem->r, sizeof(v));
59783      swapMixedEndianFloat(v);
59784    }else{
59785      v = pMem->u.i;
59786    }
59787    len = i = sqlite3VdbeSerialTypeLen(serial_type);
59788    assert( len<=(u32)nBuf );
59789    while( i-- ){
59790      buf[i] = (u8)(v&0xFF);
59791      v >>= 8;
59792    }
59793    return len;
59794  }
59795
59796  /* String or blob */
59797  if( serial_type>=12 ){
59798    assert( pMem->n + ((pMem->flags & MEM_Zero)?pMem->u.nZero:0)
59799             == (int)sqlite3VdbeSerialTypeLen(serial_type) );
59800    assert( pMem->n<=nBuf );
59801    len = pMem->n;
59802    memcpy(buf, pMem->z, len);
59803    if( pMem->flags & MEM_Zero ){
59804      len += pMem->u.nZero;
59805      assert( nBuf>=0 );
59806      if( len > (u32)nBuf ){
59807        len = (u32)nBuf;
59808      }
59809      memset(&buf[pMem->n], 0, len-pMem->n);
59810    }
59811    return len;
59812  }
59813
59814  /* NULL or constants 0 or 1 */
59815  return 0;
59816}
59817
59818/*
59819** Deserialize the data blob pointed to by buf as serial type serial_type
59820** and store the result in pMem.  Return the number of bytes read.
59821*/
59822SQLITE_PRIVATE u32 sqlite3VdbeSerialGet(
59823  const unsigned char *buf,     /* Buffer to deserialize from */
59824  u32 serial_type,              /* Serial type to deserialize */
59825  Mem *pMem                     /* Memory cell to write value into */
59826){
59827  switch( serial_type ){
59828    case 10:   /* Reserved for future use */
59829    case 11:   /* Reserved for future use */
59830    case 0: {  /* NULL */
59831      pMem->flags = MEM_Null;
59832      break;
59833    }
59834    case 1: { /* 1-byte signed integer */
59835      pMem->u.i = (signed char)buf[0];
59836      pMem->flags = MEM_Int;
59837      return 1;
59838    }
59839    case 2: { /* 2-byte signed integer */
59840      pMem->u.i = (((signed char)buf[0])<<8) | buf[1];
59841      pMem->flags = MEM_Int;
59842      return 2;
59843    }
59844    case 3: { /* 3-byte signed integer */
59845      pMem->u.i = (((signed char)buf[0])<<16) | (buf[1]<<8) | buf[2];
59846      pMem->flags = MEM_Int;
59847      return 3;
59848    }
59849    case 4: { /* 4-byte signed integer */
59850      pMem->u.i = (buf[0]<<24) | (buf[1]<<16) | (buf[2]<<8) | buf[3];
59851      pMem->flags = MEM_Int;
59852      return 4;
59853    }
59854    case 5: { /* 6-byte signed integer */
59855      u64 x = (((signed char)buf[0])<<8) | buf[1];
59856      u32 y = (buf[2]<<24) | (buf[3]<<16) | (buf[4]<<8) | buf[5];
59857      x = (x<<32) | y;
59858      pMem->u.i = *(i64*)&x;
59859      pMem->flags = MEM_Int;
59860      return 6;
59861    }
59862    case 6:   /* 8-byte signed integer */
59863    case 7: { /* IEEE floating point */
59864      u64 x;
59865      u32 y;
59866#if !defined(NDEBUG) && !defined(SQLITE_OMIT_FLOATING_POINT)
59867      /* Verify that integers and floating point values use the same
59868      ** byte order.  Or, that if SQLITE_MIXED_ENDIAN_64BIT_FLOAT is
59869      ** defined that 64-bit floating point values really are mixed
59870      ** endian.
59871      */
59872      static const u64 t1 = ((u64)0x3ff00000)<<32;
59873      static const double r1 = 1.0;
59874      u64 t2 = t1;
59875      swapMixedEndianFloat(t2);
59876      assert( sizeof(r1)==sizeof(t2) && memcmp(&r1, &t2, sizeof(r1))==0 );
59877#endif
59878
59879      x = (buf[0]<<24) | (buf[1]<<16) | (buf[2]<<8) | buf[3];
59880      y = (buf[4]<<24) | (buf[5]<<16) | (buf[6]<<8) | buf[7];
59881      x = (x<<32) | y;
59882      if( serial_type==6 ){
59883        pMem->u.i = *(i64*)&x;
59884        pMem->flags = MEM_Int;
59885      }else{
59886        assert( sizeof(x)==8 && sizeof(pMem->r)==8 );
59887        swapMixedEndianFloat(x);
59888        memcpy(&pMem->r, &x, sizeof(x));
59889        pMem->flags = sqlite3IsNaN(pMem->r) ? MEM_Null : MEM_Real;
59890      }
59891      return 8;
59892    }
59893    case 8:    /* Integer 0 */
59894    case 9: {  /* Integer 1 */
59895      pMem->u.i = serial_type-8;
59896      pMem->flags = MEM_Int;
59897      return 0;
59898    }
59899    default: {
59900      u32 len = (serial_type-12)/2;
59901      pMem->z = (char *)buf;
59902      pMem->n = len;
59903      pMem->xDel = 0;
59904      if( serial_type&0x01 ){
59905        pMem->flags = MEM_Str | MEM_Ephem;
59906      }else{
59907        pMem->flags = MEM_Blob | MEM_Ephem;
59908      }
59909      return len;
59910    }
59911  }
59912  return 0;
59913}
59914
59915
59916/*
59917** Given the nKey-byte encoding of a record in pKey[], parse the
59918** record into a UnpackedRecord structure.  Return a pointer to
59919** that structure.
59920**
59921** The calling function might provide szSpace bytes of memory
59922** space at pSpace.  This space can be used to hold the returned
59923** VDbeParsedRecord structure if it is large enough.  If it is
59924** not big enough, space is obtained from sqlite3_malloc().
59925**
59926** The returned structure should be closed by a call to
59927** sqlite3VdbeDeleteUnpackedRecord().
59928*/
59929SQLITE_PRIVATE UnpackedRecord *sqlite3VdbeRecordUnpack(
59930  KeyInfo *pKeyInfo,     /* Information about the record format */
59931  int nKey,              /* Size of the binary record */
59932  const void *pKey,      /* The binary record */
59933  char *pSpace,          /* Unaligned space available to hold the object */
59934  int szSpace            /* Size of pSpace[] in bytes */
59935){
59936  const unsigned char *aKey = (const unsigned char *)pKey;
59937  UnpackedRecord *p;  /* The unpacked record that we will return */
59938  int nByte;          /* Memory space needed to hold p, in bytes */
59939  int d;
59940  u32 idx;
59941  u16 u;              /* Unsigned loop counter */
59942  u32 szHdr;
59943  Mem *pMem;
59944  int nOff;           /* Increase pSpace by this much to 8-byte align it */
59945
59946  /*
59947  ** We want to shift the pointer pSpace up such that it is 8-byte aligned.
59948  ** Thus, we need to calculate a value, nOff, between 0 and 7, to shift
59949  ** it by.  If pSpace is already 8-byte aligned, nOff should be zero.
59950  */
59951  nOff = (8 - (SQLITE_PTR_TO_INT(pSpace) & 7)) & 7;
59952  pSpace += nOff;
59953  szSpace -= nOff;
59954  nByte = ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*(pKeyInfo->nField+1);
59955  if( nByte>szSpace ){
59956    p = sqlite3DbMallocRaw(pKeyInfo->db, nByte);
59957    if( p==0 ) return 0;
59958    p->flags = UNPACKED_NEED_FREE | UNPACKED_NEED_DESTROY;
59959  }else{
59960    p = (UnpackedRecord*)pSpace;
59961    p->flags = UNPACKED_NEED_DESTROY;
59962  }
59963  p->pKeyInfo = pKeyInfo;
59964  p->nField = pKeyInfo->nField + 1;
59965  p->aMem = pMem = (Mem*)&((char*)p)[ROUND8(sizeof(UnpackedRecord))];
59966  assert( EIGHT_BYTE_ALIGNMENT(pMem) );
59967  idx = getVarint32(aKey, szHdr);
59968  d = szHdr;
59969  u = 0;
59970  while( idx<szHdr && u<p->nField && d<=nKey ){
59971    u32 serial_type;
59972
59973    idx += getVarint32(&aKey[idx], serial_type);
59974    pMem->enc = pKeyInfo->enc;
59975    pMem->db = pKeyInfo->db;
59976    pMem->flags = 0;
59977    pMem->zMalloc = 0;
59978    d += sqlite3VdbeSerialGet(&aKey[d], serial_type, pMem);
59979    pMem++;
59980    u++;
59981  }
59982  assert( u<=pKeyInfo->nField + 1 );
59983  p->nField = u;
59984  return (void*)p;
59985}
59986
59987/*
59988** This routine destroys a UnpackedRecord object.
59989*/
59990SQLITE_PRIVATE void sqlite3VdbeDeleteUnpackedRecord(UnpackedRecord *p){
59991  int i;
59992  Mem *pMem;
59993
59994  assert( p!=0 );
59995  assert( p->flags & UNPACKED_NEED_DESTROY );
59996  for(i=0, pMem=p->aMem; i<p->nField; i++, pMem++){
59997    /* The unpacked record is always constructed by the
59998    ** sqlite3VdbeUnpackRecord() function above, which makes all
59999    ** strings and blobs static.  And none of the elements are
60000    ** ever transformed, so there is never anything to delete.
60001    */
60002    if( NEVER(pMem->zMalloc) ) sqlite3VdbeMemRelease(pMem);
60003  }
60004  if( p->flags & UNPACKED_NEED_FREE ){
60005    sqlite3DbFree(p->pKeyInfo->db, p);
60006  }
60007}
60008
60009/*
60010** This function compares the two table rows or index records
60011** specified by {nKey1, pKey1} and pPKey2.  It returns a negative, zero
60012** or positive integer if key1 is less than, equal to or
60013** greater than key2.  The {nKey1, pKey1} key must be a blob
60014** created by th OP_MakeRecord opcode of the VDBE.  The pPKey2
60015** key must be a parsed key such as obtained from
60016** sqlite3VdbeParseRecord.
60017**
60018** Key1 and Key2 do not have to contain the same number of fields.
60019** The key with fewer fields is usually compares less than the
60020** longer key.  However if the UNPACKED_INCRKEY flags in pPKey2 is set
60021** and the common prefixes are equal, then key1 is less than key2.
60022** Or if the UNPACKED_MATCH_PREFIX flag is set and the prefixes are
60023** equal, then the keys are considered to be equal and
60024** the parts beyond the common prefix are ignored.
60025**
60026** If the UNPACKED_IGNORE_ROWID flag is set, then the last byte of
60027** the header of pKey1 is ignored.  It is assumed that pKey1 is
60028** an index key, and thus ends with a rowid value.  The last byte
60029** of the header will therefore be the serial type of the rowid:
60030** one of 1, 2, 3, 4, 5, 6, 8, or 9 - the integer serial types.
60031** The serial type of the final rowid will always be a single byte.
60032** By ignoring this last byte of the header, we force the comparison
60033** to ignore the rowid at the end of key1.
60034*/
60035SQLITE_PRIVATE int sqlite3VdbeRecordCompare(
60036  int nKey1, const void *pKey1, /* Left key */
60037  UnpackedRecord *pPKey2        /* Right key */
60038){
60039  int d1;            /* Offset into aKey[] of next data element */
60040  u32 idx1;          /* Offset into aKey[] of next header element */
60041  u32 szHdr1;        /* Number of bytes in header */
60042  int i = 0;
60043  int nField;
60044  int rc = 0;
60045  const unsigned char *aKey1 = (const unsigned char *)pKey1;
60046  KeyInfo *pKeyInfo;
60047  Mem mem1;
60048
60049  pKeyInfo = pPKey2->pKeyInfo;
60050  mem1.enc = pKeyInfo->enc;
60051  mem1.db = pKeyInfo->db;
60052  /* mem1.flags = 0;  // Will be initialized by sqlite3VdbeSerialGet() */
60053  VVA_ONLY( mem1.zMalloc = 0; ) /* Only needed by assert() statements */
60054
60055  /* Compilers may complain that mem1.u.i is potentially uninitialized.
60056  ** We could initialize it, as shown here, to silence those complaints.
60057  ** But in fact, mem1.u.i will never actually be used initialized, and doing
60058  ** the unnecessary initialization has a measurable negative performance
60059  ** impact, since this routine is a very high runner.  And so, we choose
60060  ** to ignore the compiler warnings and leave this variable uninitialized.
60061  */
60062  /*  mem1.u.i = 0;  // not needed, here to silence compiler warning */
60063
60064  idx1 = getVarint32(aKey1, szHdr1);
60065  d1 = szHdr1;
60066  if( pPKey2->flags & UNPACKED_IGNORE_ROWID ){
60067    szHdr1--;
60068  }
60069  nField = pKeyInfo->nField;
60070  while( idx1<szHdr1 && i<pPKey2->nField ){
60071    u32 serial_type1;
60072
60073    /* Read the serial types for the next element in each key. */
60074    idx1 += getVarint32( aKey1+idx1, serial_type1 );
60075    if( d1>=nKey1 && sqlite3VdbeSerialTypeLen(serial_type1)>0 ) break;
60076
60077    /* Extract the values to be compared.
60078    */
60079    d1 += sqlite3VdbeSerialGet(&aKey1[d1], serial_type1, &mem1);
60080
60081    /* Do the comparison
60082    */
60083    rc = sqlite3MemCompare(&mem1, &pPKey2->aMem[i],
60084                           i<nField ? pKeyInfo->aColl[i] : 0);
60085    if( rc!=0 ){
60086      assert( mem1.zMalloc==0 );  /* See comment below */
60087
60088      /* Invert the result if we are using DESC sort order. */
60089      if( pKeyInfo->aSortOrder && i<nField && pKeyInfo->aSortOrder[i] ){
60090        rc = -rc;
60091      }
60092
60093      /* If the PREFIX_SEARCH flag is set and all fields except the final
60094      ** rowid field were equal, then clear the PREFIX_SEARCH flag and set
60095      ** pPKey2->rowid to the value of the rowid field in (pKey1, nKey1).
60096      ** This is used by the OP_IsUnique opcode.
60097      */
60098      if( (pPKey2->flags & UNPACKED_PREFIX_SEARCH) && i==(pPKey2->nField-1) ){
60099        assert( idx1==szHdr1 && rc );
60100        assert( mem1.flags & MEM_Int );
60101        pPKey2->flags &= ~UNPACKED_PREFIX_SEARCH;
60102        pPKey2->rowid = mem1.u.i;
60103      }
60104
60105      return rc;
60106    }
60107    i++;
60108  }
60109
60110  /* No memory allocation is ever used on mem1.  Prove this using
60111  ** the following assert().  If the assert() fails, it indicates a
60112  ** memory leak and a need to call sqlite3VdbeMemRelease(&mem1).
60113  */
60114  assert( mem1.zMalloc==0 );
60115
60116  /* rc==0 here means that one of the keys ran out of fields and
60117  ** all the fields up to that point were equal. If the UNPACKED_INCRKEY
60118  ** flag is set, then break the tie by treating key2 as larger.
60119  ** If the UPACKED_PREFIX_MATCH flag is set, then keys with common prefixes
60120  ** are considered to be equal.  Otherwise, the longer key is the
60121  ** larger.  As it happens, the pPKey2 will always be the longer
60122  ** if there is a difference.
60123  */
60124  assert( rc==0 );
60125  if( pPKey2->flags & UNPACKED_INCRKEY ){
60126    rc = -1;
60127  }else if( pPKey2->flags & UNPACKED_PREFIX_MATCH ){
60128    /* Leave rc==0 */
60129  }else if( idx1<szHdr1 ){
60130    rc = 1;
60131  }
60132  return rc;
60133}
60134
60135
60136/*
60137** pCur points at an index entry created using the OP_MakeRecord opcode.
60138** Read the rowid (the last field in the record) and store it in *rowid.
60139** Return SQLITE_OK if everything works, or an error code otherwise.
60140**
60141** pCur might be pointing to text obtained from a corrupt database file.
60142** So the content cannot be trusted.  Do appropriate checks on the content.
60143*/
60144SQLITE_PRIVATE int sqlite3VdbeIdxRowid(sqlite3 *db, BtCursor *pCur, i64 *rowid){
60145  i64 nCellKey = 0;
60146  int rc;
60147  u32 szHdr;        /* Size of the header */
60148  u32 typeRowid;    /* Serial type of the rowid */
60149  u32 lenRowid;     /* Size of the rowid */
60150  Mem m, v;
60151
60152  UNUSED_PARAMETER(db);
60153
60154  /* Get the size of the index entry.  Only indices entries of less
60155  ** than 2GiB are support - anything large must be database corruption.
60156  ** Any corruption is detected in sqlite3BtreeParseCellPtr(), though, so
60157  ** this code can safely assume that nCellKey is 32-bits
60158  */
60159  assert( sqlite3BtreeCursorIsValid(pCur) );
60160  rc = sqlite3BtreeKeySize(pCur, &nCellKey);
60161  assert( rc==SQLITE_OK );     /* pCur is always valid so KeySize cannot fail */
60162  assert( (nCellKey & SQLITE_MAX_U32)==(u64)nCellKey );
60163
60164  /* Read in the complete content of the index entry */
60165  memset(&m, 0, sizeof(m));
60166  rc = sqlite3VdbeMemFromBtree(pCur, 0, (int)nCellKey, 1, &m);
60167  if( rc ){
60168    return rc;
60169  }
60170
60171  /* The index entry must begin with a header size */
60172  (void)getVarint32((u8*)m.z, szHdr);
60173  testcase( szHdr==3 );
60174  testcase( szHdr==m.n );
60175  if( unlikely(szHdr<3 || (int)szHdr>m.n) ){
60176    goto idx_rowid_corruption;
60177  }
60178
60179  /* The last field of the index should be an integer - the ROWID.
60180  ** Verify that the last entry really is an integer. */
60181  (void)getVarint32((u8*)&m.z[szHdr-1], typeRowid);
60182  testcase( typeRowid==1 );
60183  testcase( typeRowid==2 );
60184  testcase( typeRowid==3 );
60185  testcase( typeRowid==4 );
60186  testcase( typeRowid==5 );
60187  testcase( typeRowid==6 );
60188  testcase( typeRowid==8 );
60189  testcase( typeRowid==9 );
60190  if( unlikely(typeRowid<1 || typeRowid>9 || typeRowid==7) ){
60191    goto idx_rowid_corruption;
60192  }
60193  lenRowid = sqlite3VdbeSerialTypeLen(typeRowid);
60194  testcase( (u32)m.n==szHdr+lenRowid );
60195  if( unlikely((u32)m.n<szHdr+lenRowid) ){
60196    goto idx_rowid_corruption;
60197  }
60198
60199  /* Fetch the integer off the end of the index record */
60200  sqlite3VdbeSerialGet((u8*)&m.z[m.n-lenRowid], typeRowid, &v);
60201  *rowid = v.u.i;
60202  sqlite3VdbeMemRelease(&m);
60203  return SQLITE_OK;
60204
60205  /* Jump here if database corruption is detected after m has been
60206  ** allocated.  Free the m object and return SQLITE_CORRUPT. */
60207idx_rowid_corruption:
60208  testcase( m.zMalloc!=0 );
60209  sqlite3VdbeMemRelease(&m);
60210  return SQLITE_CORRUPT_BKPT;
60211}
60212
60213/*
60214** Compare the key of the index entry that cursor pC is pointing to against
60215** the key string in pUnpacked.  Write into *pRes a number
60216** that is negative, zero, or positive if pC is less than, equal to,
60217** or greater than pUnpacked.  Return SQLITE_OK on success.
60218**
60219** pUnpacked is either created without a rowid or is truncated so that it
60220** omits the rowid at the end.  The rowid at the end of the index entry
60221** is ignored as well.  Hence, this routine only compares the prefixes
60222** of the keys prior to the final rowid, not the entire key.
60223*/
60224SQLITE_PRIVATE int sqlite3VdbeIdxKeyCompare(
60225  VdbeCursor *pC,             /* The cursor to compare against */
60226  UnpackedRecord *pUnpacked,  /* Unpacked version of key to compare against */
60227  int *res                    /* Write the comparison result here */
60228){
60229  i64 nCellKey = 0;
60230  int rc;
60231  BtCursor *pCur = pC->pCursor;
60232  Mem m;
60233
60234  assert( sqlite3BtreeCursorIsValid(pCur) );
60235  rc = sqlite3BtreeKeySize(pCur, &nCellKey);
60236  assert( rc==SQLITE_OK );    /* pCur is always valid so KeySize cannot fail */
60237  /* nCellKey will always be between 0 and 0xffffffff because of the say
60238  ** that btreeParseCellPtr() and sqlite3GetVarint32() are implemented */
60239  if( nCellKey<=0 || nCellKey>0x7fffffff ){
60240    *res = 0;
60241    return SQLITE_CORRUPT_BKPT;
60242  }
60243  memset(&m, 0, sizeof(m));
60244  rc = sqlite3VdbeMemFromBtree(pC->pCursor, 0, (int)nCellKey, 1, &m);
60245  if( rc ){
60246    return rc;
60247  }
60248  assert( pUnpacked->flags & UNPACKED_IGNORE_ROWID );
60249  *res = sqlite3VdbeRecordCompare(m.n, m.z, pUnpacked);
60250  sqlite3VdbeMemRelease(&m);
60251  return SQLITE_OK;
60252}
60253
60254/*
60255** This routine sets the value to be returned by subsequent calls to
60256** sqlite3_changes() on the database handle 'db'.
60257*/
60258SQLITE_PRIVATE void sqlite3VdbeSetChanges(sqlite3 *db, int nChange){
60259  assert( sqlite3_mutex_held(db->mutex) );
60260  db->nChange = nChange;
60261  db->nTotalChange += nChange;
60262}
60263
60264/*
60265** Set a flag in the vdbe to update the change counter when it is finalised
60266** or reset.
60267*/
60268SQLITE_PRIVATE void sqlite3VdbeCountChanges(Vdbe *v){
60269  v->changeCntOn = 1;
60270}
60271
60272/*
60273** Mark every prepared statement associated with a database connection
60274** as expired.
60275**
60276** An expired statement means that recompilation of the statement is
60277** recommend.  Statements expire when things happen that make their
60278** programs obsolete.  Removing user-defined functions or collating
60279** sequences, or changing an authorization function are the types of
60280** things that make prepared statements obsolete.
60281*/
60282SQLITE_PRIVATE void sqlite3ExpirePreparedStatements(sqlite3 *db){
60283  Vdbe *p;
60284  for(p = db->pVdbe; p; p=p->pNext){
60285    p->expired = 1;
60286  }
60287}
60288
60289/*
60290** Return the database associated with the Vdbe.
60291*/
60292SQLITE_PRIVATE sqlite3 *sqlite3VdbeDb(Vdbe *v){
60293  return v->db;
60294}
60295
60296/*
60297** Return a pointer to an sqlite3_value structure containing the value bound
60298** parameter iVar of VM v. Except, if the value is an SQL NULL, return
60299** 0 instead. Unless it is NULL, apply affinity aff (one of the SQLITE_AFF_*
60300** constants) to the value before returning it.
60301**
60302** The returned value must be freed by the caller using sqlite3ValueFree().
60303*/
60304SQLITE_PRIVATE sqlite3_value *sqlite3VdbeGetValue(Vdbe *v, int iVar, u8 aff){
60305  assert( iVar>0 );
60306  if( v ){
60307    Mem *pMem = &v->aVar[iVar-1];
60308    if( 0==(pMem->flags & MEM_Null) ){
60309      sqlite3_value *pRet = sqlite3ValueNew(v->db);
60310      if( pRet ){
60311        sqlite3VdbeMemCopy((Mem *)pRet, pMem);
60312        sqlite3ValueApplyAffinity(pRet, aff, SQLITE_UTF8);
60313        sqlite3VdbeMemStoreType((Mem *)pRet);
60314      }
60315      return pRet;
60316    }
60317  }
60318  return 0;
60319}
60320
60321/*
60322** Configure SQL variable iVar so that binding a new value to it signals
60323** to sqlite3_reoptimize() that re-preparing the statement may result
60324** in a better query plan.
60325*/
60326SQLITE_PRIVATE void sqlite3VdbeSetVarmask(Vdbe *v, int iVar){
60327  assert( iVar>0 );
60328  if( iVar>32 ){
60329    v->expmask = 0xffffffff;
60330  }else{
60331    v->expmask |= ((u32)1 << (iVar-1));
60332  }
60333}
60334
60335/************** End of vdbeaux.c *********************************************/
60336/************** Begin file vdbeapi.c *****************************************/
60337/*
60338** 2004 May 26
60339**
60340** The author disclaims copyright to this source code.  In place of
60341** a legal notice, here is a blessing:
60342**
60343**    May you do good and not evil.
60344**    May you find forgiveness for yourself and forgive others.
60345**    May you share freely, never taking more than you give.
60346**
60347*************************************************************************
60348**
60349** This file contains code use to implement APIs that are part of the
60350** VDBE.
60351*/
60352
60353#ifndef SQLITE_OMIT_DEPRECATED
60354/*
60355** Return TRUE (non-zero) of the statement supplied as an argument needs
60356** to be recompiled.  A statement needs to be recompiled whenever the
60357** execution environment changes in a way that would alter the program
60358** that sqlite3_prepare() generates.  For example, if new functions or
60359** collating sequences are registered or if an authorizer function is
60360** added or changed.
60361*/
60362SQLITE_API int sqlite3_expired(sqlite3_stmt *pStmt){
60363  Vdbe *p = (Vdbe*)pStmt;
60364  return p==0 || p->expired;
60365}
60366#endif
60367
60368/*
60369** Check on a Vdbe to make sure it has not been finalized.  Log
60370** an error and return true if it has been finalized (or is otherwise
60371** invalid).  Return false if it is ok.
60372*/
60373static int vdbeSafety(Vdbe *p){
60374  if( p->db==0 ){
60375    sqlite3_log(SQLITE_MISUSE, "API called with finalized prepared statement");
60376    return 1;
60377  }else{
60378    return 0;
60379  }
60380}
60381static int vdbeSafetyNotNull(Vdbe *p){
60382  if( p==0 ){
60383    sqlite3_log(SQLITE_MISUSE, "API called with NULL prepared statement");
60384    return 1;
60385  }else{
60386    return vdbeSafety(p);
60387  }
60388}
60389
60390/*
60391** The following routine destroys a virtual machine that is created by
60392** the sqlite3_compile() routine. The integer returned is an SQLITE_
60393** success/failure code that describes the result of executing the virtual
60394** machine.
60395**
60396** This routine sets the error code and string returned by
60397** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16().
60398*/
60399SQLITE_API int sqlite3_finalize(sqlite3_stmt *pStmt){
60400  int rc;
60401  if( pStmt==0 ){
60402    /* IMPLEMENTATION-OF: R-57228-12904 Invoking sqlite3_finalize() on a NULL
60403    ** pointer is a harmless no-op. */
60404    rc = SQLITE_OK;
60405  }else{
60406    Vdbe *v = (Vdbe*)pStmt;
60407    sqlite3 *db = v->db;
60408#if SQLITE_THREADSAFE
60409    sqlite3_mutex *mutex;
60410#endif
60411    if( vdbeSafety(v) ) return SQLITE_MISUSE_BKPT;
60412#if SQLITE_THREADSAFE
60413    mutex = v->db->mutex;
60414#endif
60415    sqlite3_mutex_enter(mutex);
60416    rc = sqlite3VdbeFinalize(v);
60417    rc = sqlite3ApiExit(db, rc);
60418    sqlite3_mutex_leave(mutex);
60419  }
60420  return rc;
60421}
60422
60423/*
60424** Terminate the current execution of an SQL statement and reset it
60425** back to its starting state so that it can be reused. A success code from
60426** the prior execution is returned.
60427**
60428** This routine sets the error code and string returned by
60429** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16().
60430*/
60431SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt){
60432  int rc;
60433  if( pStmt==0 ){
60434    rc = SQLITE_OK;
60435  }else{
60436    Vdbe *v = (Vdbe*)pStmt;
60437    sqlite3_mutex_enter(v->db->mutex);
60438    rc = sqlite3VdbeReset(v);
60439    sqlite3VdbeMakeReady(v, -1, 0, 0, 0, 0, 0);
60440    assert( (rc & (v->db->errMask))==rc );
60441    rc = sqlite3ApiExit(v->db, rc);
60442    sqlite3_mutex_leave(v->db->mutex);
60443  }
60444  return rc;
60445}
60446
60447/*
60448** Set all the parameters in the compiled SQL statement to NULL.
60449*/
60450SQLITE_API int sqlite3_clear_bindings(sqlite3_stmt *pStmt){
60451  int i;
60452  int rc = SQLITE_OK;
60453  Vdbe *p = (Vdbe*)pStmt;
60454#if SQLITE_THREADSAFE
60455  sqlite3_mutex *mutex = ((Vdbe*)pStmt)->db->mutex;
60456#endif
60457  sqlite3_mutex_enter(mutex);
60458  for(i=0; i<p->nVar; i++){
60459    sqlite3VdbeMemRelease(&p->aVar[i]);
60460    p->aVar[i].flags = MEM_Null;
60461  }
60462  if( p->isPrepareV2 && p->expmask ){
60463    p->expired = 1;
60464  }
60465  sqlite3_mutex_leave(mutex);
60466  return rc;
60467}
60468
60469
60470/**************************** sqlite3_value_  *******************************
60471** The following routines extract information from a Mem or sqlite3_value
60472** structure.
60473*/
60474SQLITE_API const void *sqlite3_value_blob(sqlite3_value *pVal){
60475  Mem *p = (Mem*)pVal;
60476  if( p->flags & (MEM_Blob|MEM_Str) ){
60477    sqlite3VdbeMemExpandBlob(p);
60478    p->flags &= ~MEM_Str;
60479    p->flags |= MEM_Blob;
60480    return p->n ? p->z : 0;
60481  }else{
60482    return sqlite3_value_text(pVal);
60483  }
60484}
60485SQLITE_API int sqlite3_value_bytes(sqlite3_value *pVal){
60486  return sqlite3ValueBytes(pVal, SQLITE_UTF8);
60487}
60488SQLITE_API int sqlite3_value_bytes16(sqlite3_value *pVal){
60489  return sqlite3ValueBytes(pVal, SQLITE_UTF16NATIVE);
60490}
60491SQLITE_API double sqlite3_value_double(sqlite3_value *pVal){
60492  return sqlite3VdbeRealValue((Mem*)pVal);
60493}
60494SQLITE_API int sqlite3_value_int(sqlite3_value *pVal){
60495  return (int)sqlite3VdbeIntValue((Mem*)pVal);
60496}
60497SQLITE_API sqlite_int64 sqlite3_value_int64(sqlite3_value *pVal){
60498  return sqlite3VdbeIntValue((Mem*)pVal);
60499}
60500SQLITE_API const unsigned char *sqlite3_value_text(sqlite3_value *pVal){
60501  return (const unsigned char *)sqlite3ValueText(pVal, SQLITE_UTF8);
60502}
60503#ifndef SQLITE_OMIT_UTF16
60504SQLITE_API const void *sqlite3_value_text16(sqlite3_value* pVal){
60505  return sqlite3ValueText(pVal, SQLITE_UTF16NATIVE);
60506}
60507SQLITE_API const void *sqlite3_value_text16be(sqlite3_value *pVal){
60508  return sqlite3ValueText(pVal, SQLITE_UTF16BE);
60509}
60510SQLITE_API const void *sqlite3_value_text16le(sqlite3_value *pVal){
60511  return sqlite3ValueText(pVal, SQLITE_UTF16LE);
60512}
60513#endif /* SQLITE_OMIT_UTF16 */
60514SQLITE_API int sqlite3_value_type(sqlite3_value* pVal){
60515  return pVal->type;
60516}
60517
60518/**************************** sqlite3_result_  *******************************
60519** The following routines are used by user-defined functions to specify
60520** the function result.
60521**
60522** The setStrOrError() funtion calls sqlite3VdbeMemSetStr() to store the
60523** result as a string or blob but if the string or blob is too large, it
60524** then sets the error code to SQLITE_TOOBIG
60525*/
60526static void setResultStrOrError(
60527  sqlite3_context *pCtx,  /* Function context */
60528  const char *z,          /* String pointer */
60529  int n,                  /* Bytes in string, or negative */
60530  u8 enc,                 /* Encoding of z.  0 for BLOBs */
60531  void (*xDel)(void*)     /* Destructor function */
60532){
60533  if( sqlite3VdbeMemSetStr(&pCtx->s, z, n, enc, xDel)==SQLITE_TOOBIG ){
60534    sqlite3_result_error_toobig(pCtx);
60535  }
60536}
60537SQLITE_API void sqlite3_result_blob(
60538  sqlite3_context *pCtx,
60539  const void *z,
60540  int n,
60541  void (*xDel)(void *)
60542){
60543  assert( n>=0 );
60544  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
60545  setResultStrOrError(pCtx, z, n, 0, xDel);
60546}
60547SQLITE_API void sqlite3_result_double(sqlite3_context *pCtx, double rVal){
60548  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
60549  sqlite3VdbeMemSetDouble(&pCtx->s, rVal);
60550}
60551SQLITE_API void sqlite3_result_error(sqlite3_context *pCtx, const char *z, int n){
60552  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
60553  pCtx->isError = SQLITE_ERROR;
60554  sqlite3VdbeMemSetStr(&pCtx->s, z, n, SQLITE_UTF8, SQLITE_TRANSIENT);
60555}
60556#ifndef SQLITE_OMIT_UTF16
60557SQLITE_API void sqlite3_result_error16(sqlite3_context *pCtx, const void *z, int n){
60558  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
60559  pCtx->isError = SQLITE_ERROR;
60560  sqlite3VdbeMemSetStr(&pCtx->s, z, n, SQLITE_UTF16NATIVE, SQLITE_TRANSIENT);
60561}
60562#endif
60563SQLITE_API void sqlite3_result_int(sqlite3_context *pCtx, int iVal){
60564  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
60565  sqlite3VdbeMemSetInt64(&pCtx->s, (i64)iVal);
60566}
60567SQLITE_API void sqlite3_result_int64(sqlite3_context *pCtx, i64 iVal){
60568  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
60569  sqlite3VdbeMemSetInt64(&pCtx->s, iVal);
60570}
60571SQLITE_API void sqlite3_result_null(sqlite3_context *pCtx){
60572  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
60573  sqlite3VdbeMemSetNull(&pCtx->s);
60574}
60575SQLITE_API void sqlite3_result_text(
60576  sqlite3_context *pCtx,
60577  const char *z,
60578  int n,
60579  void (*xDel)(void *)
60580){
60581  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
60582  setResultStrOrError(pCtx, z, n, SQLITE_UTF8, xDel);
60583}
60584#ifndef SQLITE_OMIT_UTF16
60585SQLITE_API void sqlite3_result_text16(
60586  sqlite3_context *pCtx,
60587  const void *z,
60588  int n,
60589  void (*xDel)(void *)
60590){
60591  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
60592  setResultStrOrError(pCtx, z, n, SQLITE_UTF16NATIVE, xDel);
60593}
60594SQLITE_API void sqlite3_result_text16be(
60595  sqlite3_context *pCtx,
60596  const void *z,
60597  int n,
60598  void (*xDel)(void *)
60599){
60600  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
60601  setResultStrOrError(pCtx, z, n, SQLITE_UTF16BE, xDel);
60602}
60603SQLITE_API void sqlite3_result_text16le(
60604  sqlite3_context *pCtx,
60605  const void *z,
60606  int n,
60607  void (*xDel)(void *)
60608){
60609  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
60610  setResultStrOrError(pCtx, z, n, SQLITE_UTF16LE, xDel);
60611}
60612#endif /* SQLITE_OMIT_UTF16 */
60613SQLITE_API void sqlite3_result_value(sqlite3_context *pCtx, sqlite3_value *pValue){
60614  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
60615  sqlite3VdbeMemCopy(&pCtx->s, pValue);
60616}
60617SQLITE_API void sqlite3_result_zeroblob(sqlite3_context *pCtx, int n){
60618  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
60619  sqlite3VdbeMemSetZeroBlob(&pCtx->s, n);
60620}
60621SQLITE_API void sqlite3_result_error_code(sqlite3_context *pCtx, int errCode){
60622  pCtx->isError = errCode;
60623  if( pCtx->s.flags & MEM_Null ){
60624    sqlite3VdbeMemSetStr(&pCtx->s, sqlite3ErrStr(errCode), -1,
60625                         SQLITE_UTF8, SQLITE_STATIC);
60626  }
60627}
60628
60629/* Force an SQLITE_TOOBIG error. */
60630SQLITE_API void sqlite3_result_error_toobig(sqlite3_context *pCtx){
60631  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
60632  pCtx->isError = SQLITE_TOOBIG;
60633  sqlite3VdbeMemSetStr(&pCtx->s, "string or blob too big", -1,
60634                       SQLITE_UTF8, SQLITE_STATIC);
60635}
60636
60637/* An SQLITE_NOMEM error. */
60638SQLITE_API void sqlite3_result_error_nomem(sqlite3_context *pCtx){
60639  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
60640  sqlite3VdbeMemSetNull(&pCtx->s);
60641  pCtx->isError = SQLITE_NOMEM;
60642  pCtx->s.db->mallocFailed = 1;
60643}
60644
60645/*
60646** This function is called after a transaction has been committed. It
60647** invokes callbacks registered with sqlite3_wal_hook() as required.
60648*/
60649static int doWalCallbacks(sqlite3 *db){
60650  int rc = SQLITE_OK;
60651#ifndef SQLITE_OMIT_WAL
60652  int i;
60653  for(i=0; i<db->nDb; i++){
60654    Btree *pBt = db->aDb[i].pBt;
60655    if( pBt ){
60656      int nEntry = sqlite3PagerWalCallback(sqlite3BtreePager(pBt));
60657      if( db->xWalCallback && nEntry>0 && rc==SQLITE_OK ){
60658        rc = db->xWalCallback(db->pWalArg, db, db->aDb[i].zName, nEntry);
60659      }
60660    }
60661  }
60662#endif
60663  return rc;
60664}
60665
60666/*
60667** Execute the statement pStmt, either until a row of data is ready, the
60668** statement is completely executed or an error occurs.
60669**
60670** This routine implements the bulk of the logic behind the sqlite_step()
60671** API.  The only thing omitted is the automatic recompile if a
60672** schema change has occurred.  That detail is handled by the
60673** outer sqlite3_step() wrapper procedure.
60674*/
60675static int sqlite3Step(Vdbe *p){
60676  sqlite3 *db;
60677  int rc;
60678
60679  assert(p);
60680  if( p->magic!=VDBE_MAGIC_RUN ){
60681    /* We used to require that sqlite3_reset() be called before retrying
60682    ** sqlite3_step() after any error or after SQLITE_DONE.  But beginning
60683    ** with version 3.7.0, we changed this so that sqlite3_reset() would
60684    ** be called automatically instead of throwing the SQLITE_MISUSE error.
60685    ** This "automatic-reset" change is not technically an incompatibility,
60686    ** since any application that receives an SQLITE_MISUSE is broken by
60687    ** definition.
60688    **
60689    ** Nevertheless, some published applications that were originally written
60690    ** for version 3.6.23 or earlier do in fact depend on SQLITE_MISUSE
60691    ** returns, and the so were broken by the automatic-reset change.  As a
60692    ** a work-around, the SQLITE_OMIT_AUTORESET compile-time restores the
60693    ** legacy behavior of returning SQLITE_MISUSE for cases where the
60694    ** previous sqlite3_step() returned something other than a SQLITE_LOCKED
60695    ** or SQLITE_BUSY error.
60696    */
60697#ifdef SQLITE_OMIT_AUTORESET
60698    if( p->rc==SQLITE_BUSY || p->rc==SQLITE_LOCKED ){
60699      sqlite3_reset((sqlite3_stmt*)p);
60700    }else{
60701      return SQLITE_MISUSE_BKPT;
60702    }
60703#else
60704    sqlite3_reset((sqlite3_stmt*)p);
60705#endif
60706  }
60707
60708  /* Check that malloc() has not failed. If it has, return early. */
60709  db = p->db;
60710  if( db->mallocFailed ){
60711    p->rc = SQLITE_NOMEM;
60712    return SQLITE_NOMEM;
60713  }
60714
60715  if( p->pc<=0 && p->expired ){
60716    p->rc = SQLITE_SCHEMA;
60717    rc = SQLITE_ERROR;
60718    goto end_of_step;
60719  }
60720  if( p->pc<0 ){
60721    /* If there are no other statements currently running, then
60722    ** reset the interrupt flag.  This prevents a call to sqlite3_interrupt
60723    ** from interrupting a statement that has not yet started.
60724    */
60725    if( db->activeVdbeCnt==0 ){
60726      db->u1.isInterrupted = 0;
60727    }
60728
60729    assert( db->writeVdbeCnt>0 || db->autoCommit==0 || db->nDeferredCons==0 );
60730
60731#ifndef SQLITE_OMIT_TRACE
60732    if( db->xProfile && !db->init.busy ){
60733      sqlite3OsCurrentTimeInt64(db->pVfs, &p->startTime);
60734    }
60735#endif
60736
60737    db->activeVdbeCnt++;
60738    if( p->readOnly==0 ) db->writeVdbeCnt++;
60739    p->pc = 0;
60740  }
60741#ifndef SQLITE_OMIT_EXPLAIN
60742  if( p->explain ){
60743    rc = sqlite3VdbeList(p);
60744  }else
60745#endif /* SQLITE_OMIT_EXPLAIN */
60746  {
60747    db->vdbeExecCnt++;
60748    rc = sqlite3VdbeExec(p);
60749    db->vdbeExecCnt--;
60750  }
60751
60752#ifndef SQLITE_OMIT_TRACE
60753  /* Invoke the profile callback if there is one
60754  */
60755  if( rc!=SQLITE_ROW && db->xProfile && !db->init.busy && p->zSql ){
60756    sqlite3_int64 iNow;
60757    sqlite3OsCurrentTimeInt64(db->pVfs, &iNow);
60758    db->xProfile(db->pProfileArg, p->zSql, (iNow - p->startTime)*1000000);
60759  }
60760#endif
60761
60762  if( rc==SQLITE_DONE ){
60763    assert( p->rc==SQLITE_OK );
60764    p->rc = doWalCallbacks(db);
60765    if( p->rc!=SQLITE_OK ){
60766      rc = SQLITE_ERROR;
60767    }
60768  }
60769
60770  db->errCode = rc;
60771  if( SQLITE_NOMEM==sqlite3ApiExit(p->db, p->rc) ){
60772    p->rc = SQLITE_NOMEM;
60773  }
60774end_of_step:
60775  /* At this point local variable rc holds the value that should be
60776  ** returned if this statement was compiled using the legacy
60777  ** sqlite3_prepare() interface. According to the docs, this can only
60778  ** be one of the values in the first assert() below. Variable p->rc
60779  ** contains the value that would be returned if sqlite3_finalize()
60780  ** were called on statement p.
60781  */
60782  assert( rc==SQLITE_ROW  || rc==SQLITE_DONE   || rc==SQLITE_ERROR
60783       || rc==SQLITE_BUSY || rc==SQLITE_MISUSE
60784  );
60785  assert( p->rc!=SQLITE_ROW && p->rc!=SQLITE_DONE );
60786  if( p->isPrepareV2 && rc!=SQLITE_ROW && rc!=SQLITE_DONE ){
60787    /* If this statement was prepared using sqlite3_prepare_v2(), and an
60788    ** error has occured, then return the error code in p->rc to the
60789    ** caller. Set the error code in the database handle to the same value.
60790    */
60791    rc = db->errCode = p->rc;
60792  }
60793  return (rc&db->errMask);
60794}
60795
60796/*
60797** This is the top-level implementation of sqlite3_step().  Call
60798** sqlite3Step() to do most of the work.  If a schema error occurs,
60799** call sqlite3Reprepare() and try again.
60800*/
60801SQLITE_API int sqlite3_step(sqlite3_stmt *pStmt){
60802  int rc = SQLITE_OK;      /* Result from sqlite3Step() */
60803  int rc2 = SQLITE_OK;     /* Result from sqlite3Reprepare() */
60804  Vdbe *v = (Vdbe*)pStmt;  /* the prepared statement */
60805  int cnt = 0;             /* Counter to prevent infinite loop of reprepares */
60806  sqlite3 *db;             /* The database connection */
60807
60808  if( vdbeSafetyNotNull(v) ){
60809    return SQLITE_MISUSE_BKPT;
60810  }
60811  db = v->db;
60812  sqlite3_mutex_enter(db->mutex);
60813  while( (rc = sqlite3Step(v))==SQLITE_SCHEMA
60814         && cnt++ < 5
60815         && (rc2 = rc = sqlite3Reprepare(v))==SQLITE_OK ){
60816    sqlite3_reset(pStmt);
60817    v->expired = 0;
60818  }
60819  if( rc2!=SQLITE_OK && ALWAYS(v->isPrepareV2) && ALWAYS(db->pErr) ){
60820    /* This case occurs after failing to recompile an sql statement.
60821    ** The error message from the SQL compiler has already been loaded
60822    ** into the database handle. This block copies the error message
60823    ** from the database handle into the statement and sets the statement
60824    ** program counter to 0 to ensure that when the statement is
60825    ** finalized or reset the parser error message is available via
60826    ** sqlite3_errmsg() and sqlite3_errcode().
60827    */
60828    const char *zErr = (const char *)sqlite3_value_text(db->pErr);
60829    sqlite3DbFree(db, v->zErrMsg);
60830    if( !db->mallocFailed ){
60831      v->zErrMsg = sqlite3DbStrDup(db, zErr);
60832      v->rc = rc2;
60833    } else {
60834      v->zErrMsg = 0;
60835      v->rc = rc = SQLITE_NOMEM;
60836    }
60837  }
60838  rc = sqlite3ApiExit(db, rc);
60839  sqlite3_mutex_leave(db->mutex);
60840  return rc;
60841}
60842
60843/*
60844** Extract the user data from a sqlite3_context structure and return a
60845** pointer to it.
60846*/
60847SQLITE_API void *sqlite3_user_data(sqlite3_context *p){
60848  assert( p && p->pFunc );
60849  return p->pFunc->pUserData;
60850}
60851
60852/*
60853** Extract the user data from a sqlite3_context structure and return a
60854** pointer to it.
60855**
60856** IMPLEMENTATION-OF: R-46798-50301 The sqlite3_context_db_handle() interface
60857** returns a copy of the pointer to the database connection (the 1st
60858** parameter) of the sqlite3_create_function() and
60859** sqlite3_create_function16() routines that originally registered the
60860** application defined function.
60861*/
60862SQLITE_API sqlite3 *sqlite3_context_db_handle(sqlite3_context *p){
60863  assert( p && p->pFunc );
60864  return p->s.db;
60865}
60866
60867/*
60868** The following is the implementation of an SQL function that always
60869** fails with an error message stating that the function is used in the
60870** wrong context.  The sqlite3_overload_function() API might construct
60871** SQL function that use this routine so that the functions will exist
60872** for name resolution but are actually overloaded by the xFindFunction
60873** method of virtual tables.
60874*/
60875SQLITE_PRIVATE void sqlite3InvalidFunction(
60876  sqlite3_context *context,  /* The function calling context */
60877  int NotUsed,               /* Number of arguments to the function */
60878  sqlite3_value **NotUsed2   /* Value of each argument */
60879){
60880  const char *zName = context->pFunc->zName;
60881  char *zErr;
60882  UNUSED_PARAMETER2(NotUsed, NotUsed2);
60883  zErr = sqlite3_mprintf(
60884      "unable to use function %s in the requested context", zName);
60885  sqlite3_result_error(context, zErr, -1);
60886  sqlite3_free(zErr);
60887}
60888
60889/*
60890** Allocate or return the aggregate context for a user function.  A new
60891** context is allocated on the first call.  Subsequent calls return the
60892** same context that was returned on prior calls.
60893*/
60894SQLITE_API void *sqlite3_aggregate_context(sqlite3_context *p, int nByte){
60895  Mem *pMem;
60896  assert( p && p->pFunc && p->pFunc->xStep );
60897  assert( sqlite3_mutex_held(p->s.db->mutex) );
60898  pMem = p->pMem;
60899  testcase( nByte<0 );
60900  if( (pMem->flags & MEM_Agg)==0 ){
60901    if( nByte<=0 ){
60902      sqlite3VdbeMemReleaseExternal(pMem);
60903      pMem->flags = MEM_Null;
60904      pMem->z = 0;
60905    }else{
60906      sqlite3VdbeMemGrow(pMem, nByte, 0);
60907      pMem->flags = MEM_Agg;
60908      pMem->u.pDef = p->pFunc;
60909      if( pMem->z ){
60910        memset(pMem->z, 0, nByte);
60911      }
60912    }
60913  }
60914  return (void*)pMem->z;
60915}
60916
60917/*
60918** Return the auxilary data pointer, if any, for the iArg'th argument to
60919** the user-function defined by pCtx.
60920*/
60921SQLITE_API void *sqlite3_get_auxdata(sqlite3_context *pCtx, int iArg){
60922  VdbeFunc *pVdbeFunc;
60923
60924  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
60925  pVdbeFunc = pCtx->pVdbeFunc;
60926  if( !pVdbeFunc || iArg>=pVdbeFunc->nAux || iArg<0 ){
60927    return 0;
60928  }
60929  return pVdbeFunc->apAux[iArg].pAux;
60930}
60931
60932/*
60933** Set the auxilary data pointer and delete function, for the iArg'th
60934** argument to the user-function defined by pCtx. Any previous value is
60935** deleted by calling the delete function specified when it was set.
60936*/
60937SQLITE_API void sqlite3_set_auxdata(
60938  sqlite3_context *pCtx,
60939  int iArg,
60940  void *pAux,
60941  void (*xDelete)(void*)
60942){
60943  struct AuxData *pAuxData;
60944  VdbeFunc *pVdbeFunc;
60945  if( iArg<0 ) goto failed;
60946
60947  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
60948  pVdbeFunc = pCtx->pVdbeFunc;
60949  if( !pVdbeFunc || pVdbeFunc->nAux<=iArg ){
60950    int nAux = (pVdbeFunc ? pVdbeFunc->nAux : 0);
60951    int nMalloc = sizeof(VdbeFunc) + sizeof(struct AuxData)*iArg;
60952    pVdbeFunc = sqlite3DbRealloc(pCtx->s.db, pVdbeFunc, nMalloc);
60953    if( !pVdbeFunc ){
60954      goto failed;
60955    }
60956    pCtx->pVdbeFunc = pVdbeFunc;
60957    memset(&pVdbeFunc->apAux[nAux], 0, sizeof(struct AuxData)*(iArg+1-nAux));
60958    pVdbeFunc->nAux = iArg+1;
60959    pVdbeFunc->pFunc = pCtx->pFunc;
60960  }
60961
60962  pAuxData = &pVdbeFunc->apAux[iArg];
60963  if( pAuxData->pAux && pAuxData->xDelete ){
60964    pAuxData->xDelete(pAuxData->pAux);
60965  }
60966  pAuxData->pAux = pAux;
60967  pAuxData->xDelete = xDelete;
60968  return;
60969
60970failed:
60971  if( xDelete ){
60972    xDelete(pAux);
60973  }
60974}
60975
60976#ifndef SQLITE_OMIT_DEPRECATED
60977/*
60978** Return the number of times the Step function of a aggregate has been
60979** called.
60980**
60981** This function is deprecated.  Do not use it for new code.  It is
60982** provide only to avoid breaking legacy code.  New aggregate function
60983** implementations should keep their own counts within their aggregate
60984** context.
60985*/
60986SQLITE_API int sqlite3_aggregate_count(sqlite3_context *p){
60987  assert( p && p->pMem && p->pFunc && p->pFunc->xStep );
60988  return p->pMem->n;
60989}
60990#endif
60991
60992/*
60993** Return the number of columns in the result set for the statement pStmt.
60994*/
60995SQLITE_API int sqlite3_column_count(sqlite3_stmt *pStmt){
60996  Vdbe *pVm = (Vdbe *)pStmt;
60997  return pVm ? pVm->nResColumn : 0;
60998}
60999
61000/*
61001** Return the number of values available from the current row of the
61002** currently executing statement pStmt.
61003*/
61004SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt){
61005  Vdbe *pVm = (Vdbe *)pStmt;
61006  if( pVm==0 || pVm->pResultSet==0 ) return 0;
61007  return pVm->nResColumn;
61008}
61009
61010
61011/*
61012** Check to see if column iCol of the given statement is valid.  If
61013** it is, return a pointer to the Mem for the value of that column.
61014** If iCol is not valid, return a pointer to a Mem which has a value
61015** of NULL.
61016*/
61017static Mem *columnMem(sqlite3_stmt *pStmt, int i){
61018  Vdbe *pVm;
61019  Mem *pOut;
61020
61021  pVm = (Vdbe *)pStmt;
61022  if( pVm && pVm->pResultSet!=0 && i<pVm->nResColumn && i>=0 ){
61023    sqlite3_mutex_enter(pVm->db->mutex);
61024    pOut = &pVm->pResultSet[i];
61025  }else{
61026    /* If the value passed as the second argument is out of range, return
61027    ** a pointer to the following static Mem object which contains the
61028    ** value SQL NULL. Even though the Mem structure contains an element
61029    ** of type i64, on certain architecture (x86) with certain compiler
61030    ** switches (-Os), gcc may align this Mem object on a 4-byte boundary
61031    ** instead of an 8-byte one. This all works fine, except that when
61032    ** running with SQLITE_DEBUG defined the SQLite code sometimes assert()s
61033    ** that a Mem structure is located on an 8-byte boundary. To prevent
61034    ** this assert() from failing, when building with SQLITE_DEBUG defined
61035    ** using gcc, force nullMem to be 8-byte aligned using the magical
61036    ** __attribute__((aligned(8))) macro.  */
61037    static const Mem nullMem
61038#if defined(SQLITE_DEBUG) && defined(__GNUC__)
61039      __attribute__((aligned(8)))
61040#endif
61041      = {0, "", (double)0, {0}, 0, MEM_Null, SQLITE_NULL, 0,
61042#ifdef SQLITE_DEBUG
61043         0, 0,  /* pScopyFrom, pFiller */
61044#endif
61045         0, 0 };
61046
61047    if( pVm && ALWAYS(pVm->db) ){
61048      sqlite3_mutex_enter(pVm->db->mutex);
61049      sqlite3Error(pVm->db, SQLITE_RANGE, 0);
61050    }
61051    pOut = (Mem*)&nullMem;
61052  }
61053  return pOut;
61054}
61055
61056/*
61057** This function is called after invoking an sqlite3_value_XXX function on a
61058** column value (i.e. a value returned by evaluating an SQL expression in the
61059** select list of a SELECT statement) that may cause a malloc() failure. If
61060** malloc() has failed, the threads mallocFailed flag is cleared and the result
61061** code of statement pStmt set to SQLITE_NOMEM.
61062**
61063** Specifically, this is called from within:
61064**
61065**     sqlite3_column_int()
61066**     sqlite3_column_int64()
61067**     sqlite3_column_text()
61068**     sqlite3_column_text16()
61069**     sqlite3_column_real()
61070**     sqlite3_column_bytes()
61071**     sqlite3_column_bytes16()
61072**     sqiite3_column_blob()
61073*/
61074static void columnMallocFailure(sqlite3_stmt *pStmt)
61075{
61076  /* If malloc() failed during an encoding conversion within an
61077  ** sqlite3_column_XXX API, then set the return code of the statement to
61078  ** SQLITE_NOMEM. The next call to _step() (if any) will return SQLITE_ERROR
61079  ** and _finalize() will return NOMEM.
61080  */
61081  Vdbe *p = (Vdbe *)pStmt;
61082  if( p ){
61083    p->rc = sqlite3ApiExit(p->db, p->rc);
61084    sqlite3_mutex_leave(p->db->mutex);
61085  }
61086}
61087
61088/**************************** sqlite3_column_  *******************************
61089** The following routines are used to access elements of the current row
61090** in the result set.
61091*/
61092SQLITE_API const void *sqlite3_column_blob(sqlite3_stmt *pStmt, int i){
61093  const void *val;
61094  val = sqlite3_value_blob( columnMem(pStmt,i) );
61095  /* Even though there is no encoding conversion, value_blob() might
61096  ** need to call malloc() to expand the result of a zeroblob()
61097  ** expression.
61098  */
61099  columnMallocFailure(pStmt);
61100  return val;
61101}
61102SQLITE_API int sqlite3_column_bytes(sqlite3_stmt *pStmt, int i){
61103  int val = sqlite3_value_bytes( columnMem(pStmt,i) );
61104  columnMallocFailure(pStmt);
61105  return val;
61106}
61107SQLITE_API int sqlite3_column_bytes16(sqlite3_stmt *pStmt, int i){
61108  int val = sqlite3_value_bytes16( columnMem(pStmt,i) );
61109  columnMallocFailure(pStmt);
61110  return val;
61111}
61112SQLITE_API double sqlite3_column_double(sqlite3_stmt *pStmt, int i){
61113  double val = sqlite3_value_double( columnMem(pStmt,i) );
61114  columnMallocFailure(pStmt);
61115  return val;
61116}
61117SQLITE_API int sqlite3_column_int(sqlite3_stmt *pStmt, int i){
61118  int val = sqlite3_value_int( columnMem(pStmt,i) );
61119  columnMallocFailure(pStmt);
61120  return val;
61121}
61122SQLITE_API sqlite_int64 sqlite3_column_int64(sqlite3_stmt *pStmt, int i){
61123  sqlite_int64 val = sqlite3_value_int64( columnMem(pStmt,i) );
61124  columnMallocFailure(pStmt);
61125  return val;
61126}
61127SQLITE_API const unsigned char *sqlite3_column_text(sqlite3_stmt *pStmt, int i){
61128  const unsigned char *val = sqlite3_value_text( columnMem(pStmt,i) );
61129  columnMallocFailure(pStmt);
61130  return val;
61131}
61132SQLITE_API sqlite3_value *sqlite3_column_value(sqlite3_stmt *pStmt, int i){
61133  Mem *pOut = columnMem(pStmt, i);
61134  if( pOut->flags&MEM_Static ){
61135    pOut->flags &= ~MEM_Static;
61136    pOut->flags |= MEM_Ephem;
61137  }
61138  columnMallocFailure(pStmt);
61139  return (sqlite3_value *)pOut;
61140}
61141#ifndef SQLITE_OMIT_UTF16
61142SQLITE_API const void *sqlite3_column_text16(sqlite3_stmt *pStmt, int i){
61143  const void *val = sqlite3_value_text16( columnMem(pStmt,i) );
61144  columnMallocFailure(pStmt);
61145  return val;
61146}
61147#endif /* SQLITE_OMIT_UTF16 */
61148SQLITE_API int sqlite3_column_type(sqlite3_stmt *pStmt, int i){
61149  int iType = sqlite3_value_type( columnMem(pStmt,i) );
61150  columnMallocFailure(pStmt);
61151  return iType;
61152}
61153
61154/* The following function is experimental and subject to change or
61155** removal */
61156/*int sqlite3_column_numeric_type(sqlite3_stmt *pStmt, int i){
61157**  return sqlite3_value_numeric_type( columnMem(pStmt,i) );
61158**}
61159*/
61160
61161/*
61162** Convert the N-th element of pStmt->pColName[] into a string using
61163** xFunc() then return that string.  If N is out of range, return 0.
61164**
61165** There are up to 5 names for each column.  useType determines which
61166** name is returned.  Here are the names:
61167**
61168**    0      The column name as it should be displayed for output
61169**    1      The datatype name for the column
61170**    2      The name of the database that the column derives from
61171**    3      The name of the table that the column derives from
61172**    4      The name of the table column that the result column derives from
61173**
61174** If the result is not a simple column reference (if it is an expression
61175** or a constant) then useTypes 2, 3, and 4 return NULL.
61176*/
61177static const void *columnName(
61178  sqlite3_stmt *pStmt,
61179  int N,
61180  const void *(*xFunc)(Mem*),
61181  int useType
61182){
61183  const void *ret = 0;
61184  Vdbe *p = (Vdbe *)pStmt;
61185  int n;
61186  sqlite3 *db = p->db;
61187
61188  assert( db!=0 );
61189  n = sqlite3_column_count(pStmt);
61190  if( N<n && N>=0 ){
61191    N += useType*n;
61192    sqlite3_mutex_enter(db->mutex);
61193    assert( db->mallocFailed==0 );
61194    ret = xFunc(&p->aColName[N]);
61195     /* A malloc may have failed inside of the xFunc() call. If this
61196    ** is the case, clear the mallocFailed flag and return NULL.
61197    */
61198    if( db->mallocFailed ){
61199      db->mallocFailed = 0;
61200      ret = 0;
61201    }
61202    sqlite3_mutex_leave(db->mutex);
61203  }
61204  return ret;
61205}
61206
61207/*
61208** Return the name of the Nth column of the result set returned by SQL
61209** statement pStmt.
61210*/
61211SQLITE_API const char *sqlite3_column_name(sqlite3_stmt *pStmt, int N){
61212  return columnName(
61213      pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_NAME);
61214}
61215#ifndef SQLITE_OMIT_UTF16
61216SQLITE_API const void *sqlite3_column_name16(sqlite3_stmt *pStmt, int N){
61217  return columnName(
61218      pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_NAME);
61219}
61220#endif
61221
61222/*
61223** Constraint:  If you have ENABLE_COLUMN_METADATA then you must
61224** not define OMIT_DECLTYPE.
61225*/
61226#if defined(SQLITE_OMIT_DECLTYPE) && defined(SQLITE_ENABLE_COLUMN_METADATA)
61227# error "Must not define both SQLITE_OMIT_DECLTYPE \
61228         and SQLITE_ENABLE_COLUMN_METADATA"
61229#endif
61230
61231#ifndef SQLITE_OMIT_DECLTYPE
61232/*
61233** Return the column declaration type (if applicable) of the 'i'th column
61234** of the result set of SQL statement pStmt.
61235*/
61236SQLITE_API const char *sqlite3_column_decltype(sqlite3_stmt *pStmt, int N){
61237  return columnName(
61238      pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_DECLTYPE);
61239}
61240#ifndef SQLITE_OMIT_UTF16
61241SQLITE_API const void *sqlite3_column_decltype16(sqlite3_stmt *pStmt, int N){
61242  return columnName(
61243      pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_DECLTYPE);
61244}
61245#endif /* SQLITE_OMIT_UTF16 */
61246#endif /* SQLITE_OMIT_DECLTYPE */
61247
61248#ifdef SQLITE_ENABLE_COLUMN_METADATA
61249/*
61250** Return the name of the database from which a result column derives.
61251** NULL is returned if the result column is an expression or constant or
61252** anything else which is not an unabiguous reference to a database column.
61253*/
61254SQLITE_API const char *sqlite3_column_database_name(sqlite3_stmt *pStmt, int N){
61255  return columnName(
61256      pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_DATABASE);
61257}
61258#ifndef SQLITE_OMIT_UTF16
61259SQLITE_API const void *sqlite3_column_database_name16(sqlite3_stmt *pStmt, int N){
61260  return columnName(
61261      pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_DATABASE);
61262}
61263#endif /* SQLITE_OMIT_UTF16 */
61264
61265/*
61266** Return the name of the table from which a result column derives.
61267** NULL is returned if the result column is an expression or constant or
61268** anything else which is not an unabiguous reference to a database column.
61269*/
61270SQLITE_API const char *sqlite3_column_table_name(sqlite3_stmt *pStmt, int N){
61271  return columnName(
61272      pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_TABLE);
61273}
61274#ifndef SQLITE_OMIT_UTF16
61275SQLITE_API const void *sqlite3_column_table_name16(sqlite3_stmt *pStmt, int N){
61276  return columnName(
61277      pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_TABLE);
61278}
61279#endif /* SQLITE_OMIT_UTF16 */
61280
61281/*
61282** Return the name of the table column from which a result column derives.
61283** NULL is returned if the result column is an expression or constant or
61284** anything else which is not an unabiguous reference to a database column.
61285*/
61286SQLITE_API const char *sqlite3_column_origin_name(sqlite3_stmt *pStmt, int N){
61287  return columnName(
61288      pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_COLUMN);
61289}
61290#ifndef SQLITE_OMIT_UTF16
61291SQLITE_API const void *sqlite3_column_origin_name16(sqlite3_stmt *pStmt, int N){
61292  return columnName(
61293      pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_COLUMN);
61294}
61295#endif /* SQLITE_OMIT_UTF16 */
61296#endif /* SQLITE_ENABLE_COLUMN_METADATA */
61297
61298
61299/******************************* sqlite3_bind_  ***************************
61300**
61301** Routines used to attach values to wildcards in a compiled SQL statement.
61302*/
61303/*
61304** Unbind the value bound to variable i in virtual machine p. This is the
61305** the same as binding a NULL value to the column. If the "i" parameter is
61306** out of range, then SQLITE_RANGE is returned. Othewise SQLITE_OK.
61307**
61308** A successful evaluation of this routine acquires the mutex on p.
61309** the mutex is released if any kind of error occurs.
61310**
61311** The error code stored in database p->db is overwritten with the return
61312** value in any case.
61313*/
61314static int vdbeUnbind(Vdbe *p, int i){
61315  Mem *pVar;
61316  if( vdbeSafetyNotNull(p) ){
61317    return SQLITE_MISUSE_BKPT;
61318  }
61319  sqlite3_mutex_enter(p->db->mutex);
61320  if( p->magic!=VDBE_MAGIC_RUN || p->pc>=0 ){
61321    sqlite3Error(p->db, SQLITE_MISUSE, 0);
61322    sqlite3_mutex_leave(p->db->mutex);
61323    sqlite3_log(SQLITE_MISUSE,
61324        "bind on a busy prepared statement: [%s]", p->zSql);
61325    return SQLITE_MISUSE_BKPT;
61326  }
61327  if( i<1 || i>p->nVar ){
61328    sqlite3Error(p->db, SQLITE_RANGE, 0);
61329    sqlite3_mutex_leave(p->db->mutex);
61330    return SQLITE_RANGE;
61331  }
61332  i--;
61333  pVar = &p->aVar[i];
61334  sqlite3VdbeMemRelease(pVar);
61335  pVar->flags = MEM_Null;
61336  sqlite3Error(p->db, SQLITE_OK, 0);
61337
61338  /* If the bit corresponding to this variable in Vdbe.expmask is set, then
61339  ** binding a new value to this variable invalidates the current query plan.
61340  **
61341  ** IMPLEMENTATION-OF: R-48440-37595 If the specific value bound to host
61342  ** parameter in the WHERE clause might influence the choice of query plan
61343  ** for a statement, then the statement will be automatically recompiled,
61344  ** as if there had been a schema change, on the first sqlite3_step() call
61345  ** following any change to the bindings of that parameter.
61346  */
61347  if( p->isPrepareV2 &&
61348     ((i<32 && p->expmask & ((u32)1 << i)) || p->expmask==0xffffffff)
61349  ){
61350    p->expired = 1;
61351  }
61352  return SQLITE_OK;
61353}
61354
61355/*
61356** Bind a text or BLOB value.
61357*/
61358static int bindText(
61359  sqlite3_stmt *pStmt,   /* The statement to bind against */
61360  int i,                 /* Index of the parameter to bind */
61361  const void *zData,     /* Pointer to the data to be bound */
61362  int nData,             /* Number of bytes of data to be bound */
61363  void (*xDel)(void*),   /* Destructor for the data */
61364  u8 encoding            /* Encoding for the data */
61365){
61366  Vdbe *p = (Vdbe *)pStmt;
61367  Mem *pVar;
61368  int rc;
61369
61370  rc = vdbeUnbind(p, i);
61371  if( rc==SQLITE_OK ){
61372    if( zData!=0 ){
61373      pVar = &p->aVar[i-1];
61374      rc = sqlite3VdbeMemSetStr(pVar, zData, nData, encoding, xDel);
61375      if( rc==SQLITE_OK && encoding!=0 ){
61376        rc = sqlite3VdbeChangeEncoding(pVar, ENC(p->db));
61377      }
61378      sqlite3Error(p->db, rc, 0);
61379      rc = sqlite3ApiExit(p->db, rc);
61380    }
61381    sqlite3_mutex_leave(p->db->mutex);
61382  }else if( xDel!=SQLITE_STATIC && xDel!=SQLITE_TRANSIENT ){
61383    xDel((void*)zData);
61384  }
61385  return rc;
61386}
61387
61388
61389/*
61390** Bind a blob value to an SQL statement variable.
61391*/
61392SQLITE_API int sqlite3_bind_blob(
61393  sqlite3_stmt *pStmt,
61394  int i,
61395  const void *zData,
61396  int nData,
61397  void (*xDel)(void*)
61398){
61399  return bindText(pStmt, i, zData, nData, xDel, 0);
61400}
61401SQLITE_API int sqlite3_bind_double(sqlite3_stmt *pStmt, int i, double rValue){
61402  int rc;
61403  Vdbe *p = (Vdbe *)pStmt;
61404  rc = vdbeUnbind(p, i);
61405  if( rc==SQLITE_OK ){
61406    sqlite3VdbeMemSetDouble(&p->aVar[i-1], rValue);
61407    sqlite3_mutex_leave(p->db->mutex);
61408  }
61409  return rc;
61410}
61411SQLITE_API int sqlite3_bind_int(sqlite3_stmt *p, int i, int iValue){
61412  return sqlite3_bind_int64(p, i, (i64)iValue);
61413}
61414SQLITE_API int sqlite3_bind_int64(sqlite3_stmt *pStmt, int i, sqlite_int64 iValue){
61415  int rc;
61416  Vdbe *p = (Vdbe *)pStmt;
61417  rc = vdbeUnbind(p, i);
61418  if( rc==SQLITE_OK ){
61419    sqlite3VdbeMemSetInt64(&p->aVar[i-1], iValue);
61420    sqlite3_mutex_leave(p->db->mutex);
61421  }
61422  return rc;
61423}
61424SQLITE_API int sqlite3_bind_null(sqlite3_stmt *pStmt, int i){
61425  int rc;
61426  Vdbe *p = (Vdbe*)pStmt;
61427  rc = vdbeUnbind(p, i);
61428  if( rc==SQLITE_OK ){
61429    sqlite3_mutex_leave(p->db->mutex);
61430  }
61431  return rc;
61432}
61433SQLITE_API int sqlite3_bind_text(
61434  sqlite3_stmt *pStmt,
61435  int i,
61436  const char *zData,
61437  int nData,
61438  void (*xDel)(void*)
61439){
61440  return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF8);
61441}
61442#ifndef SQLITE_OMIT_UTF16
61443SQLITE_API int sqlite3_bind_text16(
61444  sqlite3_stmt *pStmt,
61445  int i,
61446  const void *zData,
61447  int nData,
61448  void (*xDel)(void*)
61449){
61450  return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF16NATIVE);
61451}
61452#endif /* SQLITE_OMIT_UTF16 */
61453SQLITE_API int sqlite3_bind_value(sqlite3_stmt *pStmt, int i, const sqlite3_value *pValue){
61454  int rc;
61455  switch( pValue->type ){
61456    case SQLITE_INTEGER: {
61457      rc = sqlite3_bind_int64(pStmt, i, pValue->u.i);
61458      break;
61459    }
61460    case SQLITE_FLOAT: {
61461      rc = sqlite3_bind_double(pStmt, i, pValue->r);
61462      break;
61463    }
61464    case SQLITE_BLOB: {
61465      if( pValue->flags & MEM_Zero ){
61466        rc = sqlite3_bind_zeroblob(pStmt, i, pValue->u.nZero);
61467      }else{
61468        rc = sqlite3_bind_blob(pStmt, i, pValue->z, pValue->n,SQLITE_TRANSIENT);
61469      }
61470      break;
61471    }
61472    case SQLITE_TEXT: {
61473      rc = bindText(pStmt,i,  pValue->z, pValue->n, SQLITE_TRANSIENT,
61474                              pValue->enc);
61475      break;
61476    }
61477    default: {
61478      rc = sqlite3_bind_null(pStmt, i);
61479      break;
61480    }
61481  }
61482  return rc;
61483}
61484SQLITE_API int sqlite3_bind_zeroblob(sqlite3_stmt *pStmt, int i, int n){
61485  int rc;
61486  Vdbe *p = (Vdbe *)pStmt;
61487  rc = vdbeUnbind(p, i);
61488  if( rc==SQLITE_OK ){
61489    sqlite3VdbeMemSetZeroBlob(&p->aVar[i-1], n);
61490    sqlite3_mutex_leave(p->db->mutex);
61491  }
61492  return rc;
61493}
61494
61495/*
61496** Return the number of wildcards that can be potentially bound to.
61497** This routine is added to support DBD::SQLite.
61498*/
61499SQLITE_API int sqlite3_bind_parameter_count(sqlite3_stmt *pStmt){
61500  Vdbe *p = (Vdbe*)pStmt;
61501  return p ? p->nVar : 0;
61502}
61503
61504/*
61505** Create a mapping from variable numbers to variable names
61506** in the Vdbe.azVar[] array, if such a mapping does not already
61507** exist.
61508*/
61509static void createVarMap(Vdbe *p){
61510  if( !p->okVar ){
61511    int j;
61512    Op *pOp;
61513    sqlite3_mutex_enter(p->db->mutex);
61514    /* The race condition here is harmless.  If two threads call this
61515    ** routine on the same Vdbe at the same time, they both might end
61516    ** up initializing the Vdbe.azVar[] array.  That is a little extra
61517    ** work but it results in the same answer.
61518    */
61519    for(j=0, pOp=p->aOp; j<p->nOp; j++, pOp++){
61520      if( pOp->opcode==OP_Variable ){
61521        assert( pOp->p1>0 && pOp->p1<=p->nVar );
61522        p->azVar[pOp->p1-1] = pOp->p4.z;
61523      }
61524    }
61525    p->okVar = 1;
61526    sqlite3_mutex_leave(p->db->mutex);
61527  }
61528}
61529
61530/*
61531** Return the name of a wildcard parameter.  Return NULL if the index
61532** is out of range or if the wildcard is unnamed.
61533**
61534** The result is always UTF-8.
61535*/
61536SQLITE_API const char *sqlite3_bind_parameter_name(sqlite3_stmt *pStmt, int i){
61537  Vdbe *p = (Vdbe*)pStmt;
61538  if( p==0 || i<1 || i>p->nVar ){
61539    return 0;
61540  }
61541  createVarMap(p);
61542  return p->azVar[i-1];
61543}
61544
61545/*
61546** Given a wildcard parameter name, return the index of the variable
61547** with that name.  If there is no variable with the given name,
61548** return 0.
61549*/
61550SQLITE_PRIVATE int sqlite3VdbeParameterIndex(Vdbe *p, const char *zName, int nName){
61551  int i;
61552  if( p==0 ){
61553    return 0;
61554  }
61555  createVarMap(p);
61556  if( zName ){
61557    for(i=0; i<p->nVar; i++){
61558      const char *z = p->azVar[i];
61559      if( z && strncmp(z,zName,nName)==0 && z[nName]==0 ){
61560        return i+1;
61561      }
61562    }
61563  }
61564  return 0;
61565}
61566SQLITE_API int sqlite3_bind_parameter_index(sqlite3_stmt *pStmt, const char *zName){
61567  return sqlite3VdbeParameterIndex((Vdbe*)pStmt, zName, sqlite3Strlen30(zName));
61568}
61569
61570/*
61571** Transfer all bindings from the first statement over to the second.
61572*/
61573SQLITE_PRIVATE int sqlite3TransferBindings(sqlite3_stmt *pFromStmt, sqlite3_stmt *pToStmt){
61574  Vdbe *pFrom = (Vdbe*)pFromStmt;
61575  Vdbe *pTo = (Vdbe*)pToStmt;
61576  int i;
61577  assert( pTo->db==pFrom->db );
61578  assert( pTo->nVar==pFrom->nVar );
61579  sqlite3_mutex_enter(pTo->db->mutex);
61580  for(i=0; i<pFrom->nVar; i++){
61581    sqlite3VdbeMemMove(&pTo->aVar[i], &pFrom->aVar[i]);
61582  }
61583  sqlite3_mutex_leave(pTo->db->mutex);
61584  return SQLITE_OK;
61585}
61586
61587#ifndef SQLITE_OMIT_DEPRECATED
61588/*
61589** Deprecated external interface.  Internal/core SQLite code
61590** should call sqlite3TransferBindings.
61591**
61592** Is is misuse to call this routine with statements from different
61593** database connections.  But as this is a deprecated interface, we
61594** will not bother to check for that condition.
61595**
61596** If the two statements contain a different number of bindings, then
61597** an SQLITE_ERROR is returned.  Nothing else can go wrong, so otherwise
61598** SQLITE_OK is returned.
61599*/
61600SQLITE_API int sqlite3_transfer_bindings(sqlite3_stmt *pFromStmt, sqlite3_stmt *pToStmt){
61601  Vdbe *pFrom = (Vdbe*)pFromStmt;
61602  Vdbe *pTo = (Vdbe*)pToStmt;
61603  if( pFrom->nVar!=pTo->nVar ){
61604    return SQLITE_ERROR;
61605  }
61606  if( pTo->isPrepareV2 && pTo->expmask ){
61607    pTo->expired = 1;
61608  }
61609  if( pFrom->isPrepareV2 && pFrom->expmask ){
61610    pFrom->expired = 1;
61611  }
61612  return sqlite3TransferBindings(pFromStmt, pToStmt);
61613}
61614#endif
61615
61616/*
61617** Return the sqlite3* database handle to which the prepared statement given
61618** in the argument belongs.  This is the same database handle that was
61619** the first argument to the sqlite3_prepare() that was used to create
61620** the statement in the first place.
61621*/
61622SQLITE_API sqlite3 *sqlite3_db_handle(sqlite3_stmt *pStmt){
61623  return pStmt ? ((Vdbe*)pStmt)->db : 0;
61624}
61625
61626/*
61627** Return true if the prepared statement is guaranteed to not modify the
61628** database.
61629*/
61630SQLITE_API int sqlite3_stmt_readonly(sqlite3_stmt *pStmt){
61631  return pStmt ? ((Vdbe*)pStmt)->readOnly : 1;
61632}
61633
61634/*
61635** Return a pointer to the next prepared statement after pStmt associated
61636** with database connection pDb.  If pStmt is NULL, return the first
61637** prepared statement for the database connection.  Return NULL if there
61638** are no more.
61639*/
61640SQLITE_API sqlite3_stmt *sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt){
61641  sqlite3_stmt *pNext;
61642  sqlite3_mutex_enter(pDb->mutex);
61643  if( pStmt==0 ){
61644    pNext = (sqlite3_stmt*)pDb->pVdbe;
61645  }else{
61646    pNext = (sqlite3_stmt*)((Vdbe*)pStmt)->pNext;
61647  }
61648  sqlite3_mutex_leave(pDb->mutex);
61649  return pNext;
61650}
61651
61652/*
61653** Return the value of a status counter for a prepared statement
61654*/
61655SQLITE_API int sqlite3_stmt_status(sqlite3_stmt *pStmt, int op, int resetFlag){
61656  Vdbe *pVdbe = (Vdbe*)pStmt;
61657  int v = pVdbe->aCounter[op-1];
61658  if( resetFlag ) pVdbe->aCounter[op-1] = 0;
61659  return v;
61660}
61661
61662/************** End of vdbeapi.c *********************************************/
61663/************** Begin file vdbetrace.c ***************************************/
61664/*
61665** 2009 November 25
61666**
61667** The author disclaims copyright to this source code.  In place of
61668** a legal notice, here is a blessing:
61669**
61670**    May you do good and not evil.
61671**    May you find forgiveness for yourself and forgive others.
61672**    May you share freely, never taking more than you give.
61673**
61674*************************************************************************
61675**
61676** This file contains code used to insert the values of host parameters
61677** (aka "wildcards") into the SQL text output by sqlite3_trace().
61678*/
61679
61680#ifndef SQLITE_OMIT_TRACE
61681
61682/*
61683** zSql is a zero-terminated string of UTF-8 SQL text.  Return the number of
61684** bytes in this text up to but excluding the first character in
61685** a host parameter.  If the text contains no host parameters, return
61686** the total number of bytes in the text.
61687*/
61688static int findNextHostParameter(const char *zSql, int *pnToken){
61689  int tokenType;
61690  int nTotal = 0;
61691  int n;
61692
61693  *pnToken = 0;
61694  while( zSql[0] ){
61695    n = sqlite3GetToken((u8*)zSql, &tokenType);
61696    assert( n>0 && tokenType!=TK_ILLEGAL );
61697    if( tokenType==TK_VARIABLE ){
61698      *pnToken = n;
61699      break;
61700    }
61701    nTotal += n;
61702    zSql += n;
61703  }
61704  return nTotal;
61705}
61706
61707/*
61708** This function returns a pointer to a nul-terminated string in memory
61709** obtained from sqlite3DbMalloc(). If sqlite3.vdbeExecCnt is 1, then the
61710** string contains a copy of zRawSql but with host parameters expanded to
61711** their current bindings. Or, if sqlite3.vdbeExecCnt is greater than 1,
61712** then the returned string holds a copy of zRawSql with "-- " prepended
61713** to each line of text.
61714**
61715** The calling function is responsible for making sure the memory returned
61716** is eventually freed.
61717**
61718** ALGORITHM:  Scan the input string looking for host parameters in any of
61719** these forms:  ?, ?N, $A, @A, :A.  Take care to avoid text within
61720** string literals, quoted identifier names, and comments.  For text forms,
61721** the host parameter index is found by scanning the perpared
61722** statement for the corresponding OP_Variable opcode.  Once the host
61723** parameter index is known, locate the value in p->aVar[].  Then render
61724** the value as a literal in place of the host parameter name.
61725*/
61726SQLITE_PRIVATE char *sqlite3VdbeExpandSql(
61727  Vdbe *p,                 /* The prepared statement being evaluated */
61728  const char *zRawSql      /* Raw text of the SQL statement */
61729){
61730  sqlite3 *db;             /* The database connection */
61731  int idx = 0;             /* Index of a host parameter */
61732  int nextIndex = 1;       /* Index of next ? host parameter */
61733  int n;                   /* Length of a token prefix */
61734  int nToken;              /* Length of the parameter token */
61735  int i;                   /* Loop counter */
61736  Mem *pVar;               /* Value of a host parameter */
61737  StrAccum out;            /* Accumulate the output here */
61738  char zBase[100];         /* Initial working space */
61739
61740  db = p->db;
61741  sqlite3StrAccumInit(&out, zBase, sizeof(zBase),
61742                      db->aLimit[SQLITE_LIMIT_LENGTH]);
61743  out.db = db;
61744  if( db->vdbeExecCnt>1 ){
61745    while( *zRawSql ){
61746      const char *zStart = zRawSql;
61747      while( *(zRawSql++)!='\n' && *zRawSql );
61748      sqlite3StrAccumAppend(&out, "-- ", 3);
61749      sqlite3StrAccumAppend(&out, zStart, (int)(zRawSql-zStart));
61750    }
61751  }else{
61752    while( zRawSql[0] ){
61753      n = findNextHostParameter(zRawSql, &nToken);
61754      assert( n>0 );
61755      sqlite3StrAccumAppend(&out, zRawSql, n);
61756      zRawSql += n;
61757      assert( zRawSql[0] || nToken==0 );
61758      if( nToken==0 ) break;
61759      if( zRawSql[0]=='?' ){
61760        if( nToken>1 ){
61761          assert( sqlite3Isdigit(zRawSql[1]) );
61762          sqlite3GetInt32(&zRawSql[1], &idx);
61763        }else{
61764          idx = nextIndex;
61765        }
61766      }else{
61767        assert( zRawSql[0]==':' || zRawSql[0]=='$' || zRawSql[0]=='@' );
61768        testcase( zRawSql[0]==':' );
61769        testcase( zRawSql[0]=='$' );
61770        testcase( zRawSql[0]=='@' );
61771        idx = sqlite3VdbeParameterIndex(p, zRawSql, nToken);
61772        assert( idx>0 );
61773      }
61774      zRawSql += nToken;
61775      nextIndex = idx + 1;
61776      assert( idx>0 && idx<=p->nVar );
61777      pVar = &p->aVar[idx-1];
61778      if( pVar->flags & MEM_Null ){
61779        sqlite3StrAccumAppend(&out, "NULL", 4);
61780      }else if( pVar->flags & MEM_Int ){
61781        sqlite3XPrintf(&out, "%lld", pVar->u.i);
61782      }else if( pVar->flags & MEM_Real ){
61783        sqlite3XPrintf(&out, "%!.15g", pVar->r);
61784      }else if( pVar->flags & MEM_Str ){
61785#ifndef SQLITE_OMIT_UTF16
61786        u8 enc = ENC(db);
61787        if( enc!=SQLITE_UTF8 ){
61788          Mem utf8;
61789          memset(&utf8, 0, sizeof(utf8));
61790          utf8.db = db;
61791          sqlite3VdbeMemSetStr(&utf8, pVar->z, pVar->n, enc, SQLITE_STATIC);
61792          sqlite3VdbeChangeEncoding(&utf8, SQLITE_UTF8);
61793          sqlite3XPrintf(&out, "'%.*q'", utf8.n, utf8.z);
61794          sqlite3VdbeMemRelease(&utf8);
61795        }else
61796#endif
61797        {
61798          sqlite3XPrintf(&out, "'%.*q'", pVar->n, pVar->z);
61799        }
61800      }else if( pVar->flags & MEM_Zero ){
61801        sqlite3XPrintf(&out, "zeroblob(%d)", pVar->u.nZero);
61802      }else{
61803        assert( pVar->flags & MEM_Blob );
61804        sqlite3StrAccumAppend(&out, "x'", 2);
61805        for(i=0; i<pVar->n; i++){
61806          sqlite3XPrintf(&out, "%02x", pVar->z[i]&0xff);
61807        }
61808        sqlite3StrAccumAppend(&out, "'", 1);
61809      }
61810    }
61811  }
61812  return sqlite3StrAccumFinish(&out);
61813}
61814
61815#endif /* #ifndef SQLITE_OMIT_TRACE */
61816
61817/************** End of vdbetrace.c *******************************************/
61818/************** Begin file vdbe.c ********************************************/
61819/*
61820** 2001 September 15
61821**
61822** The author disclaims copyright to this source code.  In place of
61823** a legal notice, here is a blessing:
61824**
61825**    May you do good and not evil.
61826**    May you find forgiveness for yourself and forgive others.
61827**    May you share freely, never taking more than you give.
61828**
61829*************************************************************************
61830** The code in this file implements execution method of the
61831** Virtual Database Engine (VDBE).  A separate file ("vdbeaux.c")
61832** handles housekeeping details such as creating and deleting
61833** VDBE instances.  This file is solely interested in executing
61834** the VDBE program.
61835**
61836** In the external interface, an "sqlite3_stmt*" is an opaque pointer
61837** to a VDBE.
61838**
61839** The SQL parser generates a program which is then executed by
61840** the VDBE to do the work of the SQL statement.  VDBE programs are
61841** similar in form to assembly language.  The program consists of
61842** a linear sequence of operations.  Each operation has an opcode
61843** and 5 operands.  Operands P1, P2, and P3 are integers.  Operand P4
61844** is a null-terminated string.  Operand P5 is an unsigned character.
61845** Few opcodes use all 5 operands.
61846**
61847** Computation results are stored on a set of registers numbered beginning
61848** with 1 and going up to Vdbe.nMem.  Each register can store
61849** either an integer, a null-terminated string, a floating point
61850** number, or the SQL "NULL" value.  An implicit conversion from one
61851** type to the other occurs as necessary.
61852**
61853** Most of the code in this file is taken up by the sqlite3VdbeExec()
61854** function which does the work of interpreting a VDBE program.
61855** But other routines are also provided to help in building up
61856** a program instruction by instruction.
61857**
61858** Various scripts scan this source file in order to generate HTML
61859** documentation, headers files, or other derived files.  The formatting
61860** of the code in this file is, therefore, important.  See other comments
61861** in this file for details.  If in doubt, do not deviate from existing
61862** commenting and indentation practices when changing or adding code.
61863*/
61864
61865/*
61866** Invoke this macro on memory cells just prior to changing the
61867** value of the cell.  This macro verifies that shallow copies are
61868** not misused.
61869*/
61870#ifdef SQLITE_DEBUG
61871# define memAboutToChange(P,M) sqlite3VdbeMemPrepareToChange(P,M)
61872#else
61873# define memAboutToChange(P,M)
61874#endif
61875
61876/*
61877** The following global variable is incremented every time a cursor
61878** moves, either by the OP_SeekXX, OP_Next, or OP_Prev opcodes.  The test
61879** procedures use this information to make sure that indices are
61880** working correctly.  This variable has no function other than to
61881** help verify the correct operation of the library.
61882*/
61883#ifdef SQLITE_TEST
61884SQLITE_API int sqlite3_search_count = 0;
61885#endif
61886
61887/*
61888** When this global variable is positive, it gets decremented once before
61889** each instruction in the VDBE.  When reaches zero, the u1.isInterrupted
61890** field of the sqlite3 structure is set in order to simulate and interrupt.
61891**
61892** This facility is used for testing purposes only.  It does not function
61893** in an ordinary build.
61894*/
61895#ifdef SQLITE_TEST
61896SQLITE_API int sqlite3_interrupt_count = 0;
61897#endif
61898
61899/*
61900** The next global variable is incremented each type the OP_Sort opcode
61901** is executed.  The test procedures use this information to make sure that
61902** sorting is occurring or not occurring at appropriate times.   This variable
61903** has no function other than to help verify the correct operation of the
61904** library.
61905*/
61906#ifdef SQLITE_TEST
61907SQLITE_API int sqlite3_sort_count = 0;
61908#endif
61909
61910/*
61911** The next global variable records the size of the largest MEM_Blob
61912** or MEM_Str that has been used by a VDBE opcode.  The test procedures
61913** use this information to make sure that the zero-blob functionality
61914** is working correctly.   This variable has no function other than to
61915** help verify the correct operation of the library.
61916*/
61917#ifdef SQLITE_TEST
61918SQLITE_API int sqlite3_max_blobsize = 0;
61919static void updateMaxBlobsize(Mem *p){
61920  if( (p->flags & (MEM_Str|MEM_Blob))!=0 && p->n>sqlite3_max_blobsize ){
61921    sqlite3_max_blobsize = p->n;
61922  }
61923}
61924#endif
61925
61926/*
61927** The next global variable is incremented each type the OP_Found opcode
61928** is executed. This is used to test whether or not the foreign key
61929** operation implemented using OP_FkIsZero is working. This variable
61930** has no function other than to help verify the correct operation of the
61931** library.
61932*/
61933#ifdef SQLITE_TEST
61934SQLITE_API int sqlite3_found_count = 0;
61935#endif
61936
61937/*
61938** Test a register to see if it exceeds the current maximum blob size.
61939** If it does, record the new maximum blob size.
61940*/
61941#if defined(SQLITE_TEST) && !defined(SQLITE_OMIT_BUILTIN_TEST)
61942# define UPDATE_MAX_BLOBSIZE(P)  updateMaxBlobsize(P)
61943#else
61944# define UPDATE_MAX_BLOBSIZE(P)
61945#endif
61946
61947/*
61948** Convert the given register into a string if it isn't one
61949** already. Return non-zero if a malloc() fails.
61950*/
61951#define Stringify(P, enc) \
61952   if(((P)->flags&(MEM_Str|MEM_Blob))==0 && sqlite3VdbeMemStringify(P,enc)) \
61953     { goto no_mem; }
61954
61955/*
61956** An ephemeral string value (signified by the MEM_Ephem flag) contains
61957** a pointer to a dynamically allocated string where some other entity
61958** is responsible for deallocating that string.  Because the register
61959** does not control the string, it might be deleted without the register
61960** knowing it.
61961**
61962** This routine converts an ephemeral string into a dynamically allocated
61963** string that the register itself controls.  In other words, it
61964** converts an MEM_Ephem string into an MEM_Dyn string.
61965*/
61966#define Deephemeralize(P) \
61967   if( ((P)->flags&MEM_Ephem)!=0 \
61968       && sqlite3VdbeMemMakeWriteable(P) ){ goto no_mem;}
61969
61970/*
61971** Call sqlite3VdbeMemExpandBlob() on the supplied value (type Mem*)
61972** P if required.
61973*/
61974#define ExpandBlob(P) (((P)->flags&MEM_Zero)?sqlite3VdbeMemExpandBlob(P):0)
61975
61976/*
61977** Argument pMem points at a register that will be passed to a
61978** user-defined function or returned to the user as the result of a query.
61979** This routine sets the pMem->type variable used by the sqlite3_value_*()
61980** routines.
61981*/
61982SQLITE_PRIVATE void sqlite3VdbeMemStoreType(Mem *pMem){
61983  int flags = pMem->flags;
61984  if( flags & MEM_Null ){
61985    pMem->type = SQLITE_NULL;
61986  }
61987  else if( flags & MEM_Int ){
61988    pMem->type = SQLITE_INTEGER;
61989  }
61990  else if( flags & MEM_Real ){
61991    pMem->type = SQLITE_FLOAT;
61992  }
61993  else if( flags & MEM_Str ){
61994    pMem->type = SQLITE_TEXT;
61995  }else{
61996    pMem->type = SQLITE_BLOB;
61997  }
61998}
61999
62000/*
62001** Allocate VdbeCursor number iCur.  Return a pointer to it.  Return NULL
62002** if we run out of memory.
62003*/
62004static VdbeCursor *allocateCursor(
62005  Vdbe *p,              /* The virtual machine */
62006  int iCur,             /* Index of the new VdbeCursor */
62007  int nField,           /* Number of fields in the table or index */
62008  int iDb,              /* When database the cursor belongs to, or -1 */
62009  int isBtreeCursor     /* True for B-Tree.  False for pseudo-table or vtab */
62010){
62011  /* Find the memory cell that will be used to store the blob of memory
62012  ** required for this VdbeCursor structure. It is convenient to use a
62013  ** vdbe memory cell to manage the memory allocation required for a
62014  ** VdbeCursor structure for the following reasons:
62015  **
62016  **   * Sometimes cursor numbers are used for a couple of different
62017  **     purposes in a vdbe program. The different uses might require
62018  **     different sized allocations. Memory cells provide growable
62019  **     allocations.
62020  **
62021  **   * When using ENABLE_MEMORY_MANAGEMENT, memory cell buffers can
62022  **     be freed lazily via the sqlite3_release_memory() API. This
62023  **     minimizes the number of malloc calls made by the system.
62024  **
62025  ** Memory cells for cursors are allocated at the top of the address
62026  ** space. Memory cell (p->nMem) corresponds to cursor 0. Space for
62027  ** cursor 1 is managed by memory cell (p->nMem-1), etc.
62028  */
62029  Mem *pMem = &p->aMem[p->nMem-iCur];
62030
62031  int nByte;
62032  VdbeCursor *pCx = 0;
62033  nByte =
62034      ROUND8(sizeof(VdbeCursor)) +
62035      (isBtreeCursor?sqlite3BtreeCursorSize():0) +
62036      2*nField*sizeof(u32);
62037
62038  assert( iCur<p->nCursor );
62039  if( p->apCsr[iCur] ){
62040    sqlite3VdbeFreeCursor(p, p->apCsr[iCur]);
62041    p->apCsr[iCur] = 0;
62042  }
62043  if( SQLITE_OK==sqlite3VdbeMemGrow(pMem, nByte, 0) ){
62044    p->apCsr[iCur] = pCx = (VdbeCursor*)pMem->z;
62045    memset(pCx, 0, sizeof(VdbeCursor));
62046    pCx->iDb = iDb;
62047    pCx->nField = nField;
62048    if( nField ){
62049      pCx->aType = (u32 *)&pMem->z[ROUND8(sizeof(VdbeCursor))];
62050    }
62051    if( isBtreeCursor ){
62052      pCx->pCursor = (BtCursor*)
62053          &pMem->z[ROUND8(sizeof(VdbeCursor))+2*nField*sizeof(u32)];
62054      sqlite3BtreeCursorZero(pCx->pCursor);
62055    }
62056  }
62057  return pCx;
62058}
62059
62060/*
62061** Try to convert a value into a numeric representation if we can
62062** do so without loss of information.  In other words, if the string
62063** looks like a number, convert it into a number.  If it does not
62064** look like a number, leave it alone.
62065*/
62066static void applyNumericAffinity(Mem *pRec){
62067  if( (pRec->flags & (MEM_Real|MEM_Int))==0 ){
62068    double rValue;
62069    i64 iValue;
62070    u8 enc = pRec->enc;
62071    if( (pRec->flags&MEM_Str)==0 ) return;
62072    if( sqlite3AtoF(pRec->z, &rValue, pRec->n, enc)==0 ) return;
62073    if( 0==sqlite3Atoi64(pRec->z, &iValue, pRec->n, enc) ){
62074      pRec->u.i = iValue;
62075      pRec->flags |= MEM_Int;
62076    }else{
62077      pRec->r = rValue;
62078      pRec->flags |= MEM_Real;
62079    }
62080  }
62081}
62082
62083/*
62084** Processing is determine by the affinity parameter:
62085**
62086** SQLITE_AFF_INTEGER:
62087** SQLITE_AFF_REAL:
62088** SQLITE_AFF_NUMERIC:
62089**    Try to convert pRec to an integer representation or a
62090**    floating-point representation if an integer representation
62091**    is not possible.  Note that the integer representation is
62092**    always preferred, even if the affinity is REAL, because
62093**    an integer representation is more space efficient on disk.
62094**
62095** SQLITE_AFF_TEXT:
62096**    Convert pRec to a text representation.
62097**
62098** SQLITE_AFF_NONE:
62099**    No-op.  pRec is unchanged.
62100*/
62101static void applyAffinity(
62102  Mem *pRec,          /* The value to apply affinity to */
62103  char affinity,      /* The affinity to be applied */
62104  u8 enc              /* Use this text encoding */
62105){
62106  if( affinity==SQLITE_AFF_TEXT ){
62107    /* Only attempt the conversion to TEXT if there is an integer or real
62108    ** representation (blob and NULL do not get converted) but no string
62109    ** representation.
62110    */
62111    if( 0==(pRec->flags&MEM_Str) && (pRec->flags&(MEM_Real|MEM_Int)) ){
62112      sqlite3VdbeMemStringify(pRec, enc);
62113    }
62114    pRec->flags &= ~(MEM_Real|MEM_Int);
62115  }else if( affinity!=SQLITE_AFF_NONE ){
62116    assert( affinity==SQLITE_AFF_INTEGER || affinity==SQLITE_AFF_REAL
62117             || affinity==SQLITE_AFF_NUMERIC );
62118    applyNumericAffinity(pRec);
62119    if( pRec->flags & MEM_Real ){
62120      sqlite3VdbeIntegerAffinity(pRec);
62121    }
62122  }
62123}
62124
62125/*
62126** Try to convert the type of a function argument or a result column
62127** into a numeric representation.  Use either INTEGER or REAL whichever
62128** is appropriate.  But only do the conversion if it is possible without
62129** loss of information and return the revised type of the argument.
62130*/
62131SQLITE_API int sqlite3_value_numeric_type(sqlite3_value *pVal){
62132  Mem *pMem = (Mem*)pVal;
62133  if( pMem->type==SQLITE_TEXT ){
62134    applyNumericAffinity(pMem);
62135    sqlite3VdbeMemStoreType(pMem);
62136  }
62137  return pMem->type;
62138}
62139
62140/*
62141** Exported version of applyAffinity(). This one works on sqlite3_value*,
62142** not the internal Mem* type.
62143*/
62144SQLITE_PRIVATE void sqlite3ValueApplyAffinity(
62145  sqlite3_value *pVal,
62146  u8 affinity,
62147  u8 enc
62148){
62149  applyAffinity((Mem *)pVal, affinity, enc);
62150}
62151
62152#ifdef SQLITE_DEBUG
62153/*
62154** Write a nice string representation of the contents of cell pMem
62155** into buffer zBuf, length nBuf.
62156*/
62157SQLITE_PRIVATE void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf){
62158  char *zCsr = zBuf;
62159  int f = pMem->flags;
62160
62161  static const char *const encnames[] = {"(X)", "(8)", "(16LE)", "(16BE)"};
62162
62163  if( f&MEM_Blob ){
62164    int i;
62165    char c;
62166    if( f & MEM_Dyn ){
62167      c = 'z';
62168      assert( (f & (MEM_Static|MEM_Ephem))==0 );
62169    }else if( f & MEM_Static ){
62170      c = 't';
62171      assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
62172    }else if( f & MEM_Ephem ){
62173      c = 'e';
62174      assert( (f & (MEM_Static|MEM_Dyn))==0 );
62175    }else{
62176      c = 's';
62177    }
62178
62179    sqlite3_snprintf(100, zCsr, "%c", c);
62180    zCsr += sqlite3Strlen30(zCsr);
62181    sqlite3_snprintf(100, zCsr, "%d[", pMem->n);
62182    zCsr += sqlite3Strlen30(zCsr);
62183    for(i=0; i<16 && i<pMem->n; i++){
62184      sqlite3_snprintf(100, zCsr, "%02X", ((int)pMem->z[i] & 0xFF));
62185      zCsr += sqlite3Strlen30(zCsr);
62186    }
62187    for(i=0; i<16 && i<pMem->n; i++){
62188      char z = pMem->z[i];
62189      if( z<32 || z>126 ) *zCsr++ = '.';
62190      else *zCsr++ = z;
62191    }
62192
62193    sqlite3_snprintf(100, zCsr, "]%s", encnames[pMem->enc]);
62194    zCsr += sqlite3Strlen30(zCsr);
62195    if( f & MEM_Zero ){
62196      sqlite3_snprintf(100, zCsr,"+%dz",pMem->u.nZero);
62197      zCsr += sqlite3Strlen30(zCsr);
62198    }
62199    *zCsr = '\0';
62200  }else if( f & MEM_Str ){
62201    int j, k;
62202    zBuf[0] = ' ';
62203    if( f & MEM_Dyn ){
62204      zBuf[1] = 'z';
62205      assert( (f & (MEM_Static|MEM_Ephem))==0 );
62206    }else if( f & MEM_Static ){
62207      zBuf[1] = 't';
62208      assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
62209    }else if( f & MEM_Ephem ){
62210      zBuf[1] = 'e';
62211      assert( (f & (MEM_Static|MEM_Dyn))==0 );
62212    }else{
62213      zBuf[1] = 's';
62214    }
62215    k = 2;
62216    sqlite3_snprintf(100, &zBuf[k], "%d", pMem->n);
62217    k += sqlite3Strlen30(&zBuf[k]);
62218    zBuf[k++] = '[';
62219    for(j=0; j<15 && j<pMem->n; j++){
62220      u8 c = pMem->z[j];
62221      if( c>=0x20 && c<0x7f ){
62222        zBuf[k++] = c;
62223      }else{
62224        zBuf[k++] = '.';
62225      }
62226    }
62227    zBuf[k++] = ']';
62228    sqlite3_snprintf(100,&zBuf[k], encnames[pMem->enc]);
62229    k += sqlite3Strlen30(&zBuf[k]);
62230    zBuf[k++] = 0;
62231  }
62232}
62233#endif
62234
62235#ifdef SQLITE_DEBUG
62236/*
62237** Print the value of a register for tracing purposes:
62238*/
62239static void memTracePrint(FILE *out, Mem *p){
62240  if( p->flags & MEM_Null ){
62241    fprintf(out, " NULL");
62242  }else if( (p->flags & (MEM_Int|MEM_Str))==(MEM_Int|MEM_Str) ){
62243    fprintf(out, " si:%lld", p->u.i);
62244  }else if( p->flags & MEM_Int ){
62245    fprintf(out, " i:%lld", p->u.i);
62246#ifndef SQLITE_OMIT_FLOATING_POINT
62247  }else if( p->flags & MEM_Real ){
62248    fprintf(out, " r:%g", p->r);
62249#endif
62250  }else if( p->flags & MEM_RowSet ){
62251    fprintf(out, " (rowset)");
62252  }else{
62253    char zBuf[200];
62254    sqlite3VdbeMemPrettyPrint(p, zBuf);
62255    fprintf(out, " ");
62256    fprintf(out, "%s", zBuf);
62257  }
62258}
62259static void registerTrace(FILE *out, int iReg, Mem *p){
62260  fprintf(out, "REG[%d] = ", iReg);
62261  memTracePrint(out, p);
62262  fprintf(out, "\n");
62263}
62264#endif
62265
62266#ifdef SQLITE_DEBUG
62267#  define REGISTER_TRACE(R,M) if(p->trace)registerTrace(p->trace,R,M)
62268#else
62269#  define REGISTER_TRACE(R,M)
62270#endif
62271
62272
62273#ifdef VDBE_PROFILE
62274
62275/*
62276** hwtime.h contains inline assembler code for implementing
62277** high-performance timing routines.
62278*/
62279/************** Include hwtime.h in the middle of vdbe.c *********************/
62280/************** Begin file hwtime.h ******************************************/
62281/*
62282** 2008 May 27
62283**
62284** The author disclaims copyright to this source code.  In place of
62285** a legal notice, here is a blessing:
62286**
62287**    May you do good and not evil.
62288**    May you find forgiveness for yourself and forgive others.
62289**    May you share freely, never taking more than you give.
62290**
62291******************************************************************************
62292**
62293** This file contains inline asm code for retrieving "high-performance"
62294** counters for x86 class CPUs.
62295*/
62296#ifndef _HWTIME_H_
62297#define _HWTIME_H_
62298
62299/*
62300** The following routine only works on pentium-class (or newer) processors.
62301** It uses the RDTSC opcode to read the cycle count value out of the
62302** processor and returns that value.  This can be used for high-res
62303** profiling.
62304*/
62305#if (defined(__GNUC__) || defined(_MSC_VER)) && \
62306      (defined(i386) || defined(__i386__) || defined(_M_IX86))
62307
62308  #if defined(__GNUC__)
62309
62310  __inline__ sqlite_uint64 sqlite3Hwtime(void){
62311     unsigned int lo, hi;
62312     __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
62313     return (sqlite_uint64)hi << 32 | lo;
62314  }
62315
62316  #elif defined(_MSC_VER)
62317
62318  __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
62319     __asm {
62320        rdtsc
62321        ret       ; return value at EDX:EAX
62322     }
62323  }
62324
62325  #endif
62326
62327#elif (defined(__GNUC__) && defined(__x86_64__))
62328
62329  __inline__ sqlite_uint64 sqlite3Hwtime(void){
62330      unsigned long val;
62331      __asm__ __volatile__ ("rdtsc" : "=A" (val));
62332      return val;
62333  }
62334
62335#elif (defined(__GNUC__) && defined(__ppc__))
62336
62337  __inline__ sqlite_uint64 sqlite3Hwtime(void){
62338      unsigned long long retval;
62339      unsigned long junk;
62340      __asm__ __volatile__ ("\n\
62341          1:      mftbu   %1\n\
62342                  mftb    %L0\n\
62343                  mftbu   %0\n\
62344                  cmpw    %0,%1\n\
62345                  bne     1b"
62346                  : "=r" (retval), "=r" (junk));
62347      return retval;
62348  }
62349
62350#else
62351
62352  #error Need implementation of sqlite3Hwtime() for your platform.
62353
62354  /*
62355  ** To compile without implementing sqlite3Hwtime() for your platform,
62356  ** you can remove the above #error and use the following
62357  ** stub function.  You will lose timing support for many
62358  ** of the debugging and testing utilities, but it should at
62359  ** least compile and run.
62360  */
62361SQLITE_PRIVATE   sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
62362
62363#endif
62364
62365#endif /* !defined(_HWTIME_H_) */
62366
62367/************** End of hwtime.h **********************************************/
62368/************** Continuing where we left off in vdbe.c ***********************/
62369
62370#endif
62371
62372/*
62373** The CHECK_FOR_INTERRUPT macro defined here looks to see if the
62374** sqlite3_interrupt() routine has been called.  If it has been, then
62375** processing of the VDBE program is interrupted.
62376**
62377** This macro added to every instruction that does a jump in order to
62378** implement a loop.  This test used to be on every single instruction,
62379** but that meant we more testing that we needed.  By only testing the
62380** flag on jump instructions, we get a (small) speed improvement.
62381*/
62382#define CHECK_FOR_INTERRUPT \
62383   if( db->u1.isInterrupted ) goto abort_due_to_interrupt;
62384
62385
62386#ifndef NDEBUG
62387/*
62388** This function is only called from within an assert() expression. It
62389** checks that the sqlite3.nTransaction variable is correctly set to
62390** the number of non-transaction savepoints currently in the
62391** linked list starting at sqlite3.pSavepoint.
62392**
62393** Usage:
62394**
62395**     assert( checkSavepointCount(db) );
62396*/
62397static int checkSavepointCount(sqlite3 *db){
62398  int n = 0;
62399  Savepoint *p;
62400  for(p=db->pSavepoint; p; p=p->pNext) n++;
62401  assert( n==(db->nSavepoint + db->isTransactionSavepoint) );
62402  return 1;
62403}
62404#endif
62405
62406/*
62407** Transfer error message text from an sqlite3_vtab.zErrMsg (text stored
62408** in memory obtained from sqlite3_malloc) into a Vdbe.zErrMsg (text stored
62409** in memory obtained from sqlite3DbMalloc).
62410*/
62411static void importVtabErrMsg(Vdbe *p, sqlite3_vtab *pVtab){
62412  sqlite3 *db = p->db;
62413  sqlite3DbFree(db, p->zErrMsg);
62414  p->zErrMsg = sqlite3DbStrDup(db, pVtab->zErrMsg);
62415  sqlite3_free(pVtab->zErrMsg);
62416  pVtab->zErrMsg = 0;
62417}
62418
62419
62420/*
62421** Execute as much of a VDBE program as we can then return.
62422**
62423** sqlite3VdbeMakeReady() must be called before this routine in order to
62424** close the program with a final OP_Halt and to set up the callbacks
62425** and the error message pointer.
62426**
62427** Whenever a row or result data is available, this routine will either
62428** invoke the result callback (if there is one) or return with
62429** SQLITE_ROW.
62430**
62431** If an attempt is made to open a locked database, then this routine
62432** will either invoke the busy callback (if there is one) or it will
62433** return SQLITE_BUSY.
62434**
62435** If an error occurs, an error message is written to memory obtained
62436** from sqlite3_malloc() and p->zErrMsg is made to point to that memory.
62437** The error code is stored in p->rc and this routine returns SQLITE_ERROR.
62438**
62439** If the callback ever returns non-zero, then the program exits
62440** immediately.  There will be no error message but the p->rc field is
62441** set to SQLITE_ABORT and this routine will return SQLITE_ERROR.
62442**
62443** A memory allocation error causes p->rc to be set to SQLITE_NOMEM and this
62444** routine to return SQLITE_ERROR.
62445**
62446** Other fatal errors return SQLITE_ERROR.
62447**
62448** After this routine has finished, sqlite3VdbeFinalize() should be
62449** used to clean up the mess that was left behind.
62450*/
62451SQLITE_PRIVATE int sqlite3VdbeExec(
62452  Vdbe *p                    /* The VDBE */
62453){
62454  int pc=0;                  /* The program counter */
62455  Op *aOp = p->aOp;          /* Copy of p->aOp */
62456  Op *pOp;                   /* Current operation */
62457  int rc = SQLITE_OK;        /* Value to return */
62458  sqlite3 *db = p->db;       /* The database */
62459  u8 resetSchemaOnFault = 0; /* Reset schema after an error if positive */
62460  u8 encoding = ENC(db);     /* The database encoding */
62461#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
62462  int checkProgress;         /* True if progress callbacks are enabled */
62463  int nProgressOps = 0;      /* Opcodes executed since progress callback. */
62464#endif
62465  Mem *aMem = p->aMem;       /* Copy of p->aMem */
62466  Mem *pIn1 = 0;             /* 1st input operand */
62467  Mem *pIn2 = 0;             /* 2nd input operand */
62468  Mem *pIn3 = 0;             /* 3rd input operand */
62469  Mem *pOut = 0;             /* Output operand */
62470  int iCompare = 0;          /* Result of last OP_Compare operation */
62471  int *aPermute = 0;         /* Permutation of columns for OP_Compare */
62472#ifdef VDBE_PROFILE
62473  u64 start;                 /* CPU clock count at start of opcode */
62474  int origPc;                /* Program counter at start of opcode */
62475#endif
62476  /********************************************************************
62477  ** Automatically generated code
62478  **
62479  ** The following union is automatically generated by the
62480  ** vdbe-compress.tcl script.  The purpose of this union is to
62481  ** reduce the amount of stack space required by this function.
62482  ** See comments in the vdbe-compress.tcl script for details.
62483  */
62484  union vdbeExecUnion {
62485    struct OP_Yield_stack_vars {
62486      int pcDest;
62487    } aa;
62488    struct OP_Variable_stack_vars {
62489      Mem *pVar;       /* Value being transferred */
62490    } ab;
62491    struct OP_Move_stack_vars {
62492      char *zMalloc;   /* Holding variable for allocated memory */
62493      int n;           /* Number of registers left to copy */
62494      int p1;          /* Register to copy from */
62495      int p2;          /* Register to copy to */
62496    } ac;
62497    struct OP_ResultRow_stack_vars {
62498      Mem *pMem;
62499      int i;
62500    } ad;
62501    struct OP_Concat_stack_vars {
62502      i64 nByte;
62503    } ae;
62504    struct OP_Remainder_stack_vars {
62505      int flags;      /* Combined MEM_* flags from both inputs */
62506      i64 iA;         /* Integer value of left operand */
62507      i64 iB;         /* Integer value of right operand */
62508      double rA;      /* Real value of left operand */
62509      double rB;      /* Real value of right operand */
62510    } af;
62511    struct OP_Function_stack_vars {
62512      int i;
62513      Mem *pArg;
62514      sqlite3_context ctx;
62515      sqlite3_value **apVal;
62516      int n;
62517    } ag;
62518    struct OP_ShiftRight_stack_vars {
62519      i64 iA;
62520      u64 uA;
62521      i64 iB;
62522      u8 op;
62523    } ah;
62524    struct OP_Ge_stack_vars {
62525      int res;            /* Result of the comparison of pIn1 against pIn3 */
62526      char affinity;      /* Affinity to use for comparison */
62527      u16 flags1;         /* Copy of initial value of pIn1->flags */
62528      u16 flags3;         /* Copy of initial value of pIn3->flags */
62529    } ai;
62530    struct OP_Compare_stack_vars {
62531      int n;
62532      int i;
62533      int p1;
62534      int p2;
62535      const KeyInfo *pKeyInfo;
62536      int idx;
62537      CollSeq *pColl;    /* Collating sequence to use on this term */
62538      int bRev;          /* True for DESCENDING sort order */
62539    } aj;
62540    struct OP_Or_stack_vars {
62541      int v1;    /* Left operand:  0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
62542      int v2;    /* Right operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
62543    } ak;
62544    struct OP_IfNot_stack_vars {
62545      int c;
62546    } al;
62547    struct OP_Column_stack_vars {
62548      u32 payloadSize;   /* Number of bytes in the record */
62549      i64 payloadSize64; /* Number of bytes in the record */
62550      int p1;            /* P1 value of the opcode */
62551      int p2;            /* column number to retrieve */
62552      VdbeCursor *pC;    /* The VDBE cursor */
62553      char *zRec;        /* Pointer to complete record-data */
62554      BtCursor *pCrsr;   /* The BTree cursor */
62555      u32 *aType;        /* aType[i] holds the numeric type of the i-th column */
62556      u32 *aOffset;      /* aOffset[i] is offset to start of data for i-th column */
62557      int nField;        /* number of fields in the record */
62558      int len;           /* The length of the serialized data for the column */
62559      int i;             /* Loop counter */
62560      char *zData;       /* Part of the record being decoded */
62561      Mem *pDest;        /* Where to write the extracted value */
62562      Mem sMem;          /* For storing the record being decoded */
62563      u8 *zIdx;          /* Index into header */
62564      u8 *zEndHdr;       /* Pointer to first byte after the header */
62565      u32 offset;        /* Offset into the data */
62566      u32 szField;       /* Number of bytes in the content of a field */
62567      int szHdr;         /* Size of the header size field at start of record */
62568      int avail;         /* Number of bytes of available data */
62569      Mem *pReg;         /* PseudoTable input register */
62570    } am;
62571    struct OP_Affinity_stack_vars {
62572      const char *zAffinity;   /* The affinity to be applied */
62573      char cAff;               /* A single character of affinity */
62574    } an;
62575    struct OP_MakeRecord_stack_vars {
62576      u8 *zNewRecord;        /* A buffer to hold the data for the new record */
62577      Mem *pRec;             /* The new record */
62578      u64 nData;             /* Number of bytes of data space */
62579      int nHdr;              /* Number of bytes of header space */
62580      i64 nByte;             /* Data space required for this record */
62581      int nZero;             /* Number of zero bytes at the end of the record */
62582      int nVarint;           /* Number of bytes in a varint */
62583      u32 serial_type;       /* Type field */
62584      Mem *pData0;           /* First field to be combined into the record */
62585      Mem *pLast;            /* Last field of the record */
62586      int nField;            /* Number of fields in the record */
62587      char *zAffinity;       /* The affinity string for the record */
62588      int file_format;       /* File format to use for encoding */
62589      int i;                 /* Space used in zNewRecord[] */
62590      int len;               /* Length of a field */
62591    } ao;
62592    struct OP_Count_stack_vars {
62593      i64 nEntry;
62594      BtCursor *pCrsr;
62595    } ap;
62596    struct OP_Savepoint_stack_vars {
62597      int p1;                         /* Value of P1 operand */
62598      char *zName;                    /* Name of savepoint */
62599      int nName;
62600      Savepoint *pNew;
62601      Savepoint *pSavepoint;
62602      Savepoint *pTmp;
62603      int iSavepoint;
62604      int ii;
62605    } aq;
62606    struct OP_AutoCommit_stack_vars {
62607      int desiredAutoCommit;
62608      int iRollback;
62609      int turnOnAC;
62610    } ar;
62611    struct OP_Transaction_stack_vars {
62612      Btree *pBt;
62613    } as;
62614    struct OP_ReadCookie_stack_vars {
62615      int iMeta;
62616      int iDb;
62617      int iCookie;
62618    } at;
62619    struct OP_SetCookie_stack_vars {
62620      Db *pDb;
62621    } au;
62622    struct OP_VerifyCookie_stack_vars {
62623      int iMeta;
62624      int iGen;
62625      Btree *pBt;
62626    } av;
62627    struct OP_OpenWrite_stack_vars {
62628      int nField;
62629      KeyInfo *pKeyInfo;
62630      int p2;
62631      int iDb;
62632      int wrFlag;
62633      Btree *pX;
62634      VdbeCursor *pCur;
62635      Db *pDb;
62636    } aw;
62637    struct OP_OpenEphemeral_stack_vars {
62638      VdbeCursor *pCx;
62639    } ax;
62640    struct OP_OpenPseudo_stack_vars {
62641      VdbeCursor *pCx;
62642    } ay;
62643    struct OP_SeekGt_stack_vars {
62644      int res;
62645      int oc;
62646      VdbeCursor *pC;
62647      UnpackedRecord r;
62648      int nField;
62649      i64 iKey;      /* The rowid we are to seek to */
62650    } az;
62651    struct OP_Seek_stack_vars {
62652      VdbeCursor *pC;
62653    } ba;
62654    struct OP_Found_stack_vars {
62655      int alreadyExists;
62656      VdbeCursor *pC;
62657      int res;
62658      UnpackedRecord *pIdxKey;
62659      UnpackedRecord r;
62660      char aTempRec[ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*3 + 7];
62661    } bb;
62662    struct OP_IsUnique_stack_vars {
62663      u16 ii;
62664      VdbeCursor *pCx;
62665      BtCursor *pCrsr;
62666      u16 nField;
62667      Mem *aMx;
62668      UnpackedRecord r;                  /* B-Tree index search key */
62669      i64 R;                             /* Rowid stored in register P3 */
62670    } bc;
62671    struct OP_NotExists_stack_vars {
62672      VdbeCursor *pC;
62673      BtCursor *pCrsr;
62674      int res;
62675      u64 iKey;
62676    } bd;
62677    struct OP_NewRowid_stack_vars {
62678      i64 v;                 /* The new rowid */
62679      VdbeCursor *pC;        /* Cursor of table to get the new rowid */
62680      int res;               /* Result of an sqlite3BtreeLast() */
62681      int cnt;               /* Counter to limit the number of searches */
62682      Mem *pMem;             /* Register holding largest rowid for AUTOINCREMENT */
62683      VdbeFrame *pFrame;     /* Root frame of VDBE */
62684    } be;
62685    struct OP_InsertInt_stack_vars {
62686      Mem *pData;       /* MEM cell holding data for the record to be inserted */
62687      Mem *pKey;        /* MEM cell holding key  for the record */
62688      i64 iKey;         /* The integer ROWID or key for the record to be inserted */
62689      VdbeCursor *pC;   /* Cursor to table into which insert is written */
62690      int nZero;        /* Number of zero-bytes to append */
62691      int seekResult;   /* Result of prior seek or 0 if no USESEEKRESULT flag */
62692      const char *zDb;  /* database name - used by the update hook */
62693      const char *zTbl; /* Table name - used by the opdate hook */
62694      int op;           /* Opcode for update hook: SQLITE_UPDATE or SQLITE_INSERT */
62695    } bf;
62696    struct OP_Delete_stack_vars {
62697      i64 iKey;
62698      VdbeCursor *pC;
62699    } bg;
62700    struct OP_RowData_stack_vars {
62701      VdbeCursor *pC;
62702      BtCursor *pCrsr;
62703      u32 n;
62704      i64 n64;
62705    } bh;
62706    struct OP_Rowid_stack_vars {
62707      VdbeCursor *pC;
62708      i64 v;
62709      sqlite3_vtab *pVtab;
62710      const sqlite3_module *pModule;
62711    } bi;
62712    struct OP_NullRow_stack_vars {
62713      VdbeCursor *pC;
62714    } bj;
62715    struct OP_Last_stack_vars {
62716      VdbeCursor *pC;
62717      BtCursor *pCrsr;
62718      int res;
62719    } bk;
62720    struct OP_Rewind_stack_vars {
62721      VdbeCursor *pC;
62722      BtCursor *pCrsr;
62723      int res;
62724    } bl;
62725    struct OP_Next_stack_vars {
62726      VdbeCursor *pC;
62727      BtCursor *pCrsr;
62728      int res;
62729    } bm;
62730    struct OP_IdxInsert_stack_vars {
62731      VdbeCursor *pC;
62732      BtCursor *pCrsr;
62733      int nKey;
62734      const char *zKey;
62735    } bn;
62736    struct OP_IdxDelete_stack_vars {
62737      VdbeCursor *pC;
62738      BtCursor *pCrsr;
62739      int res;
62740      UnpackedRecord r;
62741    } bo;
62742    struct OP_IdxRowid_stack_vars {
62743      BtCursor *pCrsr;
62744      VdbeCursor *pC;
62745      i64 rowid;
62746    } bp;
62747    struct OP_IdxGE_stack_vars {
62748      VdbeCursor *pC;
62749      int res;
62750      UnpackedRecord r;
62751    } bq;
62752    struct OP_Destroy_stack_vars {
62753      int iMoved;
62754      int iCnt;
62755      Vdbe *pVdbe;
62756      int iDb;
62757    } br;
62758    struct OP_Clear_stack_vars {
62759      int nChange;
62760    } bs;
62761    struct OP_CreateTable_stack_vars {
62762      int pgno;
62763      int flags;
62764      Db *pDb;
62765    } bt;
62766    struct OP_ParseSchema_stack_vars {
62767      int iDb;
62768      const char *zMaster;
62769      char *zSql;
62770      InitData initData;
62771    } bu;
62772    struct OP_IntegrityCk_stack_vars {
62773      int nRoot;      /* Number of tables to check.  (Number of root pages.) */
62774      int *aRoot;     /* Array of rootpage numbers for tables to be checked */
62775      int j;          /* Loop counter */
62776      int nErr;       /* Number of errors reported */
62777      char *z;        /* Text of the error report */
62778      Mem *pnErr;     /* Register keeping track of errors remaining */
62779    } bv;
62780    struct OP_RowSetRead_stack_vars {
62781      i64 val;
62782    } bw;
62783    struct OP_RowSetTest_stack_vars {
62784      int iSet;
62785      int exists;
62786    } bx;
62787    struct OP_Program_stack_vars {
62788      int nMem;               /* Number of memory registers for sub-program */
62789      int nByte;              /* Bytes of runtime space required for sub-program */
62790      Mem *pRt;               /* Register to allocate runtime space */
62791      Mem *pMem;              /* Used to iterate through memory cells */
62792      Mem *pEnd;              /* Last memory cell in new array */
62793      VdbeFrame *pFrame;      /* New vdbe frame to execute in */
62794      SubProgram *pProgram;   /* Sub-program to execute */
62795      void *t;                /* Token identifying trigger */
62796    } by;
62797    struct OP_Param_stack_vars {
62798      VdbeFrame *pFrame;
62799      Mem *pIn;
62800    } bz;
62801    struct OP_MemMax_stack_vars {
62802      Mem *pIn1;
62803      VdbeFrame *pFrame;
62804    } ca;
62805    struct OP_AggStep_stack_vars {
62806      int n;
62807      int i;
62808      Mem *pMem;
62809      Mem *pRec;
62810      sqlite3_context ctx;
62811      sqlite3_value **apVal;
62812    } cb;
62813    struct OP_AggFinal_stack_vars {
62814      Mem *pMem;
62815    } cc;
62816    struct OP_Checkpoint_stack_vars {
62817      int i;                          /* Loop counter */
62818      int aRes[3];                    /* Results */
62819      Mem *pMem;                      /* Write results here */
62820    } cd;
62821    struct OP_JournalMode_stack_vars {
62822      Btree *pBt;                     /* Btree to change journal mode of */
62823      Pager *pPager;                  /* Pager associated with pBt */
62824      int eNew;                       /* New journal mode */
62825      int eOld;                       /* The old journal mode */
62826      const char *zFilename;          /* Name of database file for pPager */
62827    } ce;
62828    struct OP_IncrVacuum_stack_vars {
62829      Btree *pBt;
62830    } cf;
62831    struct OP_VBegin_stack_vars {
62832      VTable *pVTab;
62833    } cg;
62834    struct OP_VOpen_stack_vars {
62835      VdbeCursor *pCur;
62836      sqlite3_vtab_cursor *pVtabCursor;
62837      sqlite3_vtab *pVtab;
62838      sqlite3_module *pModule;
62839    } ch;
62840    struct OP_VFilter_stack_vars {
62841      int nArg;
62842      int iQuery;
62843      const sqlite3_module *pModule;
62844      Mem *pQuery;
62845      Mem *pArgc;
62846      sqlite3_vtab_cursor *pVtabCursor;
62847      sqlite3_vtab *pVtab;
62848      VdbeCursor *pCur;
62849      int res;
62850      int i;
62851      Mem **apArg;
62852    } ci;
62853    struct OP_VColumn_stack_vars {
62854      sqlite3_vtab *pVtab;
62855      const sqlite3_module *pModule;
62856      Mem *pDest;
62857      sqlite3_context sContext;
62858    } cj;
62859    struct OP_VNext_stack_vars {
62860      sqlite3_vtab *pVtab;
62861      const sqlite3_module *pModule;
62862      int res;
62863      VdbeCursor *pCur;
62864    } ck;
62865    struct OP_VRename_stack_vars {
62866      sqlite3_vtab *pVtab;
62867      Mem *pName;
62868    } cl;
62869    struct OP_VUpdate_stack_vars {
62870      sqlite3_vtab *pVtab;
62871      sqlite3_module *pModule;
62872      int nArg;
62873      int i;
62874      sqlite_int64 rowid;
62875      Mem **apArg;
62876      Mem *pX;
62877    } cm;
62878    struct OP_Trace_stack_vars {
62879      char *zTrace;
62880    } cn;
62881  } u;
62882  /* End automatically generated code
62883  ********************************************************************/
62884
62885  assert( p->magic==VDBE_MAGIC_RUN );  /* sqlite3_step() verifies this */
62886  sqlite3VdbeEnter(p);
62887  if( p->rc==SQLITE_NOMEM ){
62888    /* This happens if a malloc() inside a call to sqlite3_column_text() or
62889    ** sqlite3_column_text16() failed.  */
62890    goto no_mem;
62891  }
62892  assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY );
62893  p->rc = SQLITE_OK;
62894  assert( p->explain==0 );
62895  p->pResultSet = 0;
62896  db->busyHandler.nBusy = 0;
62897  CHECK_FOR_INTERRUPT;
62898  sqlite3VdbeIOTraceSql(p);
62899#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
62900  checkProgress = db->xProgress!=0;
62901#endif
62902#ifdef SQLITE_DEBUG
62903  sqlite3BeginBenignMalloc();
62904  if( p->pc==0  && (p->db->flags & SQLITE_VdbeListing)!=0 ){
62905    int i;
62906    printf("VDBE Program Listing:\n");
62907    sqlite3VdbePrintSql(p);
62908    for(i=0; i<p->nOp; i++){
62909      sqlite3VdbePrintOp(stdout, i, &aOp[i]);
62910    }
62911  }
62912  sqlite3EndBenignMalloc();
62913#endif
62914  for(pc=p->pc; rc==SQLITE_OK; pc++){
62915    assert( pc>=0 && pc<p->nOp );
62916    if( db->mallocFailed ) goto no_mem;
62917#ifdef VDBE_PROFILE
62918    origPc = pc;
62919    start = sqlite3Hwtime();
62920#endif
62921    pOp = &aOp[pc];
62922
62923    /* Only allow tracing if SQLITE_DEBUG is defined.
62924    */
62925#ifdef SQLITE_DEBUG
62926    if( p->trace ){
62927      if( pc==0 ){
62928        printf("VDBE Execution Trace:\n");
62929        sqlite3VdbePrintSql(p);
62930      }
62931      sqlite3VdbePrintOp(p->trace, pc, pOp);
62932    }
62933#endif
62934
62935
62936    /* Check to see if we need to simulate an interrupt.  This only happens
62937    ** if we have a special test build.
62938    */
62939#ifdef SQLITE_TEST
62940    if( sqlite3_interrupt_count>0 ){
62941      sqlite3_interrupt_count--;
62942      if( sqlite3_interrupt_count==0 ){
62943        sqlite3_interrupt(db);
62944      }
62945    }
62946#endif
62947
62948#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
62949    /* Call the progress callback if it is configured and the required number
62950    ** of VDBE ops have been executed (either since this invocation of
62951    ** sqlite3VdbeExec() or since last time the progress callback was called).
62952    ** If the progress callback returns non-zero, exit the virtual machine with
62953    ** a return code SQLITE_ABORT.
62954    */
62955    if( checkProgress ){
62956      if( db->nProgressOps==nProgressOps ){
62957        int prc;
62958        prc = db->xProgress(db->pProgressArg);
62959        if( prc!=0 ){
62960          rc = SQLITE_INTERRUPT;
62961          goto vdbe_error_halt;
62962        }
62963        nProgressOps = 0;
62964      }
62965      nProgressOps++;
62966    }
62967#endif
62968
62969    /* On any opcode with the "out2-prerelase" tag, free any
62970    ** external allocations out of mem[p2] and set mem[p2] to be
62971    ** an undefined integer.  Opcodes will either fill in the integer
62972    ** value or convert mem[p2] to a different type.
62973    */
62974    assert( pOp->opflags==sqlite3OpcodeProperty[pOp->opcode] );
62975    if( pOp->opflags & OPFLG_OUT2_PRERELEASE ){
62976      assert( pOp->p2>0 );
62977      assert( pOp->p2<=p->nMem );
62978      pOut = &aMem[pOp->p2];
62979      memAboutToChange(p, pOut);
62980      sqlite3VdbeMemReleaseExternal(pOut);
62981      pOut->flags = MEM_Int;
62982    }
62983
62984    /* Sanity checking on other operands */
62985#ifdef SQLITE_DEBUG
62986    if( (pOp->opflags & OPFLG_IN1)!=0 ){
62987      assert( pOp->p1>0 );
62988      assert( pOp->p1<=p->nMem );
62989      assert( memIsValid(&aMem[pOp->p1]) );
62990      REGISTER_TRACE(pOp->p1, &aMem[pOp->p1]);
62991    }
62992    if( (pOp->opflags & OPFLG_IN2)!=0 ){
62993      assert( pOp->p2>0 );
62994      assert( pOp->p2<=p->nMem );
62995      assert( memIsValid(&aMem[pOp->p2]) );
62996      REGISTER_TRACE(pOp->p2, &aMem[pOp->p2]);
62997    }
62998    if( (pOp->opflags & OPFLG_IN3)!=0 ){
62999      assert( pOp->p3>0 );
63000      assert( pOp->p3<=p->nMem );
63001      assert( memIsValid(&aMem[pOp->p3]) );
63002      REGISTER_TRACE(pOp->p3, &aMem[pOp->p3]);
63003    }
63004    if( (pOp->opflags & OPFLG_OUT2)!=0 ){
63005      assert( pOp->p2>0 );
63006      assert( pOp->p2<=p->nMem );
63007      memAboutToChange(p, &aMem[pOp->p2]);
63008    }
63009    if( (pOp->opflags & OPFLG_OUT3)!=0 ){
63010      assert( pOp->p3>0 );
63011      assert( pOp->p3<=p->nMem );
63012      memAboutToChange(p, &aMem[pOp->p3]);
63013    }
63014#endif
63015
63016    switch( pOp->opcode ){
63017
63018/*****************************************************************************
63019** What follows is a massive switch statement where each case implements a
63020** separate instruction in the virtual machine.  If we follow the usual
63021** indentation conventions, each case should be indented by 6 spaces.  But
63022** that is a lot of wasted space on the left margin.  So the code within
63023** the switch statement will break with convention and be flush-left. Another
63024** big comment (similar to this one) will mark the point in the code where
63025** we transition back to normal indentation.
63026**
63027** The formatting of each case is important.  The makefile for SQLite
63028** generates two C files "opcodes.h" and "opcodes.c" by scanning this
63029** file looking for lines that begin with "case OP_".  The opcodes.h files
63030** will be filled with #defines that give unique integer values to each
63031** opcode and the opcodes.c file is filled with an array of strings where
63032** each string is the symbolic name for the corresponding opcode.  If the
63033** case statement is followed by a comment of the form "/# same as ... #/"
63034** that comment is used to determine the particular value of the opcode.
63035**
63036** Other keywords in the comment that follows each case are used to
63037** construct the OPFLG_INITIALIZER value that initializes opcodeProperty[].
63038** Keywords include: in1, in2, in3, out2_prerelease, out2, out3.  See
63039** the mkopcodeh.awk script for additional information.
63040**
63041** Documentation about VDBE opcodes is generated by scanning this file
63042** for lines of that contain "Opcode:".  That line and all subsequent
63043** comment lines are used in the generation of the opcode.html documentation
63044** file.
63045**
63046** SUMMARY:
63047**
63048**     Formatting is important to scripts that scan this file.
63049**     Do not deviate from the formatting style currently in use.
63050**
63051*****************************************************************************/
63052
63053/* Opcode:  Goto * P2 * * *
63054**
63055** An unconditional jump to address P2.
63056** The next instruction executed will be
63057** the one at index P2 from the beginning of
63058** the program.
63059*/
63060case OP_Goto: {             /* jump */
63061  CHECK_FOR_INTERRUPT;
63062  pc = pOp->p2 - 1;
63063  break;
63064}
63065
63066/* Opcode:  Gosub P1 P2 * * *
63067**
63068** Write the current address onto register P1
63069** and then jump to address P2.
63070*/
63071case OP_Gosub: {            /* jump, in1 */
63072  pIn1 = &aMem[pOp->p1];
63073  assert( (pIn1->flags & MEM_Dyn)==0 );
63074  memAboutToChange(p, pIn1);
63075  pIn1->flags = MEM_Int;
63076  pIn1->u.i = pc;
63077  REGISTER_TRACE(pOp->p1, pIn1);
63078  pc = pOp->p2 - 1;
63079  break;
63080}
63081
63082/* Opcode:  Return P1 * * * *
63083**
63084** Jump to the next instruction after the address in register P1.
63085*/
63086case OP_Return: {           /* in1 */
63087  pIn1 = &aMem[pOp->p1];
63088  assert( pIn1->flags & MEM_Int );
63089  pc = (int)pIn1->u.i;
63090  break;
63091}
63092
63093/* Opcode:  Yield P1 * * * *
63094**
63095** Swap the program counter with the value in register P1.
63096*/
63097case OP_Yield: {            /* in1 */
63098#if 0  /* local variables moved into u.aa */
63099  int pcDest;
63100#endif /* local variables moved into u.aa */
63101  pIn1 = &aMem[pOp->p1];
63102  assert( (pIn1->flags & MEM_Dyn)==0 );
63103  pIn1->flags = MEM_Int;
63104  u.aa.pcDest = (int)pIn1->u.i;
63105  pIn1->u.i = pc;
63106  REGISTER_TRACE(pOp->p1, pIn1);
63107  pc = u.aa.pcDest;
63108  break;
63109}
63110
63111/* Opcode:  HaltIfNull  P1 P2 P3 P4 *
63112**
63113** Check the value in register P3.  If is is NULL then Halt using
63114** parameter P1, P2, and P4 as if this were a Halt instruction.  If the
63115** value in register P3 is not NULL, then this routine is a no-op.
63116*/
63117case OP_HaltIfNull: {      /* in3 */
63118  pIn3 = &aMem[pOp->p3];
63119  if( (pIn3->flags & MEM_Null)==0 ) break;
63120  /* Fall through into OP_Halt */
63121}
63122
63123/* Opcode:  Halt P1 P2 * P4 *
63124**
63125** Exit immediately.  All open cursors, etc are closed
63126** automatically.
63127**
63128** P1 is the result code returned by sqlite3_exec(), sqlite3_reset(),
63129** or sqlite3_finalize().  For a normal halt, this should be SQLITE_OK (0).
63130** For errors, it can be some other value.  If P1!=0 then P2 will determine
63131** whether or not to rollback the current transaction.  Do not rollback
63132** if P2==OE_Fail. Do the rollback if P2==OE_Rollback.  If P2==OE_Abort,
63133** then back out all changes that have occurred during this execution of the
63134** VDBE, but do not rollback the transaction.
63135**
63136** If P4 is not null then it is an error message string.
63137**
63138** There is an implied "Halt 0 0 0" instruction inserted at the very end of
63139** every program.  So a jump past the last instruction of the program
63140** is the same as executing Halt.
63141*/
63142case OP_Halt: {
63143  if( pOp->p1==SQLITE_OK && p->pFrame ){
63144    /* Halt the sub-program. Return control to the parent frame. */
63145    VdbeFrame *pFrame = p->pFrame;
63146    p->pFrame = pFrame->pParent;
63147    p->nFrame--;
63148    sqlite3VdbeSetChanges(db, p->nChange);
63149    pc = sqlite3VdbeFrameRestore(pFrame);
63150    if( pOp->p2==OE_Ignore ){
63151      /* Instruction pc is the OP_Program that invoked the sub-program
63152      ** currently being halted. If the p2 instruction of this OP_Halt
63153      ** instruction is set to OE_Ignore, then the sub-program is throwing
63154      ** an IGNORE exception. In this case jump to the address specified
63155      ** as the p2 of the calling OP_Program.  */
63156      pc = p->aOp[pc].p2-1;
63157    }
63158    aOp = p->aOp;
63159    aMem = p->aMem;
63160    break;
63161  }
63162
63163  p->rc = pOp->p1;
63164  p->errorAction = (u8)pOp->p2;
63165  p->pc = pc;
63166  if( pOp->p4.z ){
63167    assert( p->rc!=SQLITE_OK );
63168    sqlite3SetString(&p->zErrMsg, db, "%s", pOp->p4.z);
63169    testcase( sqlite3GlobalConfig.xLog!=0 );
63170    sqlite3_log(pOp->p1, "abort at %d in [%s]: %s", pc, p->zSql, pOp->p4.z);
63171  }else if( p->rc ){
63172    testcase( sqlite3GlobalConfig.xLog!=0 );
63173    sqlite3_log(pOp->p1, "constraint failed at %d in [%s]", pc, p->zSql);
63174  }
63175  rc = sqlite3VdbeHalt(p);
63176  assert( rc==SQLITE_BUSY || rc==SQLITE_OK || rc==SQLITE_ERROR );
63177  if( rc==SQLITE_BUSY ){
63178    p->rc = rc = SQLITE_BUSY;
63179  }else{
63180    assert( rc==SQLITE_OK || p->rc==SQLITE_CONSTRAINT );
63181    assert( rc==SQLITE_OK || db->nDeferredCons>0 );
63182    rc = p->rc ? SQLITE_ERROR : SQLITE_DONE;
63183  }
63184  goto vdbe_return;
63185}
63186
63187/* Opcode: Integer P1 P2 * * *
63188**
63189** The 32-bit integer value P1 is written into register P2.
63190*/
63191case OP_Integer: {         /* out2-prerelease */
63192  pOut->u.i = pOp->p1;
63193  break;
63194}
63195
63196/* Opcode: Int64 * P2 * P4 *
63197**
63198** P4 is a pointer to a 64-bit integer value.
63199** Write that value into register P2.
63200*/
63201case OP_Int64: {           /* out2-prerelease */
63202  assert( pOp->p4.pI64!=0 );
63203  pOut->u.i = *pOp->p4.pI64;
63204  break;
63205}
63206
63207#ifndef SQLITE_OMIT_FLOATING_POINT
63208/* Opcode: Real * P2 * P4 *
63209**
63210** P4 is a pointer to a 64-bit floating point value.
63211** Write that value into register P2.
63212*/
63213case OP_Real: {            /* same as TK_FLOAT, out2-prerelease */
63214  pOut->flags = MEM_Real;
63215  assert( !sqlite3IsNaN(*pOp->p4.pReal) );
63216  pOut->r = *pOp->p4.pReal;
63217  break;
63218}
63219#endif
63220
63221/* Opcode: String8 * P2 * P4 *
63222**
63223** P4 points to a nul terminated UTF-8 string. This opcode is transformed
63224** into an OP_String before it is executed for the first time.
63225*/
63226case OP_String8: {         /* same as TK_STRING, out2-prerelease */
63227  assert( pOp->p4.z!=0 );
63228  pOp->opcode = OP_String;
63229  pOp->p1 = sqlite3Strlen30(pOp->p4.z);
63230
63231#ifndef SQLITE_OMIT_UTF16
63232  if( encoding!=SQLITE_UTF8 ){
63233    rc = sqlite3VdbeMemSetStr(pOut, pOp->p4.z, -1, SQLITE_UTF8, SQLITE_STATIC);
63234    if( rc==SQLITE_TOOBIG ) goto too_big;
63235    if( SQLITE_OK!=sqlite3VdbeChangeEncoding(pOut, encoding) ) goto no_mem;
63236    assert( pOut->zMalloc==pOut->z );
63237    assert( pOut->flags & MEM_Dyn );
63238    pOut->zMalloc = 0;
63239    pOut->flags |= MEM_Static;
63240    pOut->flags &= ~MEM_Dyn;
63241    if( pOp->p4type==P4_DYNAMIC ){
63242      sqlite3DbFree(db, pOp->p4.z);
63243    }
63244    pOp->p4type = P4_DYNAMIC;
63245    pOp->p4.z = pOut->z;
63246    pOp->p1 = pOut->n;
63247  }
63248#endif
63249  if( pOp->p1>db->aLimit[SQLITE_LIMIT_LENGTH] ){
63250    goto too_big;
63251  }
63252  /* Fall through to the next case, OP_String */
63253}
63254
63255/* Opcode: String P1 P2 * P4 *
63256**
63257** The string value P4 of length P1 (bytes) is stored in register P2.
63258*/
63259case OP_String: {          /* out2-prerelease */
63260  assert( pOp->p4.z!=0 );
63261  pOut->flags = MEM_Str|MEM_Static|MEM_Term;
63262  pOut->z = pOp->p4.z;
63263  pOut->n = pOp->p1;
63264  pOut->enc = encoding;
63265  UPDATE_MAX_BLOBSIZE(pOut);
63266  break;
63267}
63268
63269/* Opcode: Null * P2 * * *
63270**
63271** Write a NULL into register P2.
63272*/
63273case OP_Null: {           /* out2-prerelease */
63274  pOut->flags = MEM_Null;
63275  break;
63276}
63277
63278
63279/* Opcode: Blob P1 P2 * P4
63280**
63281** P4 points to a blob of data P1 bytes long.  Store this
63282** blob in register P2.
63283*/
63284case OP_Blob: {                /* out2-prerelease */
63285  assert( pOp->p1 <= SQLITE_MAX_LENGTH );
63286  sqlite3VdbeMemSetStr(pOut, pOp->p4.z, pOp->p1, 0, 0);
63287  pOut->enc = encoding;
63288  UPDATE_MAX_BLOBSIZE(pOut);
63289  break;
63290}
63291
63292/* Opcode: Variable P1 P2 * P4 *
63293**
63294** Transfer the values of bound parameter P1 into register P2
63295**
63296** If the parameter is named, then its name appears in P4 and P3==1.
63297** The P4 value is used by sqlite3_bind_parameter_name().
63298*/
63299case OP_Variable: {            /* out2-prerelease */
63300#if 0  /* local variables moved into u.ab */
63301  Mem *pVar;       /* Value being transferred */
63302#endif /* local variables moved into u.ab */
63303
63304  assert( pOp->p1>0 && pOp->p1<=p->nVar );
63305  u.ab.pVar = &p->aVar[pOp->p1 - 1];
63306  if( sqlite3VdbeMemTooBig(u.ab.pVar) ){
63307    goto too_big;
63308  }
63309  sqlite3VdbeMemShallowCopy(pOut, u.ab.pVar, MEM_Static);
63310  UPDATE_MAX_BLOBSIZE(pOut);
63311  break;
63312}
63313
63314/* Opcode: Move P1 P2 P3 * *
63315**
63316** Move the values in register P1..P1+P3-1 over into
63317** registers P2..P2+P3-1.  Registers P1..P1+P1-1 are
63318** left holding a NULL.  It is an error for register ranges
63319** P1..P1+P3-1 and P2..P2+P3-1 to overlap.
63320*/
63321case OP_Move: {
63322#if 0  /* local variables moved into u.ac */
63323  char *zMalloc;   /* Holding variable for allocated memory */
63324  int n;           /* Number of registers left to copy */
63325  int p1;          /* Register to copy from */
63326  int p2;          /* Register to copy to */
63327#endif /* local variables moved into u.ac */
63328
63329  u.ac.n = pOp->p3;
63330  u.ac.p1 = pOp->p1;
63331  u.ac.p2 = pOp->p2;
63332  assert( u.ac.n>0 && u.ac.p1>0 && u.ac.p2>0 );
63333  assert( u.ac.p1+u.ac.n<=u.ac.p2 || u.ac.p2+u.ac.n<=u.ac.p1 );
63334
63335  pIn1 = &aMem[u.ac.p1];
63336  pOut = &aMem[u.ac.p2];
63337  while( u.ac.n-- ){
63338    assert( pOut<=&aMem[p->nMem] );
63339    assert( pIn1<=&aMem[p->nMem] );
63340    assert( memIsValid(pIn1) );
63341    memAboutToChange(p, pOut);
63342    u.ac.zMalloc = pOut->zMalloc;
63343    pOut->zMalloc = 0;
63344    sqlite3VdbeMemMove(pOut, pIn1);
63345    pIn1->zMalloc = u.ac.zMalloc;
63346    REGISTER_TRACE(u.ac.p2++, pOut);
63347    pIn1++;
63348    pOut++;
63349  }
63350  break;
63351}
63352
63353/* Opcode: Copy P1 P2 * * *
63354**
63355** Make a copy of register P1 into register P2.
63356**
63357** This instruction makes a deep copy of the value.  A duplicate
63358** is made of any string or blob constant.  See also OP_SCopy.
63359*/
63360case OP_Copy: {             /* in1, out2 */
63361  pIn1 = &aMem[pOp->p1];
63362  pOut = &aMem[pOp->p2];
63363  assert( pOut!=pIn1 );
63364  sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
63365  Deephemeralize(pOut);
63366  REGISTER_TRACE(pOp->p2, pOut);
63367  break;
63368}
63369
63370/* Opcode: SCopy P1 P2 * * *
63371**
63372** Make a shallow copy of register P1 into register P2.
63373**
63374** This instruction makes a shallow copy of the value.  If the value
63375** is a string or blob, then the copy is only a pointer to the
63376** original and hence if the original changes so will the copy.
63377** Worse, if the original is deallocated, the copy becomes invalid.
63378** Thus the program must guarantee that the original will not change
63379** during the lifetime of the copy.  Use OP_Copy to make a complete
63380** copy.
63381*/
63382case OP_SCopy: {            /* in1, out2 */
63383  pIn1 = &aMem[pOp->p1];
63384  pOut = &aMem[pOp->p2];
63385  assert( pOut!=pIn1 );
63386  sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
63387#ifdef SQLITE_DEBUG
63388  if( pOut->pScopyFrom==0 ) pOut->pScopyFrom = pIn1;
63389#endif
63390  REGISTER_TRACE(pOp->p2, pOut);
63391  break;
63392}
63393
63394/* Opcode: ResultRow P1 P2 * * *
63395**
63396** The registers P1 through P1+P2-1 contain a single row of
63397** results. This opcode causes the sqlite3_step() call to terminate
63398** with an SQLITE_ROW return code and it sets up the sqlite3_stmt
63399** structure to provide access to the top P1 values as the result
63400** row.
63401*/
63402case OP_ResultRow: {
63403#if 0  /* local variables moved into u.ad */
63404  Mem *pMem;
63405  int i;
63406#endif /* local variables moved into u.ad */
63407  assert( p->nResColumn==pOp->p2 );
63408  assert( pOp->p1>0 );
63409  assert( pOp->p1+pOp->p2<=p->nMem+1 );
63410
63411  /* If this statement has violated immediate foreign key constraints, do
63412  ** not return the number of rows modified. And do not RELEASE the statement
63413  ** transaction. It needs to be rolled back.  */
63414  if( SQLITE_OK!=(rc = sqlite3VdbeCheckFk(p, 0)) ){
63415    assert( db->flags&SQLITE_CountRows );
63416    assert( p->usesStmtJournal );
63417    break;
63418  }
63419
63420  /* If the SQLITE_CountRows flag is set in sqlite3.flags mask, then
63421  ** DML statements invoke this opcode to return the number of rows
63422  ** modified to the user. This is the only way that a VM that
63423  ** opens a statement transaction may invoke this opcode.
63424  **
63425  ** In case this is such a statement, close any statement transaction
63426  ** opened by this VM before returning control to the user. This is to
63427  ** ensure that statement-transactions are always nested, not overlapping.
63428  ** If the open statement-transaction is not closed here, then the user
63429  ** may step another VM that opens its own statement transaction. This
63430  ** may lead to overlapping statement transactions.
63431  **
63432  ** The statement transaction is never a top-level transaction.  Hence
63433  ** the RELEASE call below can never fail.
63434  */
63435  assert( p->iStatement==0 || db->flags&SQLITE_CountRows );
63436  rc = sqlite3VdbeCloseStatement(p, SAVEPOINT_RELEASE);
63437  if( NEVER(rc!=SQLITE_OK) ){
63438    break;
63439  }
63440
63441  /* Invalidate all ephemeral cursor row caches */
63442  p->cacheCtr = (p->cacheCtr + 2)|1;
63443
63444  /* Make sure the results of the current row are \000 terminated
63445  ** and have an assigned type.  The results are de-ephemeralized as
63446  ** as side effect.
63447  */
63448  u.ad.pMem = p->pResultSet = &aMem[pOp->p1];
63449  for(u.ad.i=0; u.ad.i<pOp->p2; u.ad.i++){
63450    assert( memIsValid(&u.ad.pMem[u.ad.i]) );
63451    Deephemeralize(&u.ad.pMem[u.ad.i]);
63452    assert( (u.ad.pMem[u.ad.i].flags & MEM_Ephem)==0
63453            || (u.ad.pMem[u.ad.i].flags & (MEM_Str|MEM_Blob))==0 );
63454    sqlite3VdbeMemNulTerminate(&u.ad.pMem[u.ad.i]);
63455    sqlite3VdbeMemStoreType(&u.ad.pMem[u.ad.i]);
63456    REGISTER_TRACE(pOp->p1+u.ad.i, &u.ad.pMem[u.ad.i]);
63457  }
63458  if( db->mallocFailed ) goto no_mem;
63459
63460  /* Return SQLITE_ROW
63461  */
63462  p->pc = pc + 1;
63463  rc = SQLITE_ROW;
63464  goto vdbe_return;
63465}
63466
63467/* Opcode: Concat P1 P2 P3 * *
63468**
63469** Add the text in register P1 onto the end of the text in
63470** register P2 and store the result in register P3.
63471** If either the P1 or P2 text are NULL then store NULL in P3.
63472**
63473**   P3 = P2 || P1
63474**
63475** It is illegal for P1 and P3 to be the same register. Sometimes,
63476** if P3 is the same register as P2, the implementation is able
63477** to avoid a memcpy().
63478*/
63479case OP_Concat: {           /* same as TK_CONCAT, in1, in2, out3 */
63480#if 0  /* local variables moved into u.ae */
63481  i64 nByte;
63482#endif /* local variables moved into u.ae */
63483
63484  pIn1 = &aMem[pOp->p1];
63485  pIn2 = &aMem[pOp->p2];
63486  pOut = &aMem[pOp->p3];
63487  assert( pIn1!=pOut );
63488  if( (pIn1->flags | pIn2->flags) & MEM_Null ){
63489    sqlite3VdbeMemSetNull(pOut);
63490    break;
63491  }
63492  if( ExpandBlob(pIn1) || ExpandBlob(pIn2) ) goto no_mem;
63493  Stringify(pIn1, encoding);
63494  Stringify(pIn2, encoding);
63495  u.ae.nByte = pIn1->n + pIn2->n;
63496  if( u.ae.nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
63497    goto too_big;
63498  }
63499  MemSetTypeFlag(pOut, MEM_Str);
63500  if( sqlite3VdbeMemGrow(pOut, (int)u.ae.nByte+2, pOut==pIn2) ){
63501    goto no_mem;
63502  }
63503  if( pOut!=pIn2 ){
63504    memcpy(pOut->z, pIn2->z, pIn2->n);
63505  }
63506  memcpy(&pOut->z[pIn2->n], pIn1->z, pIn1->n);
63507  pOut->z[u.ae.nByte] = 0;
63508  pOut->z[u.ae.nByte+1] = 0;
63509  pOut->flags |= MEM_Term;
63510  pOut->n = (int)u.ae.nByte;
63511  pOut->enc = encoding;
63512  UPDATE_MAX_BLOBSIZE(pOut);
63513  break;
63514}
63515
63516/* Opcode: Add P1 P2 P3 * *
63517**
63518** Add the value in register P1 to the value in register P2
63519** and store the result in register P3.
63520** If either input is NULL, the result is NULL.
63521*/
63522/* Opcode: Multiply P1 P2 P3 * *
63523**
63524**
63525** Multiply the value in register P1 by the value in register P2
63526** and store the result in register P3.
63527** If either input is NULL, the result is NULL.
63528*/
63529/* Opcode: Subtract P1 P2 P3 * *
63530**
63531** Subtract the value in register P1 from the value in register P2
63532** and store the result in register P3.
63533** If either input is NULL, the result is NULL.
63534*/
63535/* Opcode: Divide P1 P2 P3 * *
63536**
63537** Divide the value in register P1 by the value in register P2
63538** and store the result in register P3 (P3=P2/P1). If the value in
63539** register P1 is zero, then the result is NULL. If either input is
63540** NULL, the result is NULL.
63541*/
63542/* Opcode: Remainder P1 P2 P3 * *
63543**
63544** Compute the remainder after integer division of the value in
63545** register P1 by the value in register P2 and store the result in P3.
63546** If the value in register P2 is zero the result is NULL.
63547** If either operand is NULL, the result is NULL.
63548*/
63549case OP_Add:                   /* same as TK_PLUS, in1, in2, out3 */
63550case OP_Subtract:              /* same as TK_MINUS, in1, in2, out3 */
63551case OP_Multiply:              /* same as TK_STAR, in1, in2, out3 */
63552case OP_Divide:                /* same as TK_SLASH, in1, in2, out3 */
63553case OP_Remainder: {           /* same as TK_REM, in1, in2, out3 */
63554#if 0  /* local variables moved into u.af */
63555  int flags;      /* Combined MEM_* flags from both inputs */
63556  i64 iA;         /* Integer value of left operand */
63557  i64 iB;         /* Integer value of right operand */
63558  double rA;      /* Real value of left operand */
63559  double rB;      /* Real value of right operand */
63560#endif /* local variables moved into u.af */
63561
63562  pIn1 = &aMem[pOp->p1];
63563  applyNumericAffinity(pIn1);
63564  pIn2 = &aMem[pOp->p2];
63565  applyNumericAffinity(pIn2);
63566  pOut = &aMem[pOp->p3];
63567  u.af.flags = pIn1->flags | pIn2->flags;
63568  if( (u.af.flags & MEM_Null)!=0 ) goto arithmetic_result_is_null;
63569  if( (pIn1->flags & pIn2->flags & MEM_Int)==MEM_Int ){
63570    u.af.iA = pIn1->u.i;
63571    u.af.iB = pIn2->u.i;
63572    switch( pOp->opcode ){
63573      case OP_Add:       if( sqlite3AddInt64(&u.af.iB,u.af.iA) ) goto fp_math;  break;
63574      case OP_Subtract:  if( sqlite3SubInt64(&u.af.iB,u.af.iA) ) goto fp_math;  break;
63575      case OP_Multiply:  if( sqlite3MulInt64(&u.af.iB,u.af.iA) ) goto fp_math;  break;
63576      case OP_Divide: {
63577        if( u.af.iA==0 ) goto arithmetic_result_is_null;
63578        if( u.af.iA==-1 && u.af.iB==SMALLEST_INT64 ) goto fp_math;
63579        u.af.iB /= u.af.iA;
63580        break;
63581      }
63582      default: {
63583        if( u.af.iA==0 ) goto arithmetic_result_is_null;
63584        if( u.af.iA==-1 ) u.af.iA = 1;
63585        u.af.iB %= u.af.iA;
63586        break;
63587      }
63588    }
63589    pOut->u.i = u.af.iB;
63590    MemSetTypeFlag(pOut, MEM_Int);
63591  }else{
63592fp_math:
63593    u.af.rA = sqlite3VdbeRealValue(pIn1);
63594    u.af.rB = sqlite3VdbeRealValue(pIn2);
63595    switch( pOp->opcode ){
63596      case OP_Add:         u.af.rB += u.af.rA;       break;
63597      case OP_Subtract:    u.af.rB -= u.af.rA;       break;
63598      case OP_Multiply:    u.af.rB *= u.af.rA;       break;
63599      case OP_Divide: {
63600        /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
63601        if( u.af.rA==(double)0 ) goto arithmetic_result_is_null;
63602        u.af.rB /= u.af.rA;
63603        break;
63604      }
63605      default: {
63606        u.af.iA = (i64)u.af.rA;
63607        u.af.iB = (i64)u.af.rB;
63608        if( u.af.iA==0 ) goto arithmetic_result_is_null;
63609        if( u.af.iA==-1 ) u.af.iA = 1;
63610        u.af.rB = (double)(u.af.iB % u.af.iA);
63611        break;
63612      }
63613    }
63614#ifdef SQLITE_OMIT_FLOATING_POINT
63615    pOut->u.i = u.af.rB;
63616    MemSetTypeFlag(pOut, MEM_Int);
63617#else
63618    if( sqlite3IsNaN(u.af.rB) ){
63619      goto arithmetic_result_is_null;
63620    }
63621    pOut->r = u.af.rB;
63622    MemSetTypeFlag(pOut, MEM_Real);
63623    if( (u.af.flags & MEM_Real)==0 ){
63624      sqlite3VdbeIntegerAffinity(pOut);
63625    }
63626#endif
63627  }
63628  break;
63629
63630arithmetic_result_is_null:
63631  sqlite3VdbeMemSetNull(pOut);
63632  break;
63633}
63634
63635/* Opcode: CollSeq * * P4
63636**
63637** P4 is a pointer to a CollSeq struct. If the next call to a user function
63638** or aggregate calls sqlite3GetFuncCollSeq(), this collation sequence will
63639** be returned. This is used by the built-in min(), max() and nullif()
63640** functions.
63641**
63642** The interface used by the implementation of the aforementioned functions
63643** to retrieve the collation sequence set by this opcode is not available
63644** publicly, only to user functions defined in func.c.
63645*/
63646case OP_CollSeq: {
63647  assert( pOp->p4type==P4_COLLSEQ );
63648  break;
63649}
63650
63651/* Opcode: Function P1 P2 P3 P4 P5
63652**
63653** Invoke a user function (P4 is a pointer to a Function structure that
63654** defines the function) with P5 arguments taken from register P2 and
63655** successors.  The result of the function is stored in register P3.
63656** Register P3 must not be one of the function inputs.
63657**
63658** P1 is a 32-bit bitmask indicating whether or not each argument to the
63659** function was determined to be constant at compile time. If the first
63660** argument was constant then bit 0 of P1 is set. This is used to determine
63661** whether meta data associated with a user function argument using the
63662** sqlite3_set_auxdata() API may be safely retained until the next
63663** invocation of this opcode.
63664**
63665** See also: AggStep and AggFinal
63666*/
63667case OP_Function: {
63668#if 0  /* local variables moved into u.ag */
63669  int i;
63670  Mem *pArg;
63671  sqlite3_context ctx;
63672  sqlite3_value **apVal;
63673  int n;
63674#endif /* local variables moved into u.ag */
63675
63676  u.ag.n = pOp->p5;
63677  u.ag.apVal = p->apArg;
63678  assert( u.ag.apVal || u.ag.n==0 );
63679  assert( pOp->p3>0 && pOp->p3<=p->nMem );
63680  pOut = &aMem[pOp->p3];
63681  memAboutToChange(p, pOut);
63682
63683  assert( u.ag.n==0 || (pOp->p2>0 && pOp->p2+u.ag.n<=p->nMem+1) );
63684  assert( pOp->p3<pOp->p2 || pOp->p3>=pOp->p2+u.ag.n );
63685  u.ag.pArg = &aMem[pOp->p2];
63686  for(u.ag.i=0; u.ag.i<u.ag.n; u.ag.i++, u.ag.pArg++){
63687    assert( memIsValid(u.ag.pArg) );
63688    u.ag.apVal[u.ag.i] = u.ag.pArg;
63689    Deephemeralize(u.ag.pArg);
63690    sqlite3VdbeMemStoreType(u.ag.pArg);
63691    REGISTER_TRACE(pOp->p2+u.ag.i, u.ag.pArg);
63692  }
63693
63694  assert( pOp->p4type==P4_FUNCDEF || pOp->p4type==P4_VDBEFUNC );
63695  if( pOp->p4type==P4_FUNCDEF ){
63696    u.ag.ctx.pFunc = pOp->p4.pFunc;
63697    u.ag.ctx.pVdbeFunc = 0;
63698  }else{
63699    u.ag.ctx.pVdbeFunc = (VdbeFunc*)pOp->p4.pVdbeFunc;
63700    u.ag.ctx.pFunc = u.ag.ctx.pVdbeFunc->pFunc;
63701  }
63702
63703  u.ag.ctx.s.flags = MEM_Null;
63704  u.ag.ctx.s.db = db;
63705  u.ag.ctx.s.xDel = 0;
63706  u.ag.ctx.s.zMalloc = 0;
63707
63708  /* The output cell may already have a buffer allocated. Move
63709  ** the pointer to u.ag.ctx.s so in case the user-function can use
63710  ** the already allocated buffer instead of allocating a new one.
63711  */
63712  sqlite3VdbeMemMove(&u.ag.ctx.s, pOut);
63713  MemSetTypeFlag(&u.ag.ctx.s, MEM_Null);
63714
63715  u.ag.ctx.isError = 0;
63716  if( u.ag.ctx.pFunc->flags & SQLITE_FUNC_NEEDCOLL ){
63717    assert( pOp>aOp );
63718    assert( pOp[-1].p4type==P4_COLLSEQ );
63719    assert( pOp[-1].opcode==OP_CollSeq );
63720    u.ag.ctx.pColl = pOp[-1].p4.pColl;
63721  }
63722  (*u.ag.ctx.pFunc->xFunc)(&u.ag.ctx, u.ag.n, u.ag.apVal); /* IMP: R-24505-23230 */
63723  if( db->mallocFailed ){
63724    /* Even though a malloc() has failed, the implementation of the
63725    ** user function may have called an sqlite3_result_XXX() function
63726    ** to return a value. The following call releases any resources
63727    ** associated with such a value.
63728    */
63729    sqlite3VdbeMemRelease(&u.ag.ctx.s);
63730    goto no_mem;
63731  }
63732
63733  /* If any auxiliary data functions have been called by this user function,
63734  ** immediately call the destructor for any non-static values.
63735  */
63736  if( u.ag.ctx.pVdbeFunc ){
63737    sqlite3VdbeDeleteAuxData(u.ag.ctx.pVdbeFunc, pOp->p1);
63738    pOp->p4.pVdbeFunc = u.ag.ctx.pVdbeFunc;
63739    pOp->p4type = P4_VDBEFUNC;
63740  }
63741
63742  /* If the function returned an error, throw an exception */
63743  if( u.ag.ctx.isError ){
63744    sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3_value_text(&u.ag.ctx.s));
63745    rc = u.ag.ctx.isError;
63746  }
63747
63748  /* Copy the result of the function into register P3 */
63749  sqlite3VdbeChangeEncoding(&u.ag.ctx.s, encoding);
63750  sqlite3VdbeMemMove(pOut, &u.ag.ctx.s);
63751  if( sqlite3VdbeMemTooBig(pOut) ){
63752    goto too_big;
63753  }
63754
63755#if 0
63756  /* The app-defined function has done something that as caused this
63757  ** statement to expire.  (Perhaps the function called sqlite3_exec()
63758  ** with a CREATE TABLE statement.)
63759  */
63760  if( p->expired ) rc = SQLITE_ABORT;
63761#endif
63762
63763  REGISTER_TRACE(pOp->p3, pOut);
63764  UPDATE_MAX_BLOBSIZE(pOut);
63765  break;
63766}
63767
63768/* Opcode: BitAnd P1 P2 P3 * *
63769**
63770** Take the bit-wise AND of the values in register P1 and P2 and
63771** store the result in register P3.
63772** If either input is NULL, the result is NULL.
63773*/
63774/* Opcode: BitOr P1 P2 P3 * *
63775**
63776** Take the bit-wise OR of the values in register P1 and P2 and
63777** store the result in register P3.
63778** If either input is NULL, the result is NULL.
63779*/
63780/* Opcode: ShiftLeft P1 P2 P3 * *
63781**
63782** Shift the integer value in register P2 to the left by the
63783** number of bits specified by the integer in register P1.
63784** Store the result in register P3.
63785** If either input is NULL, the result is NULL.
63786*/
63787/* Opcode: ShiftRight P1 P2 P3 * *
63788**
63789** Shift the integer value in register P2 to the right by the
63790** number of bits specified by the integer in register P1.
63791** Store the result in register P3.
63792** If either input is NULL, the result is NULL.
63793*/
63794case OP_BitAnd:                 /* same as TK_BITAND, in1, in2, out3 */
63795case OP_BitOr:                  /* same as TK_BITOR, in1, in2, out3 */
63796case OP_ShiftLeft:              /* same as TK_LSHIFT, in1, in2, out3 */
63797case OP_ShiftRight: {           /* same as TK_RSHIFT, in1, in2, out3 */
63798#if 0  /* local variables moved into u.ah */
63799  i64 iA;
63800  u64 uA;
63801  i64 iB;
63802  u8 op;
63803#endif /* local variables moved into u.ah */
63804
63805  pIn1 = &aMem[pOp->p1];
63806  pIn2 = &aMem[pOp->p2];
63807  pOut = &aMem[pOp->p3];
63808  if( (pIn1->flags | pIn2->flags) & MEM_Null ){
63809    sqlite3VdbeMemSetNull(pOut);
63810    break;
63811  }
63812  u.ah.iA = sqlite3VdbeIntValue(pIn2);
63813  u.ah.iB = sqlite3VdbeIntValue(pIn1);
63814  u.ah.op = pOp->opcode;
63815  if( u.ah.op==OP_BitAnd ){
63816    u.ah.iA &= u.ah.iB;
63817  }else if( u.ah.op==OP_BitOr ){
63818    u.ah.iA |= u.ah.iB;
63819  }else if( u.ah.iB!=0 ){
63820    assert( u.ah.op==OP_ShiftRight || u.ah.op==OP_ShiftLeft );
63821
63822    /* If shifting by a negative amount, shift in the other direction */
63823    if( u.ah.iB<0 ){
63824      assert( OP_ShiftRight==OP_ShiftLeft+1 );
63825      u.ah.op = 2*OP_ShiftLeft + 1 - u.ah.op;
63826      u.ah.iB = u.ah.iB>(-64) ? -u.ah.iB : 64;
63827    }
63828
63829    if( u.ah.iB>=64 ){
63830      u.ah.iA = (u.ah.iA>=0 || u.ah.op==OP_ShiftLeft) ? 0 : -1;
63831    }else{
63832      memcpy(&u.ah.uA, &u.ah.iA, sizeof(u.ah.uA));
63833      if( u.ah.op==OP_ShiftLeft ){
63834        u.ah.uA <<= u.ah.iB;
63835      }else{
63836        u.ah.uA >>= u.ah.iB;
63837        /* Sign-extend on a right shift of a negative number */
63838        if( u.ah.iA<0 ) u.ah.uA |= ((((u64)0xffffffff)<<32)|0xffffffff) << (64-u.ah.iB);
63839      }
63840      memcpy(&u.ah.iA, &u.ah.uA, sizeof(u.ah.iA));
63841    }
63842  }
63843  pOut->u.i = u.ah.iA;
63844  MemSetTypeFlag(pOut, MEM_Int);
63845  break;
63846}
63847
63848/* Opcode: AddImm  P1 P2 * * *
63849**
63850** Add the constant P2 to the value in register P1.
63851** The result is always an integer.
63852**
63853** To force any register to be an integer, just add 0.
63854*/
63855case OP_AddImm: {            /* in1 */
63856  pIn1 = &aMem[pOp->p1];
63857  memAboutToChange(p, pIn1);
63858  sqlite3VdbeMemIntegerify(pIn1);
63859  pIn1->u.i += pOp->p2;
63860  break;
63861}
63862
63863/* Opcode: MustBeInt P1 P2 * * *
63864**
63865** Force the value in register P1 to be an integer.  If the value
63866** in P1 is not an integer and cannot be converted into an integer
63867** without data loss, then jump immediately to P2, or if P2==0
63868** raise an SQLITE_MISMATCH exception.
63869*/
63870case OP_MustBeInt: {            /* jump, in1 */
63871  pIn1 = &aMem[pOp->p1];
63872  applyAffinity(pIn1, SQLITE_AFF_NUMERIC, encoding);
63873  if( (pIn1->flags & MEM_Int)==0 ){
63874    if( pOp->p2==0 ){
63875      rc = SQLITE_MISMATCH;
63876      goto abort_due_to_error;
63877    }else{
63878      pc = pOp->p2 - 1;
63879    }
63880  }else{
63881    MemSetTypeFlag(pIn1, MEM_Int);
63882  }
63883  break;
63884}
63885
63886#ifndef SQLITE_OMIT_FLOATING_POINT
63887/* Opcode: RealAffinity P1 * * * *
63888**
63889** If register P1 holds an integer convert it to a real value.
63890**
63891** This opcode is used when extracting information from a column that
63892** has REAL affinity.  Such column values may still be stored as
63893** integers, for space efficiency, but after extraction we want them
63894** to have only a real value.
63895*/
63896case OP_RealAffinity: {                  /* in1 */
63897  pIn1 = &aMem[pOp->p1];
63898  if( pIn1->flags & MEM_Int ){
63899    sqlite3VdbeMemRealify(pIn1);
63900  }
63901  break;
63902}
63903#endif
63904
63905#ifndef SQLITE_OMIT_CAST
63906/* Opcode: ToText P1 * * * *
63907**
63908** Force the value in register P1 to be text.
63909** If the value is numeric, convert it to a string using the
63910** equivalent of printf().  Blob values are unchanged and
63911** are afterwards simply interpreted as text.
63912**
63913** A NULL value is not changed by this routine.  It remains NULL.
63914*/
63915case OP_ToText: {                  /* same as TK_TO_TEXT, in1 */
63916  pIn1 = &aMem[pOp->p1];
63917  memAboutToChange(p, pIn1);
63918  if( pIn1->flags & MEM_Null ) break;
63919  assert( MEM_Str==(MEM_Blob>>3) );
63920  pIn1->flags |= (pIn1->flags&MEM_Blob)>>3;
63921  applyAffinity(pIn1, SQLITE_AFF_TEXT, encoding);
63922  rc = ExpandBlob(pIn1);
63923  assert( pIn1->flags & MEM_Str || db->mallocFailed );
63924  pIn1->flags &= ~(MEM_Int|MEM_Real|MEM_Blob|MEM_Zero);
63925  UPDATE_MAX_BLOBSIZE(pIn1);
63926  break;
63927}
63928
63929/* Opcode: ToBlob P1 * * * *
63930**
63931** Force the value in register P1 to be a BLOB.
63932** If the value is numeric, convert it to a string first.
63933** Strings are simply reinterpreted as blobs with no change
63934** to the underlying data.
63935**
63936** A NULL value is not changed by this routine.  It remains NULL.
63937*/
63938case OP_ToBlob: {                  /* same as TK_TO_BLOB, in1 */
63939  pIn1 = &aMem[pOp->p1];
63940  if( pIn1->flags & MEM_Null ) break;
63941  if( (pIn1->flags & MEM_Blob)==0 ){
63942    applyAffinity(pIn1, SQLITE_AFF_TEXT, encoding);
63943    assert( pIn1->flags & MEM_Str || db->mallocFailed );
63944    MemSetTypeFlag(pIn1, MEM_Blob);
63945  }else{
63946    pIn1->flags &= ~(MEM_TypeMask&~MEM_Blob);
63947  }
63948  UPDATE_MAX_BLOBSIZE(pIn1);
63949  break;
63950}
63951
63952/* Opcode: ToNumeric P1 * * * *
63953**
63954** Force the value in register P1 to be numeric (either an
63955** integer or a floating-point number.)
63956** If the value is text or blob, try to convert it to an using the
63957** equivalent of atoi() or atof() and store 0 if no such conversion
63958** is possible.
63959**
63960** A NULL value is not changed by this routine.  It remains NULL.
63961*/
63962case OP_ToNumeric: {                  /* same as TK_TO_NUMERIC, in1 */
63963  pIn1 = &aMem[pOp->p1];
63964  sqlite3VdbeMemNumerify(pIn1);
63965  break;
63966}
63967#endif /* SQLITE_OMIT_CAST */
63968
63969/* Opcode: ToInt P1 * * * *
63970**
63971** Force the value in register P1 to be an integer.  If
63972** The value is currently a real number, drop its fractional part.
63973** If the value is text or blob, try to convert it to an integer using the
63974** equivalent of atoi() and store 0 if no such conversion is possible.
63975**
63976** A NULL value is not changed by this routine.  It remains NULL.
63977*/
63978case OP_ToInt: {                  /* same as TK_TO_INT, in1 */
63979  pIn1 = &aMem[pOp->p1];
63980  if( (pIn1->flags & MEM_Null)==0 ){
63981    sqlite3VdbeMemIntegerify(pIn1);
63982  }
63983  break;
63984}
63985
63986#if !defined(SQLITE_OMIT_CAST) && !defined(SQLITE_OMIT_FLOATING_POINT)
63987/* Opcode: ToReal P1 * * * *
63988**
63989** Force the value in register P1 to be a floating point number.
63990** If The value is currently an integer, convert it.
63991** If the value is text or blob, try to convert it to an integer using the
63992** equivalent of atoi() and store 0.0 if no such conversion is possible.
63993**
63994** A NULL value is not changed by this routine.  It remains NULL.
63995*/
63996case OP_ToReal: {                  /* same as TK_TO_REAL, in1 */
63997  pIn1 = &aMem[pOp->p1];
63998  memAboutToChange(p, pIn1);
63999  if( (pIn1->flags & MEM_Null)==0 ){
64000    sqlite3VdbeMemRealify(pIn1);
64001  }
64002  break;
64003}
64004#endif /* !defined(SQLITE_OMIT_CAST) && !defined(SQLITE_OMIT_FLOATING_POINT) */
64005
64006/* Opcode: Lt P1 P2 P3 P4 P5
64007**
64008** Compare the values in register P1 and P3.  If reg(P3)<reg(P1) then
64009** jump to address P2.
64010**
64011** If the SQLITE_JUMPIFNULL bit of P5 is set and either reg(P1) or
64012** reg(P3) is NULL then take the jump.  If the SQLITE_JUMPIFNULL
64013** bit is clear then fall through if either operand is NULL.
64014**
64015** The SQLITE_AFF_MASK portion of P5 must be an affinity character -
64016** SQLITE_AFF_TEXT, SQLITE_AFF_INTEGER, and so forth. An attempt is made
64017** to coerce both inputs according to this affinity before the
64018** comparison is made. If the SQLITE_AFF_MASK is 0x00, then numeric
64019** affinity is used. Note that the affinity conversions are stored
64020** back into the input registers P1 and P3.  So this opcode can cause
64021** persistent changes to registers P1 and P3.
64022**
64023** Once any conversions have taken place, and neither value is NULL,
64024** the values are compared. If both values are blobs then memcmp() is
64025** used to determine the results of the comparison.  If both values
64026** are text, then the appropriate collating function specified in
64027** P4 is  used to do the comparison.  If P4 is not specified then
64028** memcmp() is used to compare text string.  If both values are
64029** numeric, then a numeric comparison is used. If the two values
64030** are of different types, then numbers are considered less than
64031** strings and strings are considered less than blobs.
64032**
64033** If the SQLITE_STOREP2 bit of P5 is set, then do not jump.  Instead,
64034** store a boolean result (either 0, or 1, or NULL) in register P2.
64035*/
64036/* Opcode: Ne P1 P2 P3 P4 P5
64037**
64038** This works just like the Lt opcode except that the jump is taken if
64039** the operands in registers P1 and P3 are not equal.  See the Lt opcode for
64040** additional information.
64041**
64042** If SQLITE_NULLEQ is set in P5 then the result of comparison is always either
64043** true or false and is never NULL.  If both operands are NULL then the result
64044** of comparison is false.  If either operand is NULL then the result is true.
64045** If neither operand is NULL the the result is the same as it would be if
64046** the SQLITE_NULLEQ flag were omitted from P5.
64047*/
64048/* Opcode: Eq P1 P2 P3 P4 P5
64049**
64050** This works just like the Lt opcode except that the jump is taken if
64051** the operands in registers P1 and P3 are equal.
64052** See the Lt opcode for additional information.
64053**
64054** If SQLITE_NULLEQ is set in P5 then the result of comparison is always either
64055** true or false and is never NULL.  If both operands are NULL then the result
64056** of comparison is true.  If either operand is NULL then the result is false.
64057** If neither operand is NULL the the result is the same as it would be if
64058** the SQLITE_NULLEQ flag were omitted from P5.
64059*/
64060/* Opcode: Le P1 P2 P3 P4 P5
64061**
64062** This works just like the Lt opcode except that the jump is taken if
64063** the content of register P3 is less than or equal to the content of
64064** register P1.  See the Lt opcode for additional information.
64065*/
64066/* Opcode: Gt P1 P2 P3 P4 P5
64067**
64068** This works just like the Lt opcode except that the jump is taken if
64069** the content of register P3 is greater than the content of
64070** register P1.  See the Lt opcode for additional information.
64071*/
64072/* Opcode: Ge P1 P2 P3 P4 P5
64073**
64074** This works just like the Lt opcode except that the jump is taken if
64075** the content of register P3 is greater than or equal to the content of
64076** register P1.  See the Lt opcode for additional information.
64077*/
64078case OP_Eq:               /* same as TK_EQ, jump, in1, in3 */
64079case OP_Ne:               /* same as TK_NE, jump, in1, in3 */
64080case OP_Lt:               /* same as TK_LT, jump, in1, in3 */
64081case OP_Le:               /* same as TK_LE, jump, in1, in3 */
64082case OP_Gt:               /* same as TK_GT, jump, in1, in3 */
64083case OP_Ge: {             /* same as TK_GE, jump, in1, in3 */
64084#if 0  /* local variables moved into u.ai */
64085  int res;            /* Result of the comparison of pIn1 against pIn3 */
64086  char affinity;      /* Affinity to use for comparison */
64087  u16 flags1;         /* Copy of initial value of pIn1->flags */
64088  u16 flags3;         /* Copy of initial value of pIn3->flags */
64089#endif /* local variables moved into u.ai */
64090
64091  pIn1 = &aMem[pOp->p1];
64092  pIn3 = &aMem[pOp->p3];
64093  u.ai.flags1 = pIn1->flags;
64094  u.ai.flags3 = pIn3->flags;
64095  if( (pIn1->flags | pIn3->flags)&MEM_Null ){
64096    /* One or both operands are NULL */
64097    if( pOp->p5 & SQLITE_NULLEQ ){
64098      /* If SQLITE_NULLEQ is set (which will only happen if the operator is
64099      ** OP_Eq or OP_Ne) then take the jump or not depending on whether
64100      ** or not both operands are null.
64101      */
64102      assert( pOp->opcode==OP_Eq || pOp->opcode==OP_Ne );
64103      u.ai.res = (pIn1->flags & pIn3->flags & MEM_Null)==0;
64104    }else{
64105      /* SQLITE_NULLEQ is clear and at least one operand is NULL,
64106      ** then the result is always NULL.
64107      ** The jump is taken if the SQLITE_JUMPIFNULL bit is set.
64108      */
64109      if( pOp->p5 & SQLITE_STOREP2 ){
64110        pOut = &aMem[pOp->p2];
64111        MemSetTypeFlag(pOut, MEM_Null);
64112        REGISTER_TRACE(pOp->p2, pOut);
64113      }else if( pOp->p5 & SQLITE_JUMPIFNULL ){
64114        pc = pOp->p2-1;
64115      }
64116      break;
64117    }
64118  }else{
64119    /* Neither operand is NULL.  Do a comparison. */
64120    u.ai.affinity = pOp->p5 & SQLITE_AFF_MASK;
64121    if( u.ai.affinity ){
64122      applyAffinity(pIn1, u.ai.affinity, encoding);
64123      applyAffinity(pIn3, u.ai.affinity, encoding);
64124      if( db->mallocFailed ) goto no_mem;
64125    }
64126
64127    assert( pOp->p4type==P4_COLLSEQ || pOp->p4.pColl==0 );
64128    ExpandBlob(pIn1);
64129    ExpandBlob(pIn3);
64130    u.ai.res = sqlite3MemCompare(pIn3, pIn1, pOp->p4.pColl);
64131  }
64132  switch( pOp->opcode ){
64133    case OP_Eq:    u.ai.res = u.ai.res==0;     break;
64134    case OP_Ne:    u.ai.res = u.ai.res!=0;     break;
64135    case OP_Lt:    u.ai.res = u.ai.res<0;      break;
64136    case OP_Le:    u.ai.res = u.ai.res<=0;     break;
64137    case OP_Gt:    u.ai.res = u.ai.res>0;      break;
64138    default:       u.ai.res = u.ai.res>=0;     break;
64139  }
64140
64141  if( pOp->p5 & SQLITE_STOREP2 ){
64142    pOut = &aMem[pOp->p2];
64143    memAboutToChange(p, pOut);
64144    MemSetTypeFlag(pOut, MEM_Int);
64145    pOut->u.i = u.ai.res;
64146    REGISTER_TRACE(pOp->p2, pOut);
64147  }else if( u.ai.res ){
64148    pc = pOp->p2-1;
64149  }
64150
64151  /* Undo any changes made by applyAffinity() to the input registers. */
64152  pIn1->flags = (pIn1->flags&~MEM_TypeMask) | (u.ai.flags1&MEM_TypeMask);
64153  pIn3->flags = (pIn3->flags&~MEM_TypeMask) | (u.ai.flags3&MEM_TypeMask);
64154  break;
64155}
64156
64157/* Opcode: Permutation * * * P4 *
64158**
64159** Set the permutation used by the OP_Compare operator to be the array
64160** of integers in P4.
64161**
64162** The permutation is only valid until the next OP_Permutation, OP_Compare,
64163** OP_Halt, or OP_ResultRow.  Typically the OP_Permutation should occur
64164** immediately prior to the OP_Compare.
64165*/
64166case OP_Permutation: {
64167  assert( pOp->p4type==P4_INTARRAY );
64168  assert( pOp->p4.ai );
64169  aPermute = pOp->p4.ai;
64170  break;
64171}
64172
64173/* Opcode: Compare P1 P2 P3 P4 *
64174**
64175** Compare two vectors of registers in reg(P1)..reg(P1+P3-1) (call this
64176** vector "A") and in reg(P2)..reg(P2+P3-1) ("B").  Save the result of
64177** the comparison for use by the next OP_Jump instruct.
64178**
64179** P4 is a KeyInfo structure that defines collating sequences and sort
64180** orders for the comparison.  The permutation applies to registers
64181** only.  The KeyInfo elements are used sequentially.
64182**
64183** The comparison is a sort comparison, so NULLs compare equal,
64184** NULLs are less than numbers, numbers are less than strings,
64185** and strings are less than blobs.
64186*/
64187case OP_Compare: {
64188#if 0  /* local variables moved into u.aj */
64189  int n;
64190  int i;
64191  int p1;
64192  int p2;
64193  const KeyInfo *pKeyInfo;
64194  int idx;
64195  CollSeq *pColl;    /* Collating sequence to use on this term */
64196  int bRev;          /* True for DESCENDING sort order */
64197#endif /* local variables moved into u.aj */
64198
64199  u.aj.n = pOp->p3;
64200  u.aj.pKeyInfo = pOp->p4.pKeyInfo;
64201  assert( u.aj.n>0 );
64202  assert( u.aj.pKeyInfo!=0 );
64203  u.aj.p1 = pOp->p1;
64204  u.aj.p2 = pOp->p2;
64205#if SQLITE_DEBUG
64206  if( aPermute ){
64207    int k, mx = 0;
64208    for(k=0; k<u.aj.n; k++) if( aPermute[k]>mx ) mx = aPermute[k];
64209    assert( u.aj.p1>0 && u.aj.p1+mx<=p->nMem+1 );
64210    assert( u.aj.p2>0 && u.aj.p2+mx<=p->nMem+1 );
64211  }else{
64212    assert( u.aj.p1>0 && u.aj.p1+u.aj.n<=p->nMem+1 );
64213    assert( u.aj.p2>0 && u.aj.p2+u.aj.n<=p->nMem+1 );
64214  }
64215#endif /* SQLITE_DEBUG */
64216  for(u.aj.i=0; u.aj.i<u.aj.n; u.aj.i++){
64217    u.aj.idx = aPermute ? aPermute[u.aj.i] : u.aj.i;
64218    assert( memIsValid(&aMem[u.aj.p1+u.aj.idx]) );
64219    assert( memIsValid(&aMem[u.aj.p2+u.aj.idx]) );
64220    REGISTER_TRACE(u.aj.p1+u.aj.idx, &aMem[u.aj.p1+u.aj.idx]);
64221    REGISTER_TRACE(u.aj.p2+u.aj.idx, &aMem[u.aj.p2+u.aj.idx]);
64222    assert( u.aj.i<u.aj.pKeyInfo->nField );
64223    u.aj.pColl = u.aj.pKeyInfo->aColl[u.aj.i];
64224    u.aj.bRev = u.aj.pKeyInfo->aSortOrder[u.aj.i];
64225    iCompare = sqlite3MemCompare(&aMem[u.aj.p1+u.aj.idx], &aMem[u.aj.p2+u.aj.idx], u.aj.pColl);
64226    if( iCompare ){
64227      if( u.aj.bRev ) iCompare = -iCompare;
64228      break;
64229    }
64230  }
64231  aPermute = 0;
64232  break;
64233}
64234
64235/* Opcode: Jump P1 P2 P3 * *
64236**
64237** Jump to the instruction at address P1, P2, or P3 depending on whether
64238** in the most recent OP_Compare instruction the P1 vector was less than
64239** equal to, or greater than the P2 vector, respectively.
64240*/
64241case OP_Jump: {             /* jump */
64242  if( iCompare<0 ){
64243    pc = pOp->p1 - 1;
64244  }else if( iCompare==0 ){
64245    pc = pOp->p2 - 1;
64246  }else{
64247    pc = pOp->p3 - 1;
64248  }
64249  break;
64250}
64251
64252/* Opcode: And P1 P2 P3 * *
64253**
64254** Take the logical AND of the values in registers P1 and P2 and
64255** write the result into register P3.
64256**
64257** If either P1 or P2 is 0 (false) then the result is 0 even if
64258** the other input is NULL.  A NULL and true or two NULLs give
64259** a NULL output.
64260*/
64261/* Opcode: Or P1 P2 P3 * *
64262**
64263** Take the logical OR of the values in register P1 and P2 and
64264** store the answer in register P3.
64265**
64266** If either P1 or P2 is nonzero (true) then the result is 1 (true)
64267** even if the other input is NULL.  A NULL and false or two NULLs
64268** give a NULL output.
64269*/
64270case OP_And:              /* same as TK_AND, in1, in2, out3 */
64271case OP_Or: {             /* same as TK_OR, in1, in2, out3 */
64272#if 0  /* local variables moved into u.ak */
64273  int v1;    /* Left operand:  0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
64274  int v2;    /* Right operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
64275#endif /* local variables moved into u.ak */
64276
64277  pIn1 = &aMem[pOp->p1];
64278  if( pIn1->flags & MEM_Null ){
64279    u.ak.v1 = 2;
64280  }else{
64281    u.ak.v1 = sqlite3VdbeIntValue(pIn1)!=0;
64282  }
64283  pIn2 = &aMem[pOp->p2];
64284  if( pIn2->flags & MEM_Null ){
64285    u.ak.v2 = 2;
64286  }else{
64287    u.ak.v2 = sqlite3VdbeIntValue(pIn2)!=0;
64288  }
64289  if( pOp->opcode==OP_And ){
64290    static const unsigned char and_logic[] = { 0, 0, 0, 0, 1, 2, 0, 2, 2 };
64291    u.ak.v1 = and_logic[u.ak.v1*3+u.ak.v2];
64292  }else{
64293    static const unsigned char or_logic[] = { 0, 1, 2, 1, 1, 1, 2, 1, 2 };
64294    u.ak.v1 = or_logic[u.ak.v1*3+u.ak.v2];
64295  }
64296  pOut = &aMem[pOp->p3];
64297  if( u.ak.v1==2 ){
64298    MemSetTypeFlag(pOut, MEM_Null);
64299  }else{
64300    pOut->u.i = u.ak.v1;
64301    MemSetTypeFlag(pOut, MEM_Int);
64302  }
64303  break;
64304}
64305
64306/* Opcode: Not P1 P2 * * *
64307**
64308** Interpret the value in register P1 as a boolean value.  Store the
64309** boolean complement in register P2.  If the value in register P1 is
64310** NULL, then a NULL is stored in P2.
64311*/
64312case OP_Not: {                /* same as TK_NOT, in1, out2 */
64313  pIn1 = &aMem[pOp->p1];
64314  pOut = &aMem[pOp->p2];
64315  if( pIn1->flags & MEM_Null ){
64316    sqlite3VdbeMemSetNull(pOut);
64317  }else{
64318    sqlite3VdbeMemSetInt64(pOut, !sqlite3VdbeIntValue(pIn1));
64319  }
64320  break;
64321}
64322
64323/* Opcode: BitNot P1 P2 * * *
64324**
64325** Interpret the content of register P1 as an integer.  Store the
64326** ones-complement of the P1 value into register P2.  If P1 holds
64327** a NULL then store a NULL in P2.
64328*/
64329case OP_BitNot: {             /* same as TK_BITNOT, in1, out2 */
64330  pIn1 = &aMem[pOp->p1];
64331  pOut = &aMem[pOp->p2];
64332  if( pIn1->flags & MEM_Null ){
64333    sqlite3VdbeMemSetNull(pOut);
64334  }else{
64335    sqlite3VdbeMemSetInt64(pOut, ~sqlite3VdbeIntValue(pIn1));
64336  }
64337  break;
64338}
64339
64340/* Opcode: If P1 P2 P3 * *
64341**
64342** Jump to P2 if the value in register P1 is true.  The value is
64343** is considered true if it is numeric and non-zero.  If the value
64344** in P1 is NULL then take the jump if P3 is true.
64345*/
64346/* Opcode: IfNot P1 P2 P3 * *
64347**
64348** Jump to P2 if the value in register P1 is False.  The value is
64349** is considered true if it has a numeric value of zero.  If the value
64350** in P1 is NULL then take the jump if P3 is true.
64351*/
64352case OP_If:                 /* jump, in1 */
64353case OP_IfNot: {            /* jump, in1 */
64354#if 0  /* local variables moved into u.al */
64355  int c;
64356#endif /* local variables moved into u.al */
64357  pIn1 = &aMem[pOp->p1];
64358  if( pIn1->flags & MEM_Null ){
64359    u.al.c = pOp->p3;
64360  }else{
64361#ifdef SQLITE_OMIT_FLOATING_POINT
64362    u.al.c = sqlite3VdbeIntValue(pIn1)!=0;
64363#else
64364    u.al.c = sqlite3VdbeRealValue(pIn1)!=0.0;
64365#endif
64366    if( pOp->opcode==OP_IfNot ) u.al.c = !u.al.c;
64367  }
64368  if( u.al.c ){
64369    pc = pOp->p2-1;
64370  }
64371  break;
64372}
64373
64374/* Opcode: IsNull P1 P2 * * *
64375**
64376** Jump to P2 if the value in register P1 is NULL.
64377*/
64378case OP_IsNull: {            /* same as TK_ISNULL, jump, in1 */
64379  pIn1 = &aMem[pOp->p1];
64380  if( (pIn1->flags & MEM_Null)!=0 ){
64381    pc = pOp->p2 - 1;
64382  }
64383  break;
64384}
64385
64386/* Opcode: NotNull P1 P2 * * *
64387**
64388** Jump to P2 if the value in register P1 is not NULL.
64389*/
64390case OP_NotNull: {            /* same as TK_NOTNULL, jump, in1 */
64391  pIn1 = &aMem[pOp->p1];
64392  if( (pIn1->flags & MEM_Null)==0 ){
64393    pc = pOp->p2 - 1;
64394  }
64395  break;
64396}
64397
64398/* Opcode: Column P1 P2 P3 P4 P5
64399**
64400** Interpret the data that cursor P1 points to as a structure built using
64401** the MakeRecord instruction.  (See the MakeRecord opcode for additional
64402** information about the format of the data.)  Extract the P2-th column
64403** from this record.  If there are less that (P2+1)
64404** values in the record, extract a NULL.
64405**
64406** The value extracted is stored in register P3.
64407**
64408** If the column contains fewer than P2 fields, then extract a NULL.  Or,
64409** if the P4 argument is a P4_MEM use the value of the P4 argument as
64410** the result.
64411**
64412** If the OPFLAG_CLEARCACHE bit is set on P5 and P1 is a pseudo-table cursor,
64413** then the cache of the cursor is reset prior to extracting the column.
64414** The first OP_Column against a pseudo-table after the value of the content
64415** register has changed should have this bit set.
64416*/
64417case OP_Column: {
64418#if 0  /* local variables moved into u.am */
64419  u32 payloadSize;   /* Number of bytes in the record */
64420  i64 payloadSize64; /* Number of bytes in the record */
64421  int p1;            /* P1 value of the opcode */
64422  int p2;            /* column number to retrieve */
64423  VdbeCursor *pC;    /* The VDBE cursor */
64424  char *zRec;        /* Pointer to complete record-data */
64425  BtCursor *pCrsr;   /* The BTree cursor */
64426  u32 *aType;        /* aType[i] holds the numeric type of the i-th column */
64427  u32 *aOffset;      /* aOffset[i] is offset to start of data for i-th column */
64428  int nField;        /* number of fields in the record */
64429  int len;           /* The length of the serialized data for the column */
64430  int i;             /* Loop counter */
64431  char *zData;       /* Part of the record being decoded */
64432  Mem *pDest;        /* Where to write the extracted value */
64433  Mem sMem;          /* For storing the record being decoded */
64434  u8 *zIdx;          /* Index into header */
64435  u8 *zEndHdr;       /* Pointer to first byte after the header */
64436  u32 offset;        /* Offset into the data */
64437  u32 szField;       /* Number of bytes in the content of a field */
64438  int szHdr;         /* Size of the header size field at start of record */
64439  int avail;         /* Number of bytes of available data */
64440  Mem *pReg;         /* PseudoTable input register */
64441#endif /* local variables moved into u.am */
64442
64443
64444  u.am.p1 = pOp->p1;
64445  u.am.p2 = pOp->p2;
64446  u.am.pC = 0;
64447  memset(&u.am.sMem, 0, sizeof(u.am.sMem));
64448  assert( u.am.p1<p->nCursor );
64449  assert( pOp->p3>0 && pOp->p3<=p->nMem );
64450  u.am.pDest = &aMem[pOp->p3];
64451  memAboutToChange(p, u.am.pDest);
64452  MemSetTypeFlag(u.am.pDest, MEM_Null);
64453  u.am.zRec = 0;
64454
64455  /* This block sets the variable u.am.payloadSize to be the total number of
64456  ** bytes in the record.
64457  **
64458  ** u.am.zRec is set to be the complete text of the record if it is available.
64459  ** The complete record text is always available for pseudo-tables
64460  ** If the record is stored in a cursor, the complete record text
64461  ** might be available in the  u.am.pC->aRow cache.  Or it might not be.
64462  ** If the data is unavailable,  u.am.zRec is set to NULL.
64463  **
64464  ** We also compute the number of columns in the record.  For cursors,
64465  ** the number of columns is stored in the VdbeCursor.nField element.
64466  */
64467  u.am.pC = p->apCsr[u.am.p1];
64468  assert( u.am.pC!=0 );
64469#ifndef SQLITE_OMIT_VIRTUALTABLE
64470  assert( u.am.pC->pVtabCursor==0 );
64471#endif
64472  u.am.pCrsr = u.am.pC->pCursor;
64473  if( u.am.pCrsr!=0 ){
64474    /* The record is stored in a B-Tree */
64475    rc = sqlite3VdbeCursorMoveto(u.am.pC);
64476    if( rc ) goto abort_due_to_error;
64477    if( u.am.pC->nullRow ){
64478      u.am.payloadSize = 0;
64479    }else if( u.am.pC->cacheStatus==p->cacheCtr ){
64480      u.am.payloadSize = u.am.pC->payloadSize;
64481      u.am.zRec = (char*)u.am.pC->aRow;
64482    }else if( u.am.pC->isIndex ){
64483      assert( sqlite3BtreeCursorIsValid(u.am.pCrsr) );
64484      rc = sqlite3BtreeKeySize(u.am.pCrsr, &u.am.payloadSize64);
64485      assert( rc==SQLITE_OK );   /* True because of CursorMoveto() call above */
64486      /* sqlite3BtreeParseCellPtr() uses getVarint32() to extract the
64487      ** payload size, so it is impossible for u.am.payloadSize64 to be
64488      ** larger than 32 bits. */
64489      assert( (u.am.payloadSize64 & SQLITE_MAX_U32)==(u64)u.am.payloadSize64 );
64490      u.am.payloadSize = (u32)u.am.payloadSize64;
64491    }else{
64492      assert( sqlite3BtreeCursorIsValid(u.am.pCrsr) );
64493      rc = sqlite3BtreeDataSize(u.am.pCrsr, &u.am.payloadSize);
64494      assert( rc==SQLITE_OK );   /* DataSize() cannot fail */
64495    }
64496  }else if( u.am.pC->pseudoTableReg>0 ){
64497    u.am.pReg = &aMem[u.am.pC->pseudoTableReg];
64498    assert( u.am.pReg->flags & MEM_Blob );
64499    assert( memIsValid(u.am.pReg) );
64500    u.am.payloadSize = u.am.pReg->n;
64501    u.am.zRec = u.am.pReg->z;
64502    u.am.pC->cacheStatus = (pOp->p5&OPFLAG_CLEARCACHE) ? CACHE_STALE : p->cacheCtr;
64503    assert( u.am.payloadSize==0 || u.am.zRec!=0 );
64504  }else{
64505    /* Consider the row to be NULL */
64506    u.am.payloadSize = 0;
64507  }
64508
64509  /* If u.am.payloadSize is 0, then just store a NULL */
64510  if( u.am.payloadSize==0 ){
64511    assert( u.am.pDest->flags&MEM_Null );
64512    goto op_column_out;
64513  }
64514  assert( db->aLimit[SQLITE_LIMIT_LENGTH]>=0 );
64515  if( u.am.payloadSize > (u32)db->aLimit[SQLITE_LIMIT_LENGTH] ){
64516    goto too_big;
64517  }
64518
64519  u.am.nField = u.am.pC->nField;
64520  assert( u.am.p2<u.am.nField );
64521
64522  /* Read and parse the table header.  Store the results of the parse
64523  ** into the record header cache fields of the cursor.
64524  */
64525  u.am.aType = u.am.pC->aType;
64526  if( u.am.pC->cacheStatus==p->cacheCtr ){
64527    u.am.aOffset = u.am.pC->aOffset;
64528  }else{
64529    assert(u.am.aType);
64530    u.am.avail = 0;
64531    u.am.pC->aOffset = u.am.aOffset = &u.am.aType[u.am.nField];
64532    u.am.pC->payloadSize = u.am.payloadSize;
64533    u.am.pC->cacheStatus = p->cacheCtr;
64534
64535    /* Figure out how many bytes are in the header */
64536    if( u.am.zRec ){
64537      u.am.zData = u.am.zRec;
64538    }else{
64539      if( u.am.pC->isIndex ){
64540        u.am.zData = (char*)sqlite3BtreeKeyFetch(u.am.pCrsr, &u.am.avail);
64541      }else{
64542        u.am.zData = (char*)sqlite3BtreeDataFetch(u.am.pCrsr, &u.am.avail);
64543      }
64544      /* If KeyFetch()/DataFetch() managed to get the entire payload,
64545      ** save the payload in the u.am.pC->aRow cache.  That will save us from
64546      ** having to make additional calls to fetch the content portion of
64547      ** the record.
64548      */
64549      assert( u.am.avail>=0 );
64550      if( u.am.payloadSize <= (u32)u.am.avail ){
64551        u.am.zRec = u.am.zData;
64552        u.am.pC->aRow = (u8*)u.am.zData;
64553      }else{
64554        u.am.pC->aRow = 0;
64555      }
64556    }
64557    /* The following assert is true in all cases accept when
64558    ** the database file has been corrupted externally.
64559    **    assert( u.am.zRec!=0 || u.am.avail>=u.am.payloadSize || u.am.avail>=9 ); */
64560    u.am.szHdr = getVarint32((u8*)u.am.zData, u.am.offset);
64561
64562    /* Make sure a corrupt database has not given us an oversize header.
64563    ** Do this now to avoid an oversize memory allocation.
64564    **
64565    ** Type entries can be between 1 and 5 bytes each.  But 4 and 5 byte
64566    ** types use so much data space that there can only be 4096 and 32 of
64567    ** them, respectively.  So the maximum header length results from a
64568    ** 3-byte type for each of the maximum of 32768 columns plus three
64569    ** extra bytes for the header length itself.  32768*3 + 3 = 98307.
64570    */
64571    if( u.am.offset > 98307 ){
64572      rc = SQLITE_CORRUPT_BKPT;
64573      goto op_column_out;
64574    }
64575
64576    /* Compute in u.am.len the number of bytes of data we need to read in order
64577    ** to get u.am.nField type values.  u.am.offset is an upper bound on this.  But
64578    ** u.am.nField might be significantly less than the true number of columns
64579    ** in the table, and in that case, 5*u.am.nField+3 might be smaller than u.am.offset.
64580    ** We want to minimize u.am.len in order to limit the size of the memory
64581    ** allocation, especially if a corrupt database file has caused u.am.offset
64582    ** to be oversized. Offset is limited to 98307 above.  But 98307 might
64583    ** still exceed Robson memory allocation limits on some configurations.
64584    ** On systems that cannot tolerate large memory allocations, u.am.nField*5+3
64585    ** will likely be much smaller since u.am.nField will likely be less than
64586    ** 20 or so.  This insures that Robson memory allocation limits are
64587    ** not exceeded even for corrupt database files.
64588    */
64589    u.am.len = u.am.nField*5 + 3;
64590    if( u.am.len > (int)u.am.offset ) u.am.len = (int)u.am.offset;
64591
64592    /* The KeyFetch() or DataFetch() above are fast and will get the entire
64593    ** record header in most cases.  But they will fail to get the complete
64594    ** record header if the record header does not fit on a single page
64595    ** in the B-Tree.  When that happens, use sqlite3VdbeMemFromBtree() to
64596    ** acquire the complete header text.
64597    */
64598    if( !u.am.zRec && u.am.avail<u.am.len ){
64599      u.am.sMem.flags = 0;
64600      u.am.sMem.db = 0;
64601      rc = sqlite3VdbeMemFromBtree(u.am.pCrsr, 0, u.am.len, u.am.pC->isIndex, &u.am.sMem);
64602      if( rc!=SQLITE_OK ){
64603        goto op_column_out;
64604      }
64605      u.am.zData = u.am.sMem.z;
64606    }
64607    u.am.zEndHdr = (u8 *)&u.am.zData[u.am.len];
64608    u.am.zIdx = (u8 *)&u.am.zData[u.am.szHdr];
64609
64610    /* Scan the header and use it to fill in the u.am.aType[] and u.am.aOffset[]
64611    ** arrays.  u.am.aType[u.am.i] will contain the type integer for the u.am.i-th
64612    ** column and u.am.aOffset[u.am.i] will contain the u.am.offset from the beginning
64613    ** of the record to the start of the data for the u.am.i-th column
64614    */
64615    for(u.am.i=0; u.am.i<u.am.nField; u.am.i++){
64616      if( u.am.zIdx<u.am.zEndHdr ){
64617        u.am.aOffset[u.am.i] = u.am.offset;
64618        u.am.zIdx += getVarint32(u.am.zIdx, u.am.aType[u.am.i]);
64619        u.am.szField = sqlite3VdbeSerialTypeLen(u.am.aType[u.am.i]);
64620        u.am.offset += u.am.szField;
64621        if( u.am.offset<u.am.szField ){  /* True if u.am.offset overflows */
64622          u.am.zIdx = &u.am.zEndHdr[1];  /* Forces SQLITE_CORRUPT return below */
64623          break;
64624        }
64625      }else{
64626        /* If u.am.i is less that u.am.nField, then there are less fields in this
64627        ** record than SetNumColumns indicated there are columns in the
64628        ** table. Set the u.am.offset for any extra columns not present in
64629        ** the record to 0. This tells code below to store a NULL
64630        ** instead of deserializing a value from the record.
64631        */
64632        u.am.aOffset[u.am.i] = 0;
64633      }
64634    }
64635    sqlite3VdbeMemRelease(&u.am.sMem);
64636    u.am.sMem.flags = MEM_Null;
64637
64638    /* If we have read more header data than was contained in the header,
64639    ** or if the end of the last field appears to be past the end of the
64640    ** record, or if the end of the last field appears to be before the end
64641    ** of the record (when all fields present), then we must be dealing
64642    ** with a corrupt database.
64643    */
64644    if( (u.am.zIdx > u.am.zEndHdr) || (u.am.offset > u.am.payloadSize)
64645         || (u.am.zIdx==u.am.zEndHdr && u.am.offset!=u.am.payloadSize) ){
64646      rc = SQLITE_CORRUPT_BKPT;
64647      goto op_column_out;
64648    }
64649  }
64650
64651  /* Get the column information. If u.am.aOffset[u.am.p2] is non-zero, then
64652  ** deserialize the value from the record. If u.am.aOffset[u.am.p2] is zero,
64653  ** then there are not enough fields in the record to satisfy the
64654  ** request.  In this case, set the value NULL or to P4 if P4 is
64655  ** a pointer to a Mem object.
64656  */
64657  if( u.am.aOffset[u.am.p2] ){
64658    assert( rc==SQLITE_OK );
64659    if( u.am.zRec ){
64660      sqlite3VdbeMemReleaseExternal(u.am.pDest);
64661      sqlite3VdbeSerialGet((u8 *)&u.am.zRec[u.am.aOffset[u.am.p2]], u.am.aType[u.am.p2], u.am.pDest);
64662    }else{
64663      u.am.len = sqlite3VdbeSerialTypeLen(u.am.aType[u.am.p2]);
64664      sqlite3VdbeMemMove(&u.am.sMem, u.am.pDest);
64665      rc = sqlite3VdbeMemFromBtree(u.am.pCrsr, u.am.aOffset[u.am.p2], u.am.len, u.am.pC->isIndex, &u.am.sMem);
64666      if( rc!=SQLITE_OK ){
64667        goto op_column_out;
64668      }
64669      u.am.zData = u.am.sMem.z;
64670      sqlite3VdbeSerialGet((u8*)u.am.zData, u.am.aType[u.am.p2], u.am.pDest);
64671    }
64672    u.am.pDest->enc = encoding;
64673  }else{
64674    if( pOp->p4type==P4_MEM ){
64675      sqlite3VdbeMemShallowCopy(u.am.pDest, pOp->p4.pMem, MEM_Static);
64676    }else{
64677      assert( u.am.pDest->flags&MEM_Null );
64678    }
64679  }
64680
64681  /* If we dynamically allocated space to hold the data (in the
64682  ** sqlite3VdbeMemFromBtree() call above) then transfer control of that
64683  ** dynamically allocated space over to the u.am.pDest structure.
64684  ** This prevents a memory copy.
64685  */
64686  if( u.am.sMem.zMalloc ){
64687    assert( u.am.sMem.z==u.am.sMem.zMalloc );
64688    assert( !(u.am.pDest->flags & MEM_Dyn) );
64689    assert( !(u.am.pDest->flags & (MEM_Blob|MEM_Str)) || u.am.pDest->z==u.am.sMem.z );
64690    u.am.pDest->flags &= ~(MEM_Ephem|MEM_Static);
64691    u.am.pDest->flags |= MEM_Term;
64692    u.am.pDest->z = u.am.sMem.z;
64693    u.am.pDest->zMalloc = u.am.sMem.zMalloc;
64694  }
64695
64696  rc = sqlite3VdbeMemMakeWriteable(u.am.pDest);
64697
64698op_column_out:
64699  UPDATE_MAX_BLOBSIZE(u.am.pDest);
64700  REGISTER_TRACE(pOp->p3, u.am.pDest);
64701  break;
64702}
64703
64704/* Opcode: Affinity P1 P2 * P4 *
64705**
64706** Apply affinities to a range of P2 registers starting with P1.
64707**
64708** P4 is a string that is P2 characters long. The nth character of the
64709** string indicates the column affinity that should be used for the nth
64710** memory cell in the range.
64711*/
64712case OP_Affinity: {
64713#if 0  /* local variables moved into u.an */
64714  const char *zAffinity;   /* The affinity to be applied */
64715  char cAff;               /* A single character of affinity */
64716#endif /* local variables moved into u.an */
64717
64718  u.an.zAffinity = pOp->p4.z;
64719  assert( u.an.zAffinity!=0 );
64720  assert( u.an.zAffinity[pOp->p2]==0 );
64721  pIn1 = &aMem[pOp->p1];
64722  while( (u.an.cAff = *(u.an.zAffinity++))!=0 ){
64723    assert( pIn1 <= &p->aMem[p->nMem] );
64724    assert( memIsValid(pIn1) );
64725    ExpandBlob(pIn1);
64726    applyAffinity(pIn1, u.an.cAff, encoding);
64727    pIn1++;
64728  }
64729  break;
64730}
64731
64732/* Opcode: MakeRecord P1 P2 P3 P4 *
64733**
64734** Convert P2 registers beginning with P1 into the [record format]
64735** use as a data record in a database table or as a key
64736** in an index.  The OP_Column opcode can decode the record later.
64737**
64738** P4 may be a string that is P2 characters long.  The nth character of the
64739** string indicates the column affinity that should be used for the nth
64740** field of the index key.
64741**
64742** The mapping from character to affinity is given by the SQLITE_AFF_
64743** macros defined in sqliteInt.h.
64744**
64745** If P4 is NULL then all index fields have the affinity NONE.
64746*/
64747case OP_MakeRecord: {
64748#if 0  /* local variables moved into u.ao */
64749  u8 *zNewRecord;        /* A buffer to hold the data for the new record */
64750  Mem *pRec;             /* The new record */
64751  u64 nData;             /* Number of bytes of data space */
64752  int nHdr;              /* Number of bytes of header space */
64753  i64 nByte;             /* Data space required for this record */
64754  int nZero;             /* Number of zero bytes at the end of the record */
64755  int nVarint;           /* Number of bytes in a varint */
64756  u32 serial_type;       /* Type field */
64757  Mem *pData0;           /* First field to be combined into the record */
64758  Mem *pLast;            /* Last field of the record */
64759  int nField;            /* Number of fields in the record */
64760  char *zAffinity;       /* The affinity string for the record */
64761  int file_format;       /* File format to use for encoding */
64762  int i;                 /* Space used in zNewRecord[] */
64763  int len;               /* Length of a field */
64764#endif /* local variables moved into u.ao */
64765
64766  /* Assuming the record contains N fields, the record format looks
64767  ** like this:
64768  **
64769  ** ------------------------------------------------------------------------
64770  ** | hdr-size | type 0 | type 1 | ... | type N-1 | data0 | ... | data N-1 |
64771  ** ------------------------------------------------------------------------
64772  **
64773  ** Data(0) is taken from register P1.  Data(1) comes from register P1+1
64774  ** and so froth.
64775  **
64776  ** Each type field is a varint representing the serial type of the
64777  ** corresponding data element (see sqlite3VdbeSerialType()). The
64778  ** hdr-size field is also a varint which is the offset from the beginning
64779  ** of the record to data0.
64780  */
64781  u.ao.nData = 0;         /* Number of bytes of data space */
64782  u.ao.nHdr = 0;          /* Number of bytes of header space */
64783  u.ao.nZero = 0;         /* Number of zero bytes at the end of the record */
64784  u.ao.nField = pOp->p1;
64785  u.ao.zAffinity = pOp->p4.z;
64786  assert( u.ao.nField>0 && pOp->p2>0 && pOp->p2+u.ao.nField<=p->nMem+1 );
64787  u.ao.pData0 = &aMem[u.ao.nField];
64788  u.ao.nField = pOp->p2;
64789  u.ao.pLast = &u.ao.pData0[u.ao.nField-1];
64790  u.ao.file_format = p->minWriteFileFormat;
64791
64792  /* Identify the output register */
64793  assert( pOp->p3<pOp->p1 || pOp->p3>=pOp->p1+pOp->p2 );
64794  pOut = &aMem[pOp->p3];
64795  memAboutToChange(p, pOut);
64796
64797  /* Loop through the elements that will make up the record to figure
64798  ** out how much space is required for the new record.
64799  */
64800  for(u.ao.pRec=u.ao.pData0; u.ao.pRec<=u.ao.pLast; u.ao.pRec++){
64801    assert( memIsValid(u.ao.pRec) );
64802    if( u.ao.zAffinity ){
64803      applyAffinity(u.ao.pRec, u.ao.zAffinity[u.ao.pRec-u.ao.pData0], encoding);
64804    }
64805    if( u.ao.pRec->flags&MEM_Zero && u.ao.pRec->n>0 ){
64806      sqlite3VdbeMemExpandBlob(u.ao.pRec);
64807    }
64808    u.ao.serial_type = sqlite3VdbeSerialType(u.ao.pRec, u.ao.file_format);
64809    u.ao.len = sqlite3VdbeSerialTypeLen(u.ao.serial_type);
64810    u.ao.nData += u.ao.len;
64811    u.ao.nHdr += sqlite3VarintLen(u.ao.serial_type);
64812    if( u.ao.pRec->flags & MEM_Zero ){
64813      /* Only pure zero-filled BLOBs can be input to this Opcode.
64814      ** We do not allow blobs with a prefix and a zero-filled tail. */
64815      u.ao.nZero += u.ao.pRec->u.nZero;
64816    }else if( u.ao.len ){
64817      u.ao.nZero = 0;
64818    }
64819  }
64820
64821  /* Add the initial header varint and total the size */
64822  u.ao.nHdr += u.ao.nVarint = sqlite3VarintLen(u.ao.nHdr);
64823  if( u.ao.nVarint<sqlite3VarintLen(u.ao.nHdr) ){
64824    u.ao.nHdr++;
64825  }
64826  u.ao.nByte = u.ao.nHdr+u.ao.nData-u.ao.nZero;
64827  if( u.ao.nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
64828    goto too_big;
64829  }
64830
64831  /* Make sure the output register has a buffer large enough to store
64832  ** the new record. The output register (pOp->p3) is not allowed to
64833  ** be one of the input registers (because the following call to
64834  ** sqlite3VdbeMemGrow() could clobber the value before it is used).
64835  */
64836  if( sqlite3VdbeMemGrow(pOut, (int)u.ao.nByte, 0) ){
64837    goto no_mem;
64838  }
64839  u.ao.zNewRecord = (u8 *)pOut->z;
64840
64841  /* Write the record */
64842  u.ao.i = putVarint32(u.ao.zNewRecord, u.ao.nHdr);
64843  for(u.ao.pRec=u.ao.pData0; u.ao.pRec<=u.ao.pLast; u.ao.pRec++){
64844    u.ao.serial_type = sqlite3VdbeSerialType(u.ao.pRec, u.ao.file_format);
64845    u.ao.i += putVarint32(&u.ao.zNewRecord[u.ao.i], u.ao.serial_type);      /* serial type */
64846  }
64847  for(u.ao.pRec=u.ao.pData0; u.ao.pRec<=u.ao.pLast; u.ao.pRec++){  /* serial data */
64848    u.ao.i += sqlite3VdbeSerialPut(&u.ao.zNewRecord[u.ao.i], (int)(u.ao.nByte-u.ao.i), u.ao.pRec,u.ao.file_format);
64849  }
64850  assert( u.ao.i==u.ao.nByte );
64851
64852  assert( pOp->p3>0 && pOp->p3<=p->nMem );
64853  pOut->n = (int)u.ao.nByte;
64854  pOut->flags = MEM_Blob | MEM_Dyn;
64855  pOut->xDel = 0;
64856  if( u.ao.nZero ){
64857    pOut->u.nZero = u.ao.nZero;
64858    pOut->flags |= MEM_Zero;
64859  }
64860  pOut->enc = SQLITE_UTF8;  /* In case the blob is ever converted to text */
64861  REGISTER_TRACE(pOp->p3, pOut);
64862  UPDATE_MAX_BLOBSIZE(pOut);
64863  break;
64864}
64865
64866/* Opcode: Count P1 P2 * * *
64867**
64868** Store the number of entries (an integer value) in the table or index
64869** opened by cursor P1 in register P2
64870*/
64871#ifndef SQLITE_OMIT_BTREECOUNT
64872case OP_Count: {         /* out2-prerelease */
64873#if 0  /* local variables moved into u.ap */
64874  i64 nEntry;
64875  BtCursor *pCrsr;
64876#endif /* local variables moved into u.ap */
64877
64878  u.ap.pCrsr = p->apCsr[pOp->p1]->pCursor;
64879  if( u.ap.pCrsr ){
64880    rc = sqlite3BtreeCount(u.ap.pCrsr, &u.ap.nEntry);
64881  }else{
64882    u.ap.nEntry = 0;
64883  }
64884  pOut->u.i = u.ap.nEntry;
64885  break;
64886}
64887#endif
64888
64889/* Opcode: Savepoint P1 * * P4 *
64890**
64891** Open, release or rollback the savepoint named by parameter P4, depending
64892** on the value of P1. To open a new savepoint, P1==0. To release (commit) an
64893** existing savepoint, P1==1, or to rollback an existing savepoint P1==2.
64894*/
64895case OP_Savepoint: {
64896#if 0  /* local variables moved into u.aq */
64897  int p1;                         /* Value of P1 operand */
64898  char *zName;                    /* Name of savepoint */
64899  int nName;
64900  Savepoint *pNew;
64901  Savepoint *pSavepoint;
64902  Savepoint *pTmp;
64903  int iSavepoint;
64904  int ii;
64905#endif /* local variables moved into u.aq */
64906
64907  u.aq.p1 = pOp->p1;
64908  u.aq.zName = pOp->p4.z;
64909
64910  /* Assert that the u.aq.p1 parameter is valid. Also that if there is no open
64911  ** transaction, then there cannot be any savepoints.
64912  */
64913  assert( db->pSavepoint==0 || db->autoCommit==0 );
64914  assert( u.aq.p1==SAVEPOINT_BEGIN||u.aq.p1==SAVEPOINT_RELEASE||u.aq.p1==SAVEPOINT_ROLLBACK );
64915  assert( db->pSavepoint || db->isTransactionSavepoint==0 );
64916  assert( checkSavepointCount(db) );
64917
64918  if( u.aq.p1==SAVEPOINT_BEGIN ){
64919    if( db->writeVdbeCnt>0 ){
64920      /* A new savepoint cannot be created if there are active write
64921      ** statements (i.e. open read/write incremental blob handles).
64922      */
64923      sqlite3SetString(&p->zErrMsg, db, "cannot open savepoint - "
64924        "SQL statements in progress");
64925      rc = SQLITE_BUSY;
64926    }else{
64927      u.aq.nName = sqlite3Strlen30(u.aq.zName);
64928
64929      /* Create a new savepoint structure. */
64930      u.aq.pNew = sqlite3DbMallocRaw(db, sizeof(Savepoint)+u.aq.nName+1);
64931      if( u.aq.pNew ){
64932        u.aq.pNew->zName = (char *)&u.aq.pNew[1];
64933        memcpy(u.aq.pNew->zName, u.aq.zName, u.aq.nName+1);
64934
64935        /* If there is no open transaction, then mark this as a special
64936        ** "transaction savepoint". */
64937        if( db->autoCommit ){
64938          db->autoCommit = 0;
64939          db->isTransactionSavepoint = 1;
64940        }else{
64941          db->nSavepoint++;
64942        }
64943
64944        /* Link the new savepoint into the database handle's list. */
64945        u.aq.pNew->pNext = db->pSavepoint;
64946        db->pSavepoint = u.aq.pNew;
64947        u.aq.pNew->nDeferredCons = db->nDeferredCons;
64948      }
64949    }
64950  }else{
64951    u.aq.iSavepoint = 0;
64952
64953    /* Find the named savepoint. If there is no such savepoint, then an
64954    ** an error is returned to the user.  */
64955    for(
64956      u.aq.pSavepoint = db->pSavepoint;
64957      u.aq.pSavepoint && sqlite3StrICmp(u.aq.pSavepoint->zName, u.aq.zName);
64958      u.aq.pSavepoint = u.aq.pSavepoint->pNext
64959    ){
64960      u.aq.iSavepoint++;
64961    }
64962    if( !u.aq.pSavepoint ){
64963      sqlite3SetString(&p->zErrMsg, db, "no such savepoint: %s", u.aq.zName);
64964      rc = SQLITE_ERROR;
64965    }else if(
64966        db->writeVdbeCnt>0 || (u.aq.p1==SAVEPOINT_ROLLBACK && db->activeVdbeCnt>1)
64967    ){
64968      /* It is not possible to release (commit) a savepoint if there are
64969      ** active write statements. It is not possible to rollback a savepoint
64970      ** if there are any active statements at all.
64971      */
64972      sqlite3SetString(&p->zErrMsg, db,
64973        "cannot %s savepoint - SQL statements in progress",
64974        (u.aq.p1==SAVEPOINT_ROLLBACK ? "rollback": "release")
64975      );
64976      rc = SQLITE_BUSY;
64977    }else{
64978
64979      /* Determine whether or not this is a transaction savepoint. If so,
64980      ** and this is a RELEASE command, then the current transaction
64981      ** is committed.
64982      */
64983      int isTransaction = u.aq.pSavepoint->pNext==0 && db->isTransactionSavepoint;
64984      if( isTransaction && u.aq.p1==SAVEPOINT_RELEASE ){
64985        if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){
64986          goto vdbe_return;
64987        }
64988        db->autoCommit = 1;
64989        if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
64990          p->pc = pc;
64991          db->autoCommit = 0;
64992          p->rc = rc = SQLITE_BUSY;
64993          goto vdbe_return;
64994        }
64995        db->isTransactionSavepoint = 0;
64996        rc = p->rc;
64997      }else{
64998        u.aq.iSavepoint = db->nSavepoint - u.aq.iSavepoint - 1;
64999        for(u.aq.ii=0; u.aq.ii<db->nDb; u.aq.ii++){
65000          rc = sqlite3BtreeSavepoint(db->aDb[u.aq.ii].pBt, u.aq.p1, u.aq.iSavepoint);
65001          if( rc!=SQLITE_OK ){
65002            goto abort_due_to_error;
65003          }
65004        }
65005        if( u.aq.p1==SAVEPOINT_ROLLBACK && (db->flags&SQLITE_InternChanges)!=0 ){
65006          sqlite3ExpirePreparedStatements(db);
65007          sqlite3ResetInternalSchema(db, -1);
65008          db->flags = (db->flags | SQLITE_InternChanges);
65009        }
65010      }
65011
65012      /* Regardless of whether this is a RELEASE or ROLLBACK, destroy all
65013      ** savepoints nested inside of the savepoint being operated on. */
65014      while( db->pSavepoint!=u.aq.pSavepoint ){
65015        u.aq.pTmp = db->pSavepoint;
65016        db->pSavepoint = u.aq.pTmp->pNext;
65017        sqlite3DbFree(db, u.aq.pTmp);
65018        db->nSavepoint--;
65019      }
65020
65021      /* If it is a RELEASE, then destroy the savepoint being operated on
65022      ** too. If it is a ROLLBACK TO, then set the number of deferred
65023      ** constraint violations present in the database to the value stored
65024      ** when the savepoint was created.  */
65025      if( u.aq.p1==SAVEPOINT_RELEASE ){
65026        assert( u.aq.pSavepoint==db->pSavepoint );
65027        db->pSavepoint = u.aq.pSavepoint->pNext;
65028        sqlite3DbFree(db, u.aq.pSavepoint);
65029        if( !isTransaction ){
65030          db->nSavepoint--;
65031        }
65032      }else{
65033        db->nDeferredCons = u.aq.pSavepoint->nDeferredCons;
65034      }
65035    }
65036  }
65037
65038  break;
65039}
65040
65041/* Opcode: AutoCommit P1 P2 * * *
65042**
65043** Set the database auto-commit flag to P1 (1 or 0). If P2 is true, roll
65044** back any currently active btree transactions. If there are any active
65045** VMs (apart from this one), then a ROLLBACK fails.  A COMMIT fails if
65046** there are active writing VMs or active VMs that use shared cache.
65047**
65048** This instruction causes the VM to halt.
65049*/
65050case OP_AutoCommit: {
65051#if 0  /* local variables moved into u.ar */
65052  int desiredAutoCommit;
65053  int iRollback;
65054  int turnOnAC;
65055#endif /* local variables moved into u.ar */
65056
65057  u.ar.desiredAutoCommit = pOp->p1;
65058  u.ar.iRollback = pOp->p2;
65059  u.ar.turnOnAC = u.ar.desiredAutoCommit && !db->autoCommit;
65060  assert( u.ar.desiredAutoCommit==1 || u.ar.desiredAutoCommit==0 );
65061  assert( u.ar.desiredAutoCommit==1 || u.ar.iRollback==0 );
65062  assert( db->activeVdbeCnt>0 );  /* At least this one VM is active */
65063
65064  if( u.ar.turnOnAC && u.ar.iRollback && db->activeVdbeCnt>1 ){
65065    /* If this instruction implements a ROLLBACK and other VMs are
65066    ** still running, and a transaction is active, return an error indicating
65067    ** that the other VMs must complete first.
65068    */
65069    sqlite3SetString(&p->zErrMsg, db, "cannot rollback transaction - "
65070        "SQL statements in progress");
65071    rc = SQLITE_BUSY;
65072  }else if( u.ar.turnOnAC && !u.ar.iRollback && db->writeVdbeCnt>0 ){
65073    /* If this instruction implements a COMMIT and other VMs are writing
65074    ** return an error indicating that the other VMs must complete first.
65075    */
65076    sqlite3SetString(&p->zErrMsg, db, "cannot commit transaction - "
65077        "SQL statements in progress");
65078    rc = SQLITE_BUSY;
65079  }else if( u.ar.desiredAutoCommit!=db->autoCommit ){
65080    if( u.ar.iRollback ){
65081      assert( u.ar.desiredAutoCommit==1 );
65082      sqlite3RollbackAll(db);
65083      db->autoCommit = 1;
65084    }else if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){
65085      goto vdbe_return;
65086    }else{
65087      db->autoCommit = (u8)u.ar.desiredAutoCommit;
65088      if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
65089        p->pc = pc;
65090        db->autoCommit = (u8)(1-u.ar.desiredAutoCommit);
65091        p->rc = rc = SQLITE_BUSY;
65092        goto vdbe_return;
65093      }
65094    }
65095    assert( db->nStatement==0 );
65096    sqlite3CloseSavepoints(db);
65097    if( p->rc==SQLITE_OK ){
65098      rc = SQLITE_DONE;
65099    }else{
65100      rc = SQLITE_ERROR;
65101    }
65102    goto vdbe_return;
65103  }else{
65104    sqlite3SetString(&p->zErrMsg, db,
65105        (!u.ar.desiredAutoCommit)?"cannot start a transaction within a transaction":(
65106        (u.ar.iRollback)?"cannot rollback - no transaction is active":
65107                   "cannot commit - no transaction is active"));
65108
65109    rc = SQLITE_ERROR;
65110  }
65111  break;
65112}
65113
65114/* Opcode: Transaction P1 P2 * * *
65115**
65116** Begin a transaction.  The transaction ends when a Commit or Rollback
65117** opcode is encountered.  Depending on the ON CONFLICT setting, the
65118** transaction might also be rolled back if an error is encountered.
65119**
65120** P1 is the index of the database file on which the transaction is
65121** started.  Index 0 is the main database file and index 1 is the
65122** file used for temporary tables.  Indices of 2 or more are used for
65123** attached databases.
65124**
65125** If P2 is non-zero, then a write-transaction is started.  A RESERVED lock is
65126** obtained on the database file when a write-transaction is started.  No
65127** other process can start another write transaction while this transaction is
65128** underway.  Starting a write transaction also creates a rollback journal. A
65129** write transaction must be started before any changes can be made to the
65130** database.  If P2 is 2 or greater then an EXCLUSIVE lock is also obtained
65131** on the file.
65132**
65133** If a write-transaction is started and the Vdbe.usesStmtJournal flag is
65134** true (this flag is set if the Vdbe may modify more than one row and may
65135** throw an ABORT exception), a statement transaction may also be opened.
65136** More specifically, a statement transaction is opened iff the database
65137** connection is currently not in autocommit mode, or if there are other
65138** active statements. A statement transaction allows the affects of this
65139** VDBE to be rolled back after an error without having to roll back the
65140** entire transaction. If no error is encountered, the statement transaction
65141** will automatically commit when the VDBE halts.
65142**
65143** If P2 is zero, then a read-lock is obtained on the database file.
65144*/
65145case OP_Transaction: {
65146#if 0  /* local variables moved into u.as */
65147  Btree *pBt;
65148#endif /* local variables moved into u.as */
65149
65150  assert( pOp->p1>=0 && pOp->p1<db->nDb );
65151  assert( (p->btreeMask & (((yDbMask)1)<<pOp->p1))!=0 );
65152  u.as.pBt = db->aDb[pOp->p1].pBt;
65153
65154  if( u.as.pBt ){
65155    rc = sqlite3BtreeBeginTrans(u.as.pBt, pOp->p2);
65156    if( rc==SQLITE_BUSY ){
65157      p->pc = pc;
65158      p->rc = rc = SQLITE_BUSY;
65159      goto vdbe_return;
65160    }
65161    if( rc!=SQLITE_OK ){
65162      goto abort_due_to_error;
65163    }
65164
65165    if( pOp->p2 && p->usesStmtJournal
65166     && (db->autoCommit==0 || db->activeVdbeCnt>1)
65167    ){
65168      assert( sqlite3BtreeIsInTrans(u.as.pBt) );
65169      if( p->iStatement==0 ){
65170        assert( db->nStatement>=0 && db->nSavepoint>=0 );
65171        db->nStatement++;
65172        p->iStatement = db->nSavepoint + db->nStatement;
65173      }
65174      rc = sqlite3BtreeBeginStmt(u.as.pBt, p->iStatement);
65175
65176      /* Store the current value of the database handles deferred constraint
65177      ** counter. If the statement transaction needs to be rolled back,
65178      ** the value of this counter needs to be restored too.  */
65179      p->nStmtDefCons = db->nDeferredCons;
65180    }
65181  }
65182  break;
65183}
65184
65185/* Opcode: ReadCookie P1 P2 P3 * *
65186**
65187** Read cookie number P3 from database P1 and write it into register P2.
65188** P3==1 is the schema version.  P3==2 is the database format.
65189** P3==3 is the recommended pager cache size, and so forth.  P1==0 is
65190** the main database file and P1==1 is the database file used to store
65191** temporary tables.
65192**
65193** There must be a read-lock on the database (either a transaction
65194** must be started or there must be an open cursor) before
65195** executing this instruction.
65196*/
65197case OP_ReadCookie: {               /* out2-prerelease */
65198#if 0  /* local variables moved into u.at */
65199  int iMeta;
65200  int iDb;
65201  int iCookie;
65202#endif /* local variables moved into u.at */
65203
65204  u.at.iDb = pOp->p1;
65205  u.at.iCookie = pOp->p3;
65206  assert( pOp->p3<SQLITE_N_BTREE_META );
65207  assert( u.at.iDb>=0 && u.at.iDb<db->nDb );
65208  assert( db->aDb[u.at.iDb].pBt!=0 );
65209  assert( (p->btreeMask & (((yDbMask)1)<<u.at.iDb))!=0 );
65210
65211  sqlite3BtreeGetMeta(db->aDb[u.at.iDb].pBt, u.at.iCookie, (u32 *)&u.at.iMeta);
65212  pOut->u.i = u.at.iMeta;
65213  break;
65214}
65215
65216/* Opcode: SetCookie P1 P2 P3 * *
65217**
65218** Write the content of register P3 (interpreted as an integer)
65219** into cookie number P2 of database P1.  P2==1 is the schema version.
65220** P2==2 is the database format. P2==3 is the recommended pager cache
65221** size, and so forth.  P1==0 is the main database file and P1==1 is the
65222** database file used to store temporary tables.
65223**
65224** A transaction must be started before executing this opcode.
65225*/
65226case OP_SetCookie: {       /* in3 */
65227#if 0  /* local variables moved into u.au */
65228  Db *pDb;
65229#endif /* local variables moved into u.au */
65230  assert( pOp->p2<SQLITE_N_BTREE_META );
65231  assert( pOp->p1>=0 && pOp->p1<db->nDb );
65232  assert( (p->btreeMask & (((yDbMask)1)<<pOp->p1))!=0 );
65233  u.au.pDb = &db->aDb[pOp->p1];
65234  assert( u.au.pDb->pBt!=0 );
65235  assert( sqlite3SchemaMutexHeld(db, pOp->p1, 0) );
65236  pIn3 = &aMem[pOp->p3];
65237  sqlite3VdbeMemIntegerify(pIn3);
65238  /* See note about index shifting on OP_ReadCookie */
65239  rc = sqlite3BtreeUpdateMeta(u.au.pDb->pBt, pOp->p2, (int)pIn3->u.i);
65240  if( pOp->p2==BTREE_SCHEMA_VERSION ){
65241    /* When the schema cookie changes, record the new cookie internally */
65242    u.au.pDb->pSchema->schema_cookie = (int)pIn3->u.i;
65243    db->flags |= SQLITE_InternChanges;
65244  }else if( pOp->p2==BTREE_FILE_FORMAT ){
65245    /* Record changes in the file format */
65246    u.au.pDb->pSchema->file_format = (u8)pIn3->u.i;
65247  }
65248  if( pOp->p1==1 ){
65249    /* Invalidate all prepared statements whenever the TEMP database
65250    ** schema is changed.  Ticket #1644 */
65251    sqlite3ExpirePreparedStatements(db);
65252    p->expired = 0;
65253  }
65254  break;
65255}
65256
65257/* Opcode: VerifyCookie P1 P2 P3 * *
65258**
65259** Check the value of global database parameter number 0 (the
65260** schema version) and make sure it is equal to P2 and that the
65261** generation counter on the local schema parse equals P3.
65262**
65263** P1 is the database number which is 0 for the main database file
65264** and 1 for the file holding temporary tables and some higher number
65265** for auxiliary databases.
65266**
65267** The cookie changes its value whenever the database schema changes.
65268** This operation is used to detect when that the cookie has changed
65269** and that the current process needs to reread the schema.
65270**
65271** Either a transaction needs to have been started or an OP_Open needs
65272** to be executed (to establish a read lock) before this opcode is
65273** invoked.
65274*/
65275case OP_VerifyCookie: {
65276#if 0  /* local variables moved into u.av */
65277  int iMeta;
65278  int iGen;
65279  Btree *pBt;
65280#endif /* local variables moved into u.av */
65281
65282  assert( pOp->p1>=0 && pOp->p1<db->nDb );
65283  assert( (p->btreeMask & (((yDbMask)1)<<pOp->p1))!=0 );
65284  assert( sqlite3SchemaMutexHeld(db, pOp->p1, 0) );
65285  u.av.pBt = db->aDb[pOp->p1].pBt;
65286  if( u.av.pBt ){
65287    sqlite3BtreeGetMeta(u.av.pBt, BTREE_SCHEMA_VERSION, (u32 *)&u.av.iMeta);
65288    u.av.iGen = db->aDb[pOp->p1].pSchema->iGeneration;
65289  }else{
65290    u.av.iGen = u.av.iMeta = 0;
65291  }
65292  if( u.av.iMeta!=pOp->p2 || u.av.iGen!=pOp->p3 ){
65293    sqlite3DbFree(db, p->zErrMsg);
65294    p->zErrMsg = sqlite3DbStrDup(db, "database schema has changed");
65295    /* If the schema-cookie from the database file matches the cookie
65296    ** stored with the in-memory representation of the schema, do
65297    ** not reload the schema from the database file.
65298    **
65299    ** If virtual-tables are in use, this is not just an optimization.
65300    ** Often, v-tables store their data in other SQLite tables, which
65301    ** are queried from within xNext() and other v-table methods using
65302    ** prepared queries. If such a query is out-of-date, we do not want to
65303    ** discard the database schema, as the user code implementing the
65304    ** v-table would have to be ready for the sqlite3_vtab structure itself
65305    ** to be invalidated whenever sqlite3_step() is called from within
65306    ** a v-table method.
65307    */
65308    if( db->aDb[pOp->p1].pSchema->schema_cookie!=u.av.iMeta ){
65309      sqlite3ResetInternalSchema(db, pOp->p1);
65310    }
65311
65312    p->expired = 1;
65313    rc = SQLITE_SCHEMA;
65314  }
65315  break;
65316}
65317
65318/* Opcode: OpenRead P1 P2 P3 P4 P5
65319**
65320** Open a read-only cursor for the database table whose root page is
65321** P2 in a database file.  The database file is determined by P3.
65322** P3==0 means the main database, P3==1 means the database used for
65323** temporary tables, and P3>1 means used the corresponding attached
65324** database.  Give the new cursor an identifier of P1.  The P1
65325** values need not be contiguous but all P1 values should be small integers.
65326** It is an error for P1 to be negative.
65327**
65328** If P5!=0 then use the content of register P2 as the root page, not
65329** the value of P2 itself.
65330**
65331** There will be a read lock on the database whenever there is an
65332** open cursor.  If the database was unlocked prior to this instruction
65333** then a read lock is acquired as part of this instruction.  A read
65334** lock allows other processes to read the database but prohibits
65335** any other process from modifying the database.  The read lock is
65336** released when all cursors are closed.  If this instruction attempts
65337** to get a read lock but fails, the script terminates with an
65338** SQLITE_BUSY error code.
65339**
65340** The P4 value may be either an integer (P4_INT32) or a pointer to
65341** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo
65342** structure, then said structure defines the content and collating
65343** sequence of the index being opened. Otherwise, if P4 is an integer
65344** value, it is set to the number of columns in the table.
65345**
65346** See also OpenWrite.
65347*/
65348/* Opcode: OpenWrite P1 P2 P3 P4 P5
65349**
65350** Open a read/write cursor named P1 on the table or index whose root
65351** page is P2.  Or if P5!=0 use the content of register P2 to find the
65352** root page.
65353**
65354** The P4 value may be either an integer (P4_INT32) or a pointer to
65355** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo
65356** structure, then said structure defines the content and collating
65357** sequence of the index being opened. Otherwise, if P4 is an integer
65358** value, it is set to the number of columns in the table, or to the
65359** largest index of any column of the table that is actually used.
65360**
65361** This instruction works just like OpenRead except that it opens the cursor
65362** in read/write mode.  For a given table, there can be one or more read-only
65363** cursors or a single read/write cursor but not both.
65364**
65365** See also OpenRead.
65366*/
65367case OP_OpenRead:
65368case OP_OpenWrite: {
65369#if 0  /* local variables moved into u.aw */
65370  int nField;
65371  KeyInfo *pKeyInfo;
65372  int p2;
65373  int iDb;
65374  int wrFlag;
65375  Btree *pX;
65376  VdbeCursor *pCur;
65377  Db *pDb;
65378#endif /* local variables moved into u.aw */
65379
65380  if( p->expired ){
65381    rc = SQLITE_ABORT;
65382    break;
65383  }
65384
65385  u.aw.nField = 0;
65386  u.aw.pKeyInfo = 0;
65387  u.aw.p2 = pOp->p2;
65388  u.aw.iDb = pOp->p3;
65389  assert( u.aw.iDb>=0 && u.aw.iDb<db->nDb );
65390  assert( (p->btreeMask & (((yDbMask)1)<<u.aw.iDb))!=0 );
65391  u.aw.pDb = &db->aDb[u.aw.iDb];
65392  u.aw.pX = u.aw.pDb->pBt;
65393  assert( u.aw.pX!=0 );
65394  if( pOp->opcode==OP_OpenWrite ){
65395    u.aw.wrFlag = 1;
65396    assert( sqlite3SchemaMutexHeld(db, u.aw.iDb, 0) );
65397    if( u.aw.pDb->pSchema->file_format < p->minWriteFileFormat ){
65398      p->minWriteFileFormat = u.aw.pDb->pSchema->file_format;
65399    }
65400  }else{
65401    u.aw.wrFlag = 0;
65402  }
65403  if( pOp->p5 ){
65404    assert( u.aw.p2>0 );
65405    assert( u.aw.p2<=p->nMem );
65406    pIn2 = &aMem[u.aw.p2];
65407    assert( memIsValid(pIn2) );
65408    assert( (pIn2->flags & MEM_Int)!=0 );
65409    sqlite3VdbeMemIntegerify(pIn2);
65410    u.aw.p2 = (int)pIn2->u.i;
65411    /* The u.aw.p2 value always comes from a prior OP_CreateTable opcode and
65412    ** that opcode will always set the u.aw.p2 value to 2 or more or else fail.
65413    ** If there were a failure, the prepared statement would have halted
65414    ** before reaching this instruction. */
65415    if( NEVER(u.aw.p2<2) ) {
65416      rc = SQLITE_CORRUPT_BKPT;
65417      goto abort_due_to_error;
65418    }
65419  }
65420  if( pOp->p4type==P4_KEYINFO ){
65421    u.aw.pKeyInfo = pOp->p4.pKeyInfo;
65422    u.aw.pKeyInfo->enc = ENC(p->db);
65423    u.aw.nField = u.aw.pKeyInfo->nField+1;
65424  }else if( pOp->p4type==P4_INT32 ){
65425    u.aw.nField = pOp->p4.i;
65426  }
65427  assert( pOp->p1>=0 );
65428  u.aw.pCur = allocateCursor(p, pOp->p1, u.aw.nField, u.aw.iDb, 1);
65429  if( u.aw.pCur==0 ) goto no_mem;
65430  u.aw.pCur->nullRow = 1;
65431  u.aw.pCur->isOrdered = 1;
65432  rc = sqlite3BtreeCursor(u.aw.pX, u.aw.p2, u.aw.wrFlag, u.aw.pKeyInfo, u.aw.pCur->pCursor);
65433  u.aw.pCur->pKeyInfo = u.aw.pKeyInfo;
65434
65435  /* Since it performs no memory allocation or IO, the only values that
65436  ** sqlite3BtreeCursor() may return are SQLITE_EMPTY and SQLITE_OK.
65437  ** SQLITE_EMPTY is only returned when attempting to open the table
65438  ** rooted at page 1 of a zero-byte database.  */
65439  assert( rc==SQLITE_EMPTY || rc==SQLITE_OK );
65440  if( rc==SQLITE_EMPTY ){
65441    u.aw.pCur->pCursor = 0;
65442    rc = SQLITE_OK;
65443  }
65444
65445  /* Set the VdbeCursor.isTable and isIndex variables. Previous versions of
65446  ** SQLite used to check if the root-page flags were sane at this point
65447  ** and report database corruption if they were not, but this check has
65448  ** since moved into the btree layer.  */
65449  u.aw.pCur->isTable = pOp->p4type!=P4_KEYINFO;
65450  u.aw.pCur->isIndex = !u.aw.pCur->isTable;
65451  break;
65452}
65453
65454/* Opcode: OpenEphemeral P1 P2 * P4 *
65455**
65456** Open a new cursor P1 to a transient table.
65457** The cursor is always opened read/write even if
65458** the main database is read-only.  The ephemeral
65459** table is deleted automatically when the cursor is closed.
65460**
65461** P2 is the number of columns in the ephemeral table.
65462** The cursor points to a BTree table if P4==0 and to a BTree index
65463** if P4 is not 0.  If P4 is not NULL, it points to a KeyInfo structure
65464** that defines the format of keys in the index.
65465**
65466** This opcode was once called OpenTemp.  But that created
65467** confusion because the term "temp table", might refer either
65468** to a TEMP table at the SQL level, or to a table opened by
65469** this opcode.  Then this opcode was call OpenVirtual.  But
65470** that created confusion with the whole virtual-table idea.
65471*/
65472/* Opcode: OpenAutoindex P1 P2 * P4 *
65473**
65474** This opcode works the same as OP_OpenEphemeral.  It has a
65475** different name to distinguish its use.  Tables created using
65476** by this opcode will be used for automatically created transient
65477** indices in joins.
65478*/
65479case OP_OpenAutoindex:
65480case OP_OpenEphemeral: {
65481#if 0  /* local variables moved into u.ax */
65482  VdbeCursor *pCx;
65483#endif /* local variables moved into u.ax */
65484  static const int vfsFlags =
65485      SQLITE_OPEN_READWRITE |
65486      SQLITE_OPEN_CREATE |
65487      SQLITE_OPEN_EXCLUSIVE |
65488      SQLITE_OPEN_DELETEONCLOSE |
65489      SQLITE_OPEN_TRANSIENT_DB;
65490
65491  assert( pOp->p1>=0 );
65492  u.ax.pCx = allocateCursor(p, pOp->p1, pOp->p2, -1, 1);
65493  if( u.ax.pCx==0 ) goto no_mem;
65494  u.ax.pCx->nullRow = 1;
65495  rc = sqlite3BtreeOpen(0, db, &u.ax.pCx->pBt,
65496                        BTREE_OMIT_JOURNAL | BTREE_SINGLE | pOp->p5, vfsFlags);
65497  if( rc==SQLITE_OK ){
65498    rc = sqlite3BtreeBeginTrans(u.ax.pCx->pBt, 1);
65499  }
65500  if( rc==SQLITE_OK ){
65501    /* If a transient index is required, create it by calling
65502    ** sqlite3BtreeCreateTable() with the BTREE_BLOBKEY flag before
65503    ** opening it. If a transient table is required, just use the
65504    ** automatically created table with root-page 1 (an BLOB_INTKEY table).
65505    */
65506    if( pOp->p4.pKeyInfo ){
65507      int pgno;
65508      assert( pOp->p4type==P4_KEYINFO );
65509      rc = sqlite3BtreeCreateTable(u.ax.pCx->pBt, &pgno, BTREE_BLOBKEY);
65510      if( rc==SQLITE_OK ){
65511        assert( pgno==MASTER_ROOT+1 );
65512        rc = sqlite3BtreeCursor(u.ax.pCx->pBt, pgno, 1,
65513                                (KeyInfo*)pOp->p4.z, u.ax.pCx->pCursor);
65514        u.ax.pCx->pKeyInfo = pOp->p4.pKeyInfo;
65515        u.ax.pCx->pKeyInfo->enc = ENC(p->db);
65516      }
65517      u.ax.pCx->isTable = 0;
65518    }else{
65519      rc = sqlite3BtreeCursor(u.ax.pCx->pBt, MASTER_ROOT, 1, 0, u.ax.pCx->pCursor);
65520      u.ax.pCx->isTable = 1;
65521    }
65522  }
65523  u.ax.pCx->isOrdered = (pOp->p5!=BTREE_UNORDERED);
65524  u.ax.pCx->isIndex = !u.ax.pCx->isTable;
65525  break;
65526}
65527
65528/* Opcode: OpenPseudo P1 P2 P3 * *
65529**
65530** Open a new cursor that points to a fake table that contains a single
65531** row of data.  The content of that one row in the content of memory
65532** register P2.  In other words, cursor P1 becomes an alias for the
65533** MEM_Blob content contained in register P2.
65534**
65535** A pseudo-table created by this opcode is used to hold a single
65536** row output from the sorter so that the row can be decomposed into
65537** individual columns using the OP_Column opcode.  The OP_Column opcode
65538** is the only cursor opcode that works with a pseudo-table.
65539**
65540** P3 is the number of fields in the records that will be stored by
65541** the pseudo-table.
65542*/
65543case OP_OpenPseudo: {
65544#if 0  /* local variables moved into u.ay */
65545  VdbeCursor *pCx;
65546#endif /* local variables moved into u.ay */
65547
65548  assert( pOp->p1>=0 );
65549  u.ay.pCx = allocateCursor(p, pOp->p1, pOp->p3, -1, 0);
65550  if( u.ay.pCx==0 ) goto no_mem;
65551  u.ay.pCx->nullRow = 1;
65552  u.ay.pCx->pseudoTableReg = pOp->p2;
65553  u.ay.pCx->isTable = 1;
65554  u.ay.pCx->isIndex = 0;
65555  break;
65556}
65557
65558/* Opcode: Close P1 * * * *
65559**
65560** Close a cursor previously opened as P1.  If P1 is not
65561** currently open, this instruction is a no-op.
65562*/
65563case OP_Close: {
65564  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
65565  sqlite3VdbeFreeCursor(p, p->apCsr[pOp->p1]);
65566  p->apCsr[pOp->p1] = 0;
65567  break;
65568}
65569
65570/* Opcode: SeekGe P1 P2 P3 P4 *
65571**
65572** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
65573** use the value in register P3 as the key.  If cursor P1 refers
65574** to an SQL index, then P3 is the first in an array of P4 registers
65575** that are used as an unpacked index key.
65576**
65577** Reposition cursor P1 so that  it points to the smallest entry that
65578** is greater than or equal to the key value. If there are no records
65579** greater than or equal to the key and P2 is not zero, then jump to P2.
65580**
65581** See also: Found, NotFound, Distinct, SeekLt, SeekGt, SeekLe
65582*/
65583/* Opcode: SeekGt P1 P2 P3 P4 *
65584**
65585** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
65586** use the value in register P3 as a key. If cursor P1 refers
65587** to an SQL index, then P3 is the first in an array of P4 registers
65588** that are used as an unpacked index key.
65589**
65590** Reposition cursor P1 so that  it points to the smallest entry that
65591** is greater than the key value. If there are no records greater than
65592** the key and P2 is not zero, then jump to P2.
65593**
65594** See also: Found, NotFound, Distinct, SeekLt, SeekGe, SeekLe
65595*/
65596/* Opcode: SeekLt P1 P2 P3 P4 *
65597**
65598** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
65599** use the value in register P3 as a key. If cursor P1 refers
65600** to an SQL index, then P3 is the first in an array of P4 registers
65601** that are used as an unpacked index key.
65602**
65603** Reposition cursor P1 so that  it points to the largest entry that
65604** is less than the key value. If there are no records less than
65605** the key and P2 is not zero, then jump to P2.
65606**
65607** See also: Found, NotFound, Distinct, SeekGt, SeekGe, SeekLe
65608*/
65609/* Opcode: SeekLe P1 P2 P3 P4 *
65610**
65611** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
65612** use the value in register P3 as a key. If cursor P1 refers
65613** to an SQL index, then P3 is the first in an array of P4 registers
65614** that are used as an unpacked index key.
65615**
65616** Reposition cursor P1 so that it points to the largest entry that
65617** is less than or equal to the key value. If there are no records
65618** less than or equal to the key and P2 is not zero, then jump to P2.
65619**
65620** See also: Found, NotFound, Distinct, SeekGt, SeekGe, SeekLt
65621*/
65622case OP_SeekLt:         /* jump, in3 */
65623case OP_SeekLe:         /* jump, in3 */
65624case OP_SeekGe:         /* jump, in3 */
65625case OP_SeekGt: {       /* jump, in3 */
65626#if 0  /* local variables moved into u.az */
65627  int res;
65628  int oc;
65629  VdbeCursor *pC;
65630  UnpackedRecord r;
65631  int nField;
65632  i64 iKey;      /* The rowid we are to seek to */
65633#endif /* local variables moved into u.az */
65634
65635  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
65636  assert( pOp->p2!=0 );
65637  u.az.pC = p->apCsr[pOp->p1];
65638  assert( u.az.pC!=0 );
65639  assert( u.az.pC->pseudoTableReg==0 );
65640  assert( OP_SeekLe == OP_SeekLt+1 );
65641  assert( OP_SeekGe == OP_SeekLt+2 );
65642  assert( OP_SeekGt == OP_SeekLt+3 );
65643  assert( u.az.pC->isOrdered );
65644  if( u.az.pC->pCursor!=0 ){
65645    u.az.oc = pOp->opcode;
65646    u.az.pC->nullRow = 0;
65647    if( u.az.pC->isTable ){
65648      /* The input value in P3 might be of any type: integer, real, string,
65649      ** blob, or NULL.  But it needs to be an integer before we can do
65650      ** the seek, so covert it. */
65651      pIn3 = &aMem[pOp->p3];
65652      applyNumericAffinity(pIn3);
65653      u.az.iKey = sqlite3VdbeIntValue(pIn3);
65654      u.az.pC->rowidIsValid = 0;
65655
65656      /* If the P3 value could not be converted into an integer without
65657      ** loss of information, then special processing is required... */
65658      if( (pIn3->flags & MEM_Int)==0 ){
65659        if( (pIn3->flags & MEM_Real)==0 ){
65660          /* If the P3 value cannot be converted into any kind of a number,
65661          ** then the seek is not possible, so jump to P2 */
65662          pc = pOp->p2 - 1;
65663          break;
65664        }
65665        /* If we reach this point, then the P3 value must be a floating
65666        ** point number. */
65667        assert( (pIn3->flags & MEM_Real)!=0 );
65668
65669        if( u.az.iKey==SMALLEST_INT64 && (pIn3->r<(double)u.az.iKey || pIn3->r>0) ){
65670          /* The P3 value is too large in magnitude to be expressed as an
65671          ** integer. */
65672          u.az.res = 1;
65673          if( pIn3->r<0 ){
65674            if( u.az.oc>=OP_SeekGe ){  assert( u.az.oc==OP_SeekGe || u.az.oc==OP_SeekGt );
65675              rc = sqlite3BtreeFirst(u.az.pC->pCursor, &u.az.res);
65676              if( rc!=SQLITE_OK ) goto abort_due_to_error;
65677            }
65678          }else{
65679            if( u.az.oc<=OP_SeekLe ){  assert( u.az.oc==OP_SeekLt || u.az.oc==OP_SeekLe );
65680              rc = sqlite3BtreeLast(u.az.pC->pCursor, &u.az.res);
65681              if( rc!=SQLITE_OK ) goto abort_due_to_error;
65682            }
65683          }
65684          if( u.az.res ){
65685            pc = pOp->p2 - 1;
65686          }
65687          break;
65688        }else if( u.az.oc==OP_SeekLt || u.az.oc==OP_SeekGe ){
65689          /* Use the ceiling() function to convert real->int */
65690          if( pIn3->r > (double)u.az.iKey ) u.az.iKey++;
65691        }else{
65692          /* Use the floor() function to convert real->int */
65693          assert( u.az.oc==OP_SeekLe || u.az.oc==OP_SeekGt );
65694          if( pIn3->r < (double)u.az.iKey ) u.az.iKey--;
65695        }
65696      }
65697      rc = sqlite3BtreeMovetoUnpacked(u.az.pC->pCursor, 0, (u64)u.az.iKey, 0, &u.az.res);
65698      if( rc!=SQLITE_OK ){
65699        goto abort_due_to_error;
65700      }
65701      if( u.az.res==0 ){
65702        u.az.pC->rowidIsValid = 1;
65703        u.az.pC->lastRowid = u.az.iKey;
65704      }
65705    }else{
65706      u.az.nField = pOp->p4.i;
65707      assert( pOp->p4type==P4_INT32 );
65708      assert( u.az.nField>0 );
65709      u.az.r.pKeyInfo = u.az.pC->pKeyInfo;
65710      u.az.r.nField = (u16)u.az.nField;
65711
65712      /* The next line of code computes as follows, only faster:
65713      **   if( u.az.oc==OP_SeekGt || u.az.oc==OP_SeekLe ){
65714      **     u.az.r.flags = UNPACKED_INCRKEY;
65715      **   }else{
65716      **     u.az.r.flags = 0;
65717      **   }
65718      */
65719      u.az.r.flags = (u16)(UNPACKED_INCRKEY * (1 & (u.az.oc - OP_SeekLt)));
65720      assert( u.az.oc!=OP_SeekGt || u.az.r.flags==UNPACKED_INCRKEY );
65721      assert( u.az.oc!=OP_SeekLe || u.az.r.flags==UNPACKED_INCRKEY );
65722      assert( u.az.oc!=OP_SeekGe || u.az.r.flags==0 );
65723      assert( u.az.oc!=OP_SeekLt || u.az.r.flags==0 );
65724
65725      u.az.r.aMem = &aMem[pOp->p3];
65726#ifdef SQLITE_DEBUG
65727      { int i; for(i=0; i<u.az.r.nField; i++) assert( memIsValid(&u.az.r.aMem[i]) ); }
65728#endif
65729      ExpandBlob(u.az.r.aMem);
65730      rc = sqlite3BtreeMovetoUnpacked(u.az.pC->pCursor, &u.az.r, 0, 0, &u.az.res);
65731      if( rc!=SQLITE_OK ){
65732        goto abort_due_to_error;
65733      }
65734      u.az.pC->rowidIsValid = 0;
65735    }
65736    u.az.pC->deferredMoveto = 0;
65737    u.az.pC->cacheStatus = CACHE_STALE;
65738#ifdef SQLITE_TEST
65739    sqlite3_search_count++;
65740#endif
65741    if( u.az.oc>=OP_SeekGe ){  assert( u.az.oc==OP_SeekGe || u.az.oc==OP_SeekGt );
65742      if( u.az.res<0 || (u.az.res==0 && u.az.oc==OP_SeekGt) ){
65743        rc = sqlite3BtreeNext(u.az.pC->pCursor, &u.az.res);
65744        if( rc!=SQLITE_OK ) goto abort_due_to_error;
65745        u.az.pC->rowidIsValid = 0;
65746      }else{
65747        u.az.res = 0;
65748      }
65749    }else{
65750      assert( u.az.oc==OP_SeekLt || u.az.oc==OP_SeekLe );
65751      if( u.az.res>0 || (u.az.res==0 && u.az.oc==OP_SeekLt) ){
65752        rc = sqlite3BtreePrevious(u.az.pC->pCursor, &u.az.res);
65753        if( rc!=SQLITE_OK ) goto abort_due_to_error;
65754        u.az.pC->rowidIsValid = 0;
65755      }else{
65756        /* u.az.res might be negative because the table is empty.  Check to
65757        ** see if this is the case.
65758        */
65759        u.az.res = sqlite3BtreeEof(u.az.pC->pCursor);
65760      }
65761    }
65762    assert( pOp->p2>0 );
65763    if( u.az.res ){
65764      pc = pOp->p2 - 1;
65765    }
65766  }else{
65767    /* This happens when attempting to open the sqlite3_master table
65768    ** for read access returns SQLITE_EMPTY. In this case always
65769    ** take the jump (since there are no records in the table).
65770    */
65771    pc = pOp->p2 - 1;
65772  }
65773  break;
65774}
65775
65776/* Opcode: Seek P1 P2 * * *
65777**
65778** P1 is an open table cursor and P2 is a rowid integer.  Arrange
65779** for P1 to move so that it points to the rowid given by P2.
65780**
65781** This is actually a deferred seek.  Nothing actually happens until
65782** the cursor is used to read a record.  That way, if no reads
65783** occur, no unnecessary I/O happens.
65784*/
65785case OP_Seek: {    /* in2 */
65786#if 0  /* local variables moved into u.ba */
65787  VdbeCursor *pC;
65788#endif /* local variables moved into u.ba */
65789
65790  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
65791  u.ba.pC = p->apCsr[pOp->p1];
65792  assert( u.ba.pC!=0 );
65793  if( ALWAYS(u.ba.pC->pCursor!=0) ){
65794    assert( u.ba.pC->isTable );
65795    u.ba.pC->nullRow = 0;
65796    pIn2 = &aMem[pOp->p2];
65797    u.ba.pC->movetoTarget = sqlite3VdbeIntValue(pIn2);
65798    u.ba.pC->rowidIsValid = 0;
65799    u.ba.pC->deferredMoveto = 1;
65800  }
65801  break;
65802}
65803
65804
65805/* Opcode: Found P1 P2 P3 P4 *
65806**
65807** If P4==0 then register P3 holds a blob constructed by MakeRecord.  If
65808** P4>0 then register P3 is the first of P4 registers that form an unpacked
65809** record.
65810**
65811** Cursor P1 is on an index btree.  If the record identified by P3 and P4
65812** is a prefix of any entry in P1 then a jump is made to P2 and
65813** P1 is left pointing at the matching entry.
65814*/
65815/* Opcode: NotFound P1 P2 P3 P4 *
65816**
65817** If P4==0 then register P3 holds a blob constructed by MakeRecord.  If
65818** P4>0 then register P3 is the first of P4 registers that form an unpacked
65819** record.
65820**
65821** Cursor P1 is on an index btree.  If the record identified by P3 and P4
65822** is not the prefix of any entry in P1 then a jump is made to P2.  If P1
65823** does contain an entry whose prefix matches the P3/P4 record then control
65824** falls through to the next instruction and P1 is left pointing at the
65825** matching entry.
65826**
65827** See also: Found, NotExists, IsUnique
65828*/
65829case OP_NotFound:       /* jump, in3 */
65830case OP_Found: {        /* jump, in3 */
65831#if 0  /* local variables moved into u.bb */
65832  int alreadyExists;
65833  VdbeCursor *pC;
65834  int res;
65835  UnpackedRecord *pIdxKey;
65836  UnpackedRecord r;
65837  char aTempRec[ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*3 + 7];
65838#endif /* local variables moved into u.bb */
65839
65840#ifdef SQLITE_TEST
65841  sqlite3_found_count++;
65842#endif
65843
65844  u.bb.alreadyExists = 0;
65845  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
65846  assert( pOp->p4type==P4_INT32 );
65847  u.bb.pC = p->apCsr[pOp->p1];
65848  assert( u.bb.pC!=0 );
65849  pIn3 = &aMem[pOp->p3];
65850  if( ALWAYS(u.bb.pC->pCursor!=0) ){
65851
65852    assert( u.bb.pC->isTable==0 );
65853    if( pOp->p4.i>0 ){
65854      u.bb.r.pKeyInfo = u.bb.pC->pKeyInfo;
65855      u.bb.r.nField = (u16)pOp->p4.i;
65856      u.bb.r.aMem = pIn3;
65857#ifdef SQLITE_DEBUG
65858      { int i; for(i=0; i<u.bb.r.nField; i++) assert( memIsValid(&u.bb.r.aMem[i]) ); }
65859#endif
65860      u.bb.r.flags = UNPACKED_PREFIX_MATCH;
65861      u.bb.pIdxKey = &u.bb.r;
65862    }else{
65863      assert( pIn3->flags & MEM_Blob );
65864      assert( (pIn3->flags & MEM_Zero)==0 );  /* zeroblobs already expanded */
65865      u.bb.pIdxKey = sqlite3VdbeRecordUnpack(u.bb.pC->pKeyInfo, pIn3->n, pIn3->z,
65866                                        u.bb.aTempRec, sizeof(u.bb.aTempRec));
65867      if( u.bb.pIdxKey==0 ){
65868        goto no_mem;
65869      }
65870      u.bb.pIdxKey->flags |= UNPACKED_PREFIX_MATCH;
65871    }
65872    rc = sqlite3BtreeMovetoUnpacked(u.bb.pC->pCursor, u.bb.pIdxKey, 0, 0, &u.bb.res);
65873    if( pOp->p4.i==0 ){
65874      sqlite3VdbeDeleteUnpackedRecord(u.bb.pIdxKey);
65875    }
65876    if( rc!=SQLITE_OK ){
65877      break;
65878    }
65879    u.bb.alreadyExists = (u.bb.res==0);
65880    u.bb.pC->deferredMoveto = 0;
65881    u.bb.pC->cacheStatus = CACHE_STALE;
65882  }
65883  if( pOp->opcode==OP_Found ){
65884    if( u.bb.alreadyExists ) pc = pOp->p2 - 1;
65885  }else{
65886    if( !u.bb.alreadyExists ) pc = pOp->p2 - 1;
65887  }
65888  break;
65889}
65890
65891/* Opcode: IsUnique P1 P2 P3 P4 *
65892**
65893** Cursor P1 is open on an index b-tree - that is to say, a btree which
65894** no data and where the key are records generated by OP_MakeRecord with
65895** the list field being the integer ROWID of the entry that the index
65896** entry refers to.
65897**
65898** The P3 register contains an integer record number. Call this record
65899** number R. Register P4 is the first in a set of N contiguous registers
65900** that make up an unpacked index key that can be used with cursor P1.
65901** The value of N can be inferred from the cursor. N includes the rowid
65902** value appended to the end of the index record. This rowid value may
65903** or may not be the same as R.
65904**
65905** If any of the N registers beginning with register P4 contains a NULL
65906** value, jump immediately to P2.
65907**
65908** Otherwise, this instruction checks if cursor P1 contains an entry
65909** where the first (N-1) fields match but the rowid value at the end
65910** of the index entry is not R. If there is no such entry, control jumps
65911** to instruction P2. Otherwise, the rowid of the conflicting index
65912** entry is copied to register P3 and control falls through to the next
65913** instruction.
65914**
65915** See also: NotFound, NotExists, Found
65916*/
65917case OP_IsUnique: {        /* jump, in3 */
65918#if 0  /* local variables moved into u.bc */
65919  u16 ii;
65920  VdbeCursor *pCx;
65921  BtCursor *pCrsr;
65922  u16 nField;
65923  Mem *aMx;
65924  UnpackedRecord r;                  /* B-Tree index search key */
65925  i64 R;                             /* Rowid stored in register P3 */
65926#endif /* local variables moved into u.bc */
65927
65928  pIn3 = &aMem[pOp->p3];
65929  u.bc.aMx = &aMem[pOp->p4.i];
65930  /* Assert that the values of parameters P1 and P4 are in range. */
65931  assert( pOp->p4type==P4_INT32 );
65932  assert( pOp->p4.i>0 && pOp->p4.i<=p->nMem );
65933  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
65934
65935  /* Find the index cursor. */
65936  u.bc.pCx = p->apCsr[pOp->p1];
65937  assert( u.bc.pCx->deferredMoveto==0 );
65938  u.bc.pCx->seekResult = 0;
65939  u.bc.pCx->cacheStatus = CACHE_STALE;
65940  u.bc.pCrsr = u.bc.pCx->pCursor;
65941
65942  /* If any of the values are NULL, take the jump. */
65943  u.bc.nField = u.bc.pCx->pKeyInfo->nField;
65944  for(u.bc.ii=0; u.bc.ii<u.bc.nField; u.bc.ii++){
65945    if( u.bc.aMx[u.bc.ii].flags & MEM_Null ){
65946      pc = pOp->p2 - 1;
65947      u.bc.pCrsr = 0;
65948      break;
65949    }
65950  }
65951  assert( (u.bc.aMx[u.bc.nField].flags & MEM_Null)==0 );
65952
65953  if( u.bc.pCrsr!=0 ){
65954    /* Populate the index search key. */
65955    u.bc.r.pKeyInfo = u.bc.pCx->pKeyInfo;
65956    u.bc.r.nField = u.bc.nField + 1;
65957    u.bc.r.flags = UNPACKED_PREFIX_SEARCH;
65958    u.bc.r.aMem = u.bc.aMx;
65959#ifdef SQLITE_DEBUG
65960    { int i; for(i=0; i<u.bc.r.nField; i++) assert( memIsValid(&u.bc.r.aMem[i]) ); }
65961#endif
65962
65963    /* Extract the value of u.bc.R from register P3. */
65964    sqlite3VdbeMemIntegerify(pIn3);
65965    u.bc.R = pIn3->u.i;
65966
65967    /* Search the B-Tree index. If no conflicting record is found, jump
65968    ** to P2. Otherwise, copy the rowid of the conflicting record to
65969    ** register P3 and fall through to the next instruction.  */
65970    rc = sqlite3BtreeMovetoUnpacked(u.bc.pCrsr, &u.bc.r, 0, 0, &u.bc.pCx->seekResult);
65971    if( (u.bc.r.flags & UNPACKED_PREFIX_SEARCH) || u.bc.r.rowid==u.bc.R ){
65972      pc = pOp->p2 - 1;
65973    }else{
65974      pIn3->u.i = u.bc.r.rowid;
65975    }
65976  }
65977  break;
65978}
65979
65980/* Opcode: NotExists P1 P2 P3 * *
65981**
65982** Use the content of register P3 as a integer key.  If a record
65983** with that key does not exist in table of P1, then jump to P2.
65984** If the record does exist, then fall through.  The cursor is left
65985** pointing to the record if it exists.
65986**
65987** The difference between this operation and NotFound is that this
65988** operation assumes the key is an integer and that P1 is a table whereas
65989** NotFound assumes key is a blob constructed from MakeRecord and
65990** P1 is an index.
65991**
65992** See also: Found, NotFound, IsUnique
65993*/
65994case OP_NotExists: {        /* jump, in3 */
65995#if 0  /* local variables moved into u.bd */
65996  VdbeCursor *pC;
65997  BtCursor *pCrsr;
65998  int res;
65999  u64 iKey;
66000#endif /* local variables moved into u.bd */
66001
66002  pIn3 = &aMem[pOp->p3];
66003  assert( pIn3->flags & MEM_Int );
66004  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
66005  u.bd.pC = p->apCsr[pOp->p1];
66006  assert( u.bd.pC!=0 );
66007  assert( u.bd.pC->isTable );
66008  assert( u.bd.pC->pseudoTableReg==0 );
66009  u.bd.pCrsr = u.bd.pC->pCursor;
66010  if( u.bd.pCrsr!=0 ){
66011    u.bd.res = 0;
66012    u.bd.iKey = pIn3->u.i;
66013    rc = sqlite3BtreeMovetoUnpacked(u.bd.pCrsr, 0, u.bd.iKey, 0, &u.bd.res);
66014    u.bd.pC->lastRowid = pIn3->u.i;
66015    u.bd.pC->rowidIsValid = u.bd.res==0 ?1:0;
66016    u.bd.pC->nullRow = 0;
66017    u.bd.pC->cacheStatus = CACHE_STALE;
66018    u.bd.pC->deferredMoveto = 0;
66019    if( u.bd.res!=0 ){
66020      pc = pOp->p2 - 1;
66021      assert( u.bd.pC->rowidIsValid==0 );
66022    }
66023    u.bd.pC->seekResult = u.bd.res;
66024  }else{
66025    /* This happens when an attempt to open a read cursor on the
66026    ** sqlite_master table returns SQLITE_EMPTY.
66027    */
66028    pc = pOp->p2 - 1;
66029    assert( u.bd.pC->rowidIsValid==0 );
66030    u.bd.pC->seekResult = 0;
66031  }
66032  break;
66033}
66034
66035/* Opcode: Sequence P1 P2 * * *
66036**
66037** Find the next available sequence number for cursor P1.
66038** Write the sequence number into register P2.
66039** The sequence number on the cursor is incremented after this
66040** instruction.
66041*/
66042case OP_Sequence: {           /* out2-prerelease */
66043  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
66044  assert( p->apCsr[pOp->p1]!=0 );
66045  pOut->u.i = p->apCsr[pOp->p1]->seqCount++;
66046  break;
66047}
66048
66049
66050/* Opcode: NewRowid P1 P2 P3 * *
66051**
66052** Get a new integer record number (a.k.a "rowid") used as the key to a table.
66053** The record number is not previously used as a key in the database
66054** table that cursor P1 points to.  The new record number is written
66055** written to register P2.
66056**
66057** If P3>0 then P3 is a register in the root frame of this VDBE that holds
66058** the largest previously generated record number. No new record numbers are
66059** allowed to be less than this value. When this value reaches its maximum,
66060** a SQLITE_FULL error is generated. The P3 register is updated with the '
66061** generated record number. This P3 mechanism is used to help implement the
66062** AUTOINCREMENT feature.
66063*/
66064case OP_NewRowid: {           /* out2-prerelease */
66065#if 0  /* local variables moved into u.be */
66066  i64 v;                 /* The new rowid */
66067  VdbeCursor *pC;        /* Cursor of table to get the new rowid */
66068  int res;               /* Result of an sqlite3BtreeLast() */
66069  int cnt;               /* Counter to limit the number of searches */
66070  Mem *pMem;             /* Register holding largest rowid for AUTOINCREMENT */
66071  VdbeFrame *pFrame;     /* Root frame of VDBE */
66072#endif /* local variables moved into u.be */
66073
66074  u.be.v = 0;
66075  u.be.res = 0;
66076  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
66077  u.be.pC = p->apCsr[pOp->p1];
66078  assert( u.be.pC!=0 );
66079  if( NEVER(u.be.pC->pCursor==0) ){
66080    /* The zero initialization above is all that is needed */
66081  }else{
66082    /* The next rowid or record number (different terms for the same
66083    ** thing) is obtained in a two-step algorithm.
66084    **
66085    ** First we attempt to find the largest existing rowid and add one
66086    ** to that.  But if the largest existing rowid is already the maximum
66087    ** positive integer, we have to fall through to the second
66088    ** probabilistic algorithm
66089    **
66090    ** The second algorithm is to select a rowid at random and see if
66091    ** it already exists in the table.  If it does not exist, we have
66092    ** succeeded.  If the random rowid does exist, we select a new one
66093    ** and try again, up to 100 times.
66094    */
66095    assert( u.be.pC->isTable );
66096
66097#ifdef SQLITE_32BIT_ROWID
66098#   define MAX_ROWID 0x7fffffff
66099#else
66100    /* Some compilers complain about constants of the form 0x7fffffffffffffff.
66101    ** Others complain about 0x7ffffffffffffffffLL.  The following macro seems
66102    ** to provide the constant while making all compilers happy.
66103    */
66104#   define MAX_ROWID  (i64)( (((u64)0x7fffffff)<<32) | (u64)0xffffffff )
66105#endif
66106
66107    if( !u.be.pC->useRandomRowid ){
66108      u.be.v = sqlite3BtreeGetCachedRowid(u.be.pC->pCursor);
66109      if( u.be.v==0 ){
66110        rc = sqlite3BtreeLast(u.be.pC->pCursor, &u.be.res);
66111        if( rc!=SQLITE_OK ){
66112          goto abort_due_to_error;
66113        }
66114        if( u.be.res ){
66115          u.be.v = 1;   /* IMP: R-61914-48074 */
66116        }else{
66117          assert( sqlite3BtreeCursorIsValid(u.be.pC->pCursor) );
66118          rc = sqlite3BtreeKeySize(u.be.pC->pCursor, &u.be.v);
66119          assert( rc==SQLITE_OK );   /* Cannot fail following BtreeLast() */
66120          if( u.be.v==MAX_ROWID ){
66121            u.be.pC->useRandomRowid = 1;
66122          }else{
66123            u.be.v++;   /* IMP: R-29538-34987 */
66124          }
66125        }
66126      }
66127
66128#ifndef SQLITE_OMIT_AUTOINCREMENT
66129      if( pOp->p3 ){
66130        /* Assert that P3 is a valid memory cell. */
66131        assert( pOp->p3>0 );
66132        if( p->pFrame ){
66133          for(u.be.pFrame=p->pFrame; u.be.pFrame->pParent; u.be.pFrame=u.be.pFrame->pParent);
66134          /* Assert that P3 is a valid memory cell. */
66135          assert( pOp->p3<=u.be.pFrame->nMem );
66136          u.be.pMem = &u.be.pFrame->aMem[pOp->p3];
66137        }else{
66138          /* Assert that P3 is a valid memory cell. */
66139          assert( pOp->p3<=p->nMem );
66140          u.be.pMem = &aMem[pOp->p3];
66141          memAboutToChange(p, u.be.pMem);
66142        }
66143        assert( memIsValid(u.be.pMem) );
66144
66145        REGISTER_TRACE(pOp->p3, u.be.pMem);
66146        sqlite3VdbeMemIntegerify(u.be.pMem);
66147        assert( (u.be.pMem->flags & MEM_Int)!=0 );  /* mem(P3) holds an integer */
66148        if( u.be.pMem->u.i==MAX_ROWID || u.be.pC->useRandomRowid ){
66149          rc = SQLITE_FULL;   /* IMP: R-12275-61338 */
66150          goto abort_due_to_error;
66151        }
66152        if( u.be.v<u.be.pMem->u.i+1 ){
66153          u.be.v = u.be.pMem->u.i + 1;
66154        }
66155        u.be.pMem->u.i = u.be.v;
66156      }
66157#endif
66158
66159      sqlite3BtreeSetCachedRowid(u.be.pC->pCursor, u.be.v<MAX_ROWID ? u.be.v+1 : 0);
66160    }
66161    if( u.be.pC->useRandomRowid ){
66162      /* IMPLEMENTATION-OF: R-07677-41881 If the largest ROWID is equal to the
66163      ** largest possible integer (9223372036854775807) then the database
66164      ** engine starts picking positive candidate ROWIDs at random until
66165      ** it finds one that is not previously used. */
66166      assert( pOp->p3==0 );  /* We cannot be in random rowid mode if this is
66167                             ** an AUTOINCREMENT table. */
66168      /* on the first attempt, simply do one more than previous */
66169      u.be.v = db->lastRowid;
66170      u.be.v &= (MAX_ROWID>>1); /* ensure doesn't go negative */
66171      u.be.v++; /* ensure non-zero */
66172      u.be.cnt = 0;
66173      while(   ((rc = sqlite3BtreeMovetoUnpacked(u.be.pC->pCursor, 0, (u64)u.be.v,
66174                                                 0, &u.be.res))==SQLITE_OK)
66175            && (u.be.res==0)
66176            && (++u.be.cnt<100)){
66177        /* collision - try another random rowid */
66178        sqlite3_randomness(sizeof(u.be.v), &u.be.v);
66179        if( u.be.cnt<5 ){
66180          /* try "small" random rowids for the initial attempts */
66181          u.be.v &= 0xffffff;
66182        }else{
66183          u.be.v &= (MAX_ROWID>>1); /* ensure doesn't go negative */
66184        }
66185        u.be.v++; /* ensure non-zero */
66186      }
66187      if( rc==SQLITE_OK && u.be.res==0 ){
66188        rc = SQLITE_FULL;   /* IMP: R-38219-53002 */
66189        goto abort_due_to_error;
66190      }
66191      assert( u.be.v>0 );  /* EV: R-40812-03570 */
66192    }
66193    u.be.pC->rowidIsValid = 0;
66194    u.be.pC->deferredMoveto = 0;
66195    u.be.pC->cacheStatus = CACHE_STALE;
66196  }
66197  pOut->u.i = u.be.v;
66198  break;
66199}
66200
66201/* Opcode: Insert P1 P2 P3 P4 P5
66202**
66203** Write an entry into the table of cursor P1.  A new entry is
66204** created if it doesn't already exist or the data for an existing
66205** entry is overwritten.  The data is the value MEM_Blob stored in register
66206** number P2. The key is stored in register P3. The key must
66207** be a MEM_Int.
66208**
66209** If the OPFLAG_NCHANGE flag of P5 is set, then the row change count is
66210** incremented (otherwise not).  If the OPFLAG_LASTROWID flag of P5 is set,
66211** then rowid is stored for subsequent return by the
66212** sqlite3_last_insert_rowid() function (otherwise it is unmodified).
66213**
66214** If the OPFLAG_USESEEKRESULT flag of P5 is set and if the result of
66215** the last seek operation (OP_NotExists) was a success, then this
66216** operation will not attempt to find the appropriate row before doing
66217** the insert but will instead overwrite the row that the cursor is
66218** currently pointing to.  Presumably, the prior OP_NotExists opcode
66219** has already positioned the cursor correctly.  This is an optimization
66220** that boosts performance by avoiding redundant seeks.
66221**
66222** If the OPFLAG_ISUPDATE flag is set, then this opcode is part of an
66223** UPDATE operation.  Otherwise (if the flag is clear) then this opcode
66224** is part of an INSERT operation.  The difference is only important to
66225** the update hook.
66226**
66227** Parameter P4 may point to a string containing the table-name, or
66228** may be NULL. If it is not NULL, then the update-hook
66229** (sqlite3.xUpdateCallback) is invoked following a successful insert.
66230**
66231** (WARNING/TODO: If P1 is a pseudo-cursor and P2 is dynamically
66232** allocated, then ownership of P2 is transferred to the pseudo-cursor
66233** and register P2 becomes ephemeral.  If the cursor is changed, the
66234** value of register P2 will then change.  Make sure this does not
66235** cause any problems.)
66236**
66237** This instruction only works on tables.  The equivalent instruction
66238** for indices is OP_IdxInsert.
66239*/
66240/* Opcode: InsertInt P1 P2 P3 P4 P5
66241**
66242** This works exactly like OP_Insert except that the key is the
66243** integer value P3, not the value of the integer stored in register P3.
66244*/
66245case OP_Insert:
66246case OP_InsertInt: {
66247#if 0  /* local variables moved into u.bf */
66248  Mem *pData;       /* MEM cell holding data for the record to be inserted */
66249  Mem *pKey;        /* MEM cell holding key  for the record */
66250  i64 iKey;         /* The integer ROWID or key for the record to be inserted */
66251  VdbeCursor *pC;   /* Cursor to table into which insert is written */
66252  int nZero;        /* Number of zero-bytes to append */
66253  int seekResult;   /* Result of prior seek or 0 if no USESEEKRESULT flag */
66254  const char *zDb;  /* database name - used by the update hook */
66255  const char *zTbl; /* Table name - used by the opdate hook */
66256  int op;           /* Opcode for update hook: SQLITE_UPDATE or SQLITE_INSERT */
66257#endif /* local variables moved into u.bf */
66258
66259  u.bf.pData = &aMem[pOp->p2];
66260  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
66261  assert( memIsValid(u.bf.pData) );
66262  u.bf.pC = p->apCsr[pOp->p1];
66263  assert( u.bf.pC!=0 );
66264  assert( u.bf.pC->pCursor!=0 );
66265  assert( u.bf.pC->pseudoTableReg==0 );
66266  assert( u.bf.pC->isTable );
66267  REGISTER_TRACE(pOp->p2, u.bf.pData);
66268
66269  if( pOp->opcode==OP_Insert ){
66270    u.bf.pKey = &aMem[pOp->p3];
66271    assert( u.bf.pKey->flags & MEM_Int );
66272    assert( memIsValid(u.bf.pKey) );
66273    REGISTER_TRACE(pOp->p3, u.bf.pKey);
66274    u.bf.iKey = u.bf.pKey->u.i;
66275  }else{
66276    assert( pOp->opcode==OP_InsertInt );
66277    u.bf.iKey = pOp->p3;
66278  }
66279
66280  if( pOp->p5 & OPFLAG_NCHANGE ) p->nChange++;
66281  if( pOp->p5 & OPFLAG_LASTROWID ) db->lastRowid = u.bf.iKey;
66282  if( u.bf.pData->flags & MEM_Null ){
66283    u.bf.pData->z = 0;
66284    u.bf.pData->n = 0;
66285  }else{
66286    assert( u.bf.pData->flags & (MEM_Blob|MEM_Str) );
66287  }
66288  u.bf.seekResult = ((pOp->p5 & OPFLAG_USESEEKRESULT) ? u.bf.pC->seekResult : 0);
66289  if( u.bf.pData->flags & MEM_Zero ){
66290    u.bf.nZero = u.bf.pData->u.nZero;
66291  }else{
66292    u.bf.nZero = 0;
66293  }
66294  sqlite3BtreeSetCachedRowid(u.bf.pC->pCursor, 0);
66295  rc = sqlite3BtreeInsert(u.bf.pC->pCursor, 0, u.bf.iKey,
66296                          u.bf.pData->z, u.bf.pData->n, u.bf.nZero,
66297                          pOp->p5 & OPFLAG_APPEND, u.bf.seekResult
66298  );
66299  u.bf.pC->rowidIsValid = 0;
66300  u.bf.pC->deferredMoveto = 0;
66301  u.bf.pC->cacheStatus = CACHE_STALE;
66302
66303  /* Invoke the update-hook if required. */
66304  if( rc==SQLITE_OK && db->xUpdateCallback && pOp->p4.z ){
66305    u.bf.zDb = db->aDb[u.bf.pC->iDb].zName;
66306    u.bf.zTbl = pOp->p4.z;
66307    u.bf.op = ((pOp->p5 & OPFLAG_ISUPDATE) ? SQLITE_UPDATE : SQLITE_INSERT);
66308    assert( u.bf.pC->isTable );
66309    db->xUpdateCallback(db->pUpdateArg, u.bf.op, u.bf.zDb, u.bf.zTbl, u.bf.iKey);
66310    assert( u.bf.pC->iDb>=0 );
66311  }
66312  break;
66313}
66314
66315/* Opcode: Delete P1 P2 * P4 *
66316**
66317** Delete the record at which the P1 cursor is currently pointing.
66318**
66319** The cursor will be left pointing at either the next or the previous
66320** record in the table. If it is left pointing at the next record, then
66321** the next Next instruction will be a no-op.  Hence it is OK to delete
66322** a record from within an Next loop.
66323**
66324** If the OPFLAG_NCHANGE flag of P2 is set, then the row change count is
66325** incremented (otherwise not).
66326**
66327** P1 must not be pseudo-table.  It has to be a real table with
66328** multiple rows.
66329**
66330** If P4 is not NULL, then it is the name of the table that P1 is
66331** pointing to.  The update hook will be invoked, if it exists.
66332** If P4 is not NULL then the P1 cursor must have been positioned
66333** using OP_NotFound prior to invoking this opcode.
66334*/
66335case OP_Delete: {
66336#if 0  /* local variables moved into u.bg */
66337  i64 iKey;
66338  VdbeCursor *pC;
66339#endif /* local variables moved into u.bg */
66340
66341  u.bg.iKey = 0;
66342  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
66343  u.bg.pC = p->apCsr[pOp->p1];
66344  assert( u.bg.pC!=0 );
66345  assert( u.bg.pC->pCursor!=0 );  /* Only valid for real tables, no pseudotables */
66346
66347  /* If the update-hook will be invoked, set u.bg.iKey to the rowid of the
66348  ** row being deleted.
66349  */
66350  if( db->xUpdateCallback && pOp->p4.z ){
66351    assert( u.bg.pC->isTable );
66352    assert( u.bg.pC->rowidIsValid );  /* lastRowid set by previous OP_NotFound */
66353    u.bg.iKey = u.bg.pC->lastRowid;
66354  }
66355
66356  /* The OP_Delete opcode always follows an OP_NotExists or OP_Last or
66357  ** OP_Column on the same table without any intervening operations that
66358  ** might move or invalidate the cursor.  Hence cursor u.bg.pC is always pointing
66359  ** to the row to be deleted and the sqlite3VdbeCursorMoveto() operation
66360  ** below is always a no-op and cannot fail.  We will run it anyhow, though,
66361  ** to guard against future changes to the code generator.
66362  **/
66363  assert( u.bg.pC->deferredMoveto==0 );
66364  rc = sqlite3VdbeCursorMoveto(u.bg.pC);
66365  if( NEVER(rc!=SQLITE_OK) ) goto abort_due_to_error;
66366
66367  sqlite3BtreeSetCachedRowid(u.bg.pC->pCursor, 0);
66368  rc = sqlite3BtreeDelete(u.bg.pC->pCursor);
66369  u.bg.pC->cacheStatus = CACHE_STALE;
66370
66371  /* Invoke the update-hook if required. */
66372  if( rc==SQLITE_OK && db->xUpdateCallback && pOp->p4.z ){
66373    const char *zDb = db->aDb[u.bg.pC->iDb].zName;
66374    const char *zTbl = pOp->p4.z;
66375    db->xUpdateCallback(db->pUpdateArg, SQLITE_DELETE, zDb, zTbl, u.bg.iKey);
66376    assert( u.bg.pC->iDb>=0 );
66377  }
66378  if( pOp->p2 & OPFLAG_NCHANGE ) p->nChange++;
66379  break;
66380}
66381/* Opcode: ResetCount * * * * *
66382**
66383** The value of the change counter is copied to the database handle
66384** change counter (returned by subsequent calls to sqlite3_changes()).
66385** Then the VMs internal change counter resets to 0.
66386** This is used by trigger programs.
66387*/
66388case OP_ResetCount: {
66389  sqlite3VdbeSetChanges(db, p->nChange);
66390  p->nChange = 0;
66391  break;
66392}
66393
66394/* Opcode: RowData P1 P2 * * *
66395**
66396** Write into register P2 the complete row data for cursor P1.
66397** There is no interpretation of the data.
66398** It is just copied onto the P2 register exactly as
66399** it is found in the database file.
66400**
66401** If the P1 cursor must be pointing to a valid row (not a NULL row)
66402** of a real table, not a pseudo-table.
66403*/
66404/* Opcode: RowKey P1 P2 * * *
66405**
66406** Write into register P2 the complete row key for cursor P1.
66407** There is no interpretation of the data.
66408** The key is copied onto the P3 register exactly as
66409** it is found in the database file.
66410**
66411** If the P1 cursor must be pointing to a valid row (not a NULL row)
66412** of a real table, not a pseudo-table.
66413*/
66414case OP_RowKey:
66415case OP_RowData: {
66416#if 0  /* local variables moved into u.bh */
66417  VdbeCursor *pC;
66418  BtCursor *pCrsr;
66419  u32 n;
66420  i64 n64;
66421#endif /* local variables moved into u.bh */
66422
66423  pOut = &aMem[pOp->p2];
66424  memAboutToChange(p, pOut);
66425
66426  /* Note that RowKey and RowData are really exactly the same instruction */
66427  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
66428  u.bh.pC = p->apCsr[pOp->p1];
66429  assert( u.bh.pC->isTable || pOp->opcode==OP_RowKey );
66430  assert( u.bh.pC->isIndex || pOp->opcode==OP_RowData );
66431  assert( u.bh.pC!=0 );
66432  assert( u.bh.pC->nullRow==0 );
66433  assert( u.bh.pC->pseudoTableReg==0 );
66434  assert( u.bh.pC->pCursor!=0 );
66435  u.bh.pCrsr = u.bh.pC->pCursor;
66436  assert( sqlite3BtreeCursorIsValid(u.bh.pCrsr) );
66437
66438  /* The OP_RowKey and OP_RowData opcodes always follow OP_NotExists or
66439  ** OP_Rewind/Op_Next with no intervening instructions that might invalidate
66440  ** the cursor.  Hence the following sqlite3VdbeCursorMoveto() call is always
66441  ** a no-op and can never fail.  But we leave it in place as a safety.
66442  */
66443  assert( u.bh.pC->deferredMoveto==0 );
66444  rc = sqlite3VdbeCursorMoveto(u.bh.pC);
66445  if( NEVER(rc!=SQLITE_OK) ) goto abort_due_to_error;
66446
66447  if( u.bh.pC->isIndex ){
66448    assert( !u.bh.pC->isTable );
66449    rc = sqlite3BtreeKeySize(u.bh.pCrsr, &u.bh.n64);
66450    assert( rc==SQLITE_OK );    /* True because of CursorMoveto() call above */
66451    if( u.bh.n64>db->aLimit[SQLITE_LIMIT_LENGTH] ){
66452      goto too_big;
66453    }
66454    u.bh.n = (u32)u.bh.n64;
66455  }else{
66456    rc = sqlite3BtreeDataSize(u.bh.pCrsr, &u.bh.n);
66457    assert( rc==SQLITE_OK );    /* DataSize() cannot fail */
66458    if( u.bh.n>(u32)db->aLimit[SQLITE_LIMIT_LENGTH] ){
66459      goto too_big;
66460    }
66461  }
66462  if( sqlite3VdbeMemGrow(pOut, u.bh.n, 0) ){
66463    goto no_mem;
66464  }
66465  pOut->n = u.bh.n;
66466  MemSetTypeFlag(pOut, MEM_Blob);
66467  if( u.bh.pC->isIndex ){
66468    rc = sqlite3BtreeKey(u.bh.pCrsr, 0, u.bh.n, pOut->z);
66469  }else{
66470    rc = sqlite3BtreeData(u.bh.pCrsr, 0, u.bh.n, pOut->z);
66471  }
66472  pOut->enc = SQLITE_UTF8;  /* In case the blob is ever cast to text */
66473  UPDATE_MAX_BLOBSIZE(pOut);
66474  break;
66475}
66476
66477/* Opcode: Rowid P1 P2 * * *
66478**
66479** Store in register P2 an integer which is the key of the table entry that
66480** P1 is currently point to.
66481**
66482** P1 can be either an ordinary table or a virtual table.  There used to
66483** be a separate OP_VRowid opcode for use with virtual tables, but this
66484** one opcode now works for both table types.
66485*/
66486case OP_Rowid: {                 /* out2-prerelease */
66487#if 0  /* local variables moved into u.bi */
66488  VdbeCursor *pC;
66489  i64 v;
66490  sqlite3_vtab *pVtab;
66491  const sqlite3_module *pModule;
66492#endif /* local variables moved into u.bi */
66493
66494  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
66495  u.bi.pC = p->apCsr[pOp->p1];
66496  assert( u.bi.pC!=0 );
66497  assert( u.bi.pC->pseudoTableReg==0 );
66498  if( u.bi.pC->nullRow ){
66499    pOut->flags = MEM_Null;
66500    break;
66501  }else if( u.bi.pC->deferredMoveto ){
66502    u.bi.v = u.bi.pC->movetoTarget;
66503#ifndef SQLITE_OMIT_VIRTUALTABLE
66504  }else if( u.bi.pC->pVtabCursor ){
66505    u.bi.pVtab = u.bi.pC->pVtabCursor->pVtab;
66506    u.bi.pModule = u.bi.pVtab->pModule;
66507    assert( u.bi.pModule->xRowid );
66508    rc = u.bi.pModule->xRowid(u.bi.pC->pVtabCursor, &u.bi.v);
66509    importVtabErrMsg(p, u.bi.pVtab);
66510#endif /* SQLITE_OMIT_VIRTUALTABLE */
66511  }else{
66512    assert( u.bi.pC->pCursor!=0 );
66513    rc = sqlite3VdbeCursorMoveto(u.bi.pC);
66514    if( rc ) goto abort_due_to_error;
66515    if( u.bi.pC->rowidIsValid ){
66516      u.bi.v = u.bi.pC->lastRowid;
66517    }else{
66518      rc = sqlite3BtreeKeySize(u.bi.pC->pCursor, &u.bi.v);
66519      assert( rc==SQLITE_OK );  /* Always so because of CursorMoveto() above */
66520    }
66521  }
66522  pOut->u.i = u.bi.v;
66523  break;
66524}
66525
66526/* Opcode: NullRow P1 * * * *
66527**
66528** Move the cursor P1 to a null row.  Any OP_Column operations
66529** that occur while the cursor is on the null row will always
66530** write a NULL.
66531*/
66532case OP_NullRow: {
66533#if 0  /* local variables moved into u.bj */
66534  VdbeCursor *pC;
66535#endif /* local variables moved into u.bj */
66536
66537  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
66538  u.bj.pC = p->apCsr[pOp->p1];
66539  assert( u.bj.pC!=0 );
66540  u.bj.pC->nullRow = 1;
66541  u.bj.pC->rowidIsValid = 0;
66542  if( u.bj.pC->pCursor ){
66543    sqlite3BtreeClearCursor(u.bj.pC->pCursor);
66544  }
66545  break;
66546}
66547
66548/* Opcode: Last P1 P2 * * *
66549**
66550** The next use of the Rowid or Column or Next instruction for P1
66551** will refer to the last entry in the database table or index.
66552** If the table or index is empty and P2>0, then jump immediately to P2.
66553** If P2 is 0 or if the table or index is not empty, fall through
66554** to the following instruction.
66555*/
66556case OP_Last: {        /* jump */
66557#if 0  /* local variables moved into u.bk */
66558  VdbeCursor *pC;
66559  BtCursor *pCrsr;
66560  int res;
66561#endif /* local variables moved into u.bk */
66562
66563  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
66564  u.bk.pC = p->apCsr[pOp->p1];
66565  assert( u.bk.pC!=0 );
66566  u.bk.pCrsr = u.bk.pC->pCursor;
66567  if( u.bk.pCrsr==0 ){
66568    u.bk.res = 1;
66569  }else{
66570    rc = sqlite3BtreeLast(u.bk.pCrsr, &u.bk.res);
66571  }
66572  u.bk.pC->nullRow = (u8)u.bk.res;
66573  u.bk.pC->deferredMoveto = 0;
66574  u.bk.pC->rowidIsValid = 0;
66575  u.bk.pC->cacheStatus = CACHE_STALE;
66576  if( pOp->p2>0 && u.bk.res ){
66577    pc = pOp->p2 - 1;
66578  }
66579  break;
66580}
66581
66582
66583/* Opcode: Sort P1 P2 * * *
66584**
66585** This opcode does exactly the same thing as OP_Rewind except that
66586** it increments an undocumented global variable used for testing.
66587**
66588** Sorting is accomplished by writing records into a sorting index,
66589** then rewinding that index and playing it back from beginning to
66590** end.  We use the OP_Sort opcode instead of OP_Rewind to do the
66591** rewinding so that the global variable will be incremented and
66592** regression tests can determine whether or not the optimizer is
66593** correctly optimizing out sorts.
66594*/
66595case OP_Sort: {        /* jump */
66596#ifdef SQLITE_TEST
66597  sqlite3_sort_count++;
66598  sqlite3_search_count--;
66599#endif
66600  p->aCounter[SQLITE_STMTSTATUS_SORT-1]++;
66601  /* Fall through into OP_Rewind */
66602}
66603/* Opcode: Rewind P1 P2 * * *
66604**
66605** The next use of the Rowid or Column or Next instruction for P1
66606** will refer to the first entry in the database table or index.
66607** If the table or index is empty and P2>0, then jump immediately to P2.
66608** If P2 is 0 or if the table or index is not empty, fall through
66609** to the following instruction.
66610*/
66611case OP_Rewind: {        /* jump */
66612#if 0  /* local variables moved into u.bl */
66613  VdbeCursor *pC;
66614  BtCursor *pCrsr;
66615  int res;
66616#endif /* local variables moved into u.bl */
66617
66618  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
66619  u.bl.pC = p->apCsr[pOp->p1];
66620  assert( u.bl.pC!=0 );
66621  u.bl.res = 1;
66622  if( (u.bl.pCrsr = u.bl.pC->pCursor)!=0 ){
66623    rc = sqlite3BtreeFirst(u.bl.pCrsr, &u.bl.res);
66624    u.bl.pC->atFirst = u.bl.res==0 ?1:0;
66625    u.bl.pC->deferredMoveto = 0;
66626    u.bl.pC->cacheStatus = CACHE_STALE;
66627    u.bl.pC->rowidIsValid = 0;
66628  }
66629  u.bl.pC->nullRow = (u8)u.bl.res;
66630  assert( pOp->p2>0 && pOp->p2<p->nOp );
66631  if( u.bl.res ){
66632    pc = pOp->p2 - 1;
66633  }
66634  break;
66635}
66636
66637/* Opcode: Next P1 P2 * * P5
66638**
66639** Advance cursor P1 so that it points to the next key/data pair in its
66640** table or index.  If there are no more key/value pairs then fall through
66641** to the following instruction.  But if the cursor advance was successful,
66642** jump immediately to P2.
66643**
66644** The P1 cursor must be for a real table, not a pseudo-table.
66645**
66646** If P5 is positive and the jump is taken, then event counter
66647** number P5-1 in the prepared statement is incremented.
66648**
66649** See also: Prev
66650*/
66651/* Opcode: Prev P1 P2 * * P5
66652**
66653** Back up cursor P1 so that it points to the previous key/data pair in its
66654** table or index.  If there is no previous key/value pairs then fall through
66655** to the following instruction.  But if the cursor backup was successful,
66656** jump immediately to P2.
66657**
66658** The P1 cursor must be for a real table, not a pseudo-table.
66659**
66660** If P5 is positive and the jump is taken, then event counter
66661** number P5-1 in the prepared statement is incremented.
66662*/
66663case OP_Prev:          /* jump */
66664case OP_Next: {        /* jump */
66665#if 0  /* local variables moved into u.bm */
66666  VdbeCursor *pC;
66667  BtCursor *pCrsr;
66668  int res;
66669#endif /* local variables moved into u.bm */
66670
66671  CHECK_FOR_INTERRUPT;
66672  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
66673  assert( pOp->p5<=ArraySize(p->aCounter) );
66674  u.bm.pC = p->apCsr[pOp->p1];
66675  if( u.bm.pC==0 ){
66676    break;  /* See ticket #2273 */
66677  }
66678  u.bm.pCrsr = u.bm.pC->pCursor;
66679  if( u.bm.pCrsr==0 ){
66680    u.bm.pC->nullRow = 1;
66681    break;
66682  }
66683  u.bm.res = 1;
66684  assert( u.bm.pC->deferredMoveto==0 );
66685  rc = pOp->opcode==OP_Next ? sqlite3BtreeNext(u.bm.pCrsr, &u.bm.res) :
66686                              sqlite3BtreePrevious(u.bm.pCrsr, &u.bm.res);
66687  u.bm.pC->nullRow = (u8)u.bm.res;
66688  u.bm.pC->cacheStatus = CACHE_STALE;
66689  if( u.bm.res==0 ){
66690    pc = pOp->p2 - 1;
66691    if( pOp->p5 ) p->aCounter[pOp->p5-1]++;
66692#ifdef SQLITE_TEST
66693    sqlite3_search_count++;
66694#endif
66695  }
66696  u.bm.pC->rowidIsValid = 0;
66697  break;
66698}
66699
66700/* Opcode: IdxInsert P1 P2 P3 * P5
66701**
66702** Register P2 holds a SQL index key made using the
66703** MakeRecord instructions.  This opcode writes that key
66704** into the index P1.  Data for the entry is nil.
66705**
66706** P3 is a flag that provides a hint to the b-tree layer that this
66707** insert is likely to be an append.
66708**
66709** This instruction only works for indices.  The equivalent instruction
66710** for tables is OP_Insert.
66711*/
66712case OP_IdxInsert: {        /* in2 */
66713#if 0  /* local variables moved into u.bn */
66714  VdbeCursor *pC;
66715  BtCursor *pCrsr;
66716  int nKey;
66717  const char *zKey;
66718#endif /* local variables moved into u.bn */
66719
66720  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
66721  u.bn.pC = p->apCsr[pOp->p1];
66722  assert( u.bn.pC!=0 );
66723  pIn2 = &aMem[pOp->p2];
66724  assert( pIn2->flags & MEM_Blob );
66725  u.bn.pCrsr = u.bn.pC->pCursor;
66726  if( ALWAYS(u.bn.pCrsr!=0) ){
66727    assert( u.bn.pC->isTable==0 );
66728    rc = ExpandBlob(pIn2);
66729    if( rc==SQLITE_OK ){
66730      u.bn.nKey = pIn2->n;
66731      u.bn.zKey = pIn2->z;
66732      rc = sqlite3BtreeInsert(u.bn.pCrsr, u.bn.zKey, u.bn.nKey, "", 0, 0, pOp->p3,
66733          ((pOp->p5 & OPFLAG_USESEEKRESULT) ? u.bn.pC->seekResult : 0)
66734      );
66735      assert( u.bn.pC->deferredMoveto==0 );
66736      u.bn.pC->cacheStatus = CACHE_STALE;
66737    }
66738  }
66739  break;
66740}
66741
66742/* Opcode: IdxDelete P1 P2 P3 * *
66743**
66744** The content of P3 registers starting at register P2 form
66745** an unpacked index key. This opcode removes that entry from the
66746** index opened by cursor P1.
66747*/
66748case OP_IdxDelete: {
66749#if 0  /* local variables moved into u.bo */
66750  VdbeCursor *pC;
66751  BtCursor *pCrsr;
66752  int res;
66753  UnpackedRecord r;
66754#endif /* local variables moved into u.bo */
66755
66756  assert( pOp->p3>0 );
66757  assert( pOp->p2>0 && pOp->p2+pOp->p3<=p->nMem+1 );
66758  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
66759  u.bo.pC = p->apCsr[pOp->p1];
66760  assert( u.bo.pC!=0 );
66761  u.bo.pCrsr = u.bo.pC->pCursor;
66762  if( ALWAYS(u.bo.pCrsr!=0) ){
66763    u.bo.r.pKeyInfo = u.bo.pC->pKeyInfo;
66764    u.bo.r.nField = (u16)pOp->p3;
66765    u.bo.r.flags = 0;
66766    u.bo.r.aMem = &aMem[pOp->p2];
66767#ifdef SQLITE_DEBUG
66768    { int i; for(i=0; i<u.bo.r.nField; i++) assert( memIsValid(&u.bo.r.aMem[i]) ); }
66769#endif
66770    rc = sqlite3BtreeMovetoUnpacked(u.bo.pCrsr, &u.bo.r, 0, 0, &u.bo.res);
66771    if( rc==SQLITE_OK && u.bo.res==0 ){
66772      rc = sqlite3BtreeDelete(u.bo.pCrsr);
66773    }
66774    assert( u.bo.pC->deferredMoveto==0 );
66775    u.bo.pC->cacheStatus = CACHE_STALE;
66776  }
66777  break;
66778}
66779
66780/* Opcode: IdxRowid P1 P2 * * *
66781**
66782** Write into register P2 an integer which is the last entry in the record at
66783** the end of the index key pointed to by cursor P1.  This integer should be
66784** the rowid of the table entry to which this index entry points.
66785**
66786** See also: Rowid, MakeRecord.
66787*/
66788case OP_IdxRowid: {              /* out2-prerelease */
66789#if 0  /* local variables moved into u.bp */
66790  BtCursor *pCrsr;
66791  VdbeCursor *pC;
66792  i64 rowid;
66793#endif /* local variables moved into u.bp */
66794
66795  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
66796  u.bp.pC = p->apCsr[pOp->p1];
66797  assert( u.bp.pC!=0 );
66798  u.bp.pCrsr = u.bp.pC->pCursor;
66799  pOut->flags = MEM_Null;
66800  if( ALWAYS(u.bp.pCrsr!=0) ){
66801    rc = sqlite3VdbeCursorMoveto(u.bp.pC);
66802    if( NEVER(rc) ) goto abort_due_to_error;
66803    assert( u.bp.pC->deferredMoveto==0 );
66804    assert( u.bp.pC->isTable==0 );
66805    if( !u.bp.pC->nullRow ){
66806      rc = sqlite3VdbeIdxRowid(db, u.bp.pCrsr, &u.bp.rowid);
66807      if( rc!=SQLITE_OK ){
66808        goto abort_due_to_error;
66809      }
66810      pOut->u.i = u.bp.rowid;
66811      pOut->flags = MEM_Int;
66812    }
66813  }
66814  break;
66815}
66816
66817/* Opcode: IdxGE P1 P2 P3 P4 P5
66818**
66819** The P4 register values beginning with P3 form an unpacked index
66820** key that omits the ROWID.  Compare this key value against the index
66821** that P1 is currently pointing to, ignoring the ROWID on the P1 index.
66822**
66823** If the P1 index entry is greater than or equal to the key value
66824** then jump to P2.  Otherwise fall through to the next instruction.
66825**
66826** If P5 is non-zero then the key value is increased by an epsilon
66827** prior to the comparison.  This make the opcode work like IdxGT except
66828** that if the key from register P3 is a prefix of the key in the cursor,
66829** the result is false whereas it would be true with IdxGT.
66830*/
66831/* Opcode: IdxLT P1 P2 P3 P4 P5
66832**
66833** The P4 register values beginning with P3 form an unpacked index
66834** key that omits the ROWID.  Compare this key value against the index
66835** that P1 is currently pointing to, ignoring the ROWID on the P1 index.
66836**
66837** If the P1 index entry is less than the key value then jump to P2.
66838** Otherwise fall through to the next instruction.
66839**
66840** If P5 is non-zero then the key value is increased by an epsilon prior
66841** to the comparison.  This makes the opcode work like IdxLE.
66842*/
66843case OP_IdxLT:          /* jump */
66844case OP_IdxGE: {        /* jump */
66845#if 0  /* local variables moved into u.bq */
66846  VdbeCursor *pC;
66847  int res;
66848  UnpackedRecord r;
66849#endif /* local variables moved into u.bq */
66850
66851  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
66852  u.bq.pC = p->apCsr[pOp->p1];
66853  assert( u.bq.pC!=0 );
66854  assert( u.bq.pC->isOrdered );
66855  if( ALWAYS(u.bq.pC->pCursor!=0) ){
66856    assert( u.bq.pC->deferredMoveto==0 );
66857    assert( pOp->p5==0 || pOp->p5==1 );
66858    assert( pOp->p4type==P4_INT32 );
66859    u.bq.r.pKeyInfo = u.bq.pC->pKeyInfo;
66860    u.bq.r.nField = (u16)pOp->p4.i;
66861    if( pOp->p5 ){
66862      u.bq.r.flags = UNPACKED_INCRKEY | UNPACKED_IGNORE_ROWID;
66863    }else{
66864      u.bq.r.flags = UNPACKED_IGNORE_ROWID;
66865    }
66866    u.bq.r.aMem = &aMem[pOp->p3];
66867#ifdef SQLITE_DEBUG
66868    { int i; for(i=0; i<u.bq.r.nField; i++) assert( memIsValid(&u.bq.r.aMem[i]) ); }
66869#endif
66870    rc = sqlite3VdbeIdxKeyCompare(u.bq.pC, &u.bq.r, &u.bq.res);
66871    if( pOp->opcode==OP_IdxLT ){
66872      u.bq.res = -u.bq.res;
66873    }else{
66874      assert( pOp->opcode==OP_IdxGE );
66875      u.bq.res++;
66876    }
66877    if( u.bq.res>0 ){
66878      pc = pOp->p2 - 1 ;
66879    }
66880  }
66881  break;
66882}
66883
66884/* Opcode: Destroy P1 P2 P3 * *
66885**
66886** Delete an entire database table or index whose root page in the database
66887** file is given by P1.
66888**
66889** The table being destroyed is in the main database file if P3==0.  If
66890** P3==1 then the table to be clear is in the auxiliary database file
66891** that is used to store tables create using CREATE TEMPORARY TABLE.
66892**
66893** If AUTOVACUUM is enabled then it is possible that another root page
66894** might be moved into the newly deleted root page in order to keep all
66895** root pages contiguous at the beginning of the database.  The former
66896** value of the root page that moved - its value before the move occurred -
66897** is stored in register P2.  If no page
66898** movement was required (because the table being dropped was already
66899** the last one in the database) then a zero is stored in register P2.
66900** If AUTOVACUUM is disabled then a zero is stored in register P2.
66901**
66902** See also: Clear
66903*/
66904case OP_Destroy: {     /* out2-prerelease */
66905#if 0  /* local variables moved into u.br */
66906  int iMoved;
66907  int iCnt;
66908  Vdbe *pVdbe;
66909  int iDb;
66910#endif /* local variables moved into u.br */
66911#ifndef SQLITE_OMIT_VIRTUALTABLE
66912  u.br.iCnt = 0;
66913  for(u.br.pVdbe=db->pVdbe; u.br.pVdbe; u.br.pVdbe = u.br.pVdbe->pNext){
66914    if( u.br.pVdbe->magic==VDBE_MAGIC_RUN && u.br.pVdbe->inVtabMethod<2 && u.br.pVdbe->pc>=0 ){
66915      u.br.iCnt++;
66916    }
66917  }
66918#else
66919  u.br.iCnt = db->activeVdbeCnt;
66920#endif
66921  pOut->flags = MEM_Null;
66922  if( u.br.iCnt>1 ){
66923    rc = SQLITE_LOCKED;
66924    p->errorAction = OE_Abort;
66925  }else{
66926    u.br.iDb = pOp->p3;
66927    assert( u.br.iCnt==1 );
66928    assert( (p->btreeMask & (((yDbMask)1)<<u.br.iDb))!=0 );
66929    rc = sqlite3BtreeDropTable(db->aDb[u.br.iDb].pBt, pOp->p1, &u.br.iMoved);
66930    pOut->flags = MEM_Int;
66931    pOut->u.i = u.br.iMoved;
66932#ifndef SQLITE_OMIT_AUTOVACUUM
66933    if( rc==SQLITE_OK && u.br.iMoved!=0 ){
66934      sqlite3RootPageMoved(db, u.br.iDb, u.br.iMoved, pOp->p1);
66935      /* All OP_Destroy operations occur on the same btree */
66936      assert( resetSchemaOnFault==0 || resetSchemaOnFault==u.br.iDb+1 );
66937      resetSchemaOnFault = u.br.iDb+1;
66938    }
66939#endif
66940  }
66941  break;
66942}
66943
66944/* Opcode: Clear P1 P2 P3
66945**
66946** Delete all contents of the database table or index whose root page
66947** in the database file is given by P1.  But, unlike Destroy, do not
66948** remove the table or index from the database file.
66949**
66950** The table being clear is in the main database file if P2==0.  If
66951** P2==1 then the table to be clear is in the auxiliary database file
66952** that is used to store tables create using CREATE TEMPORARY TABLE.
66953**
66954** If the P3 value is non-zero, then the table referred to must be an
66955** intkey table (an SQL table, not an index). In this case the row change
66956** count is incremented by the number of rows in the table being cleared.
66957** If P3 is greater than zero, then the value stored in register P3 is
66958** also incremented by the number of rows in the table being cleared.
66959**
66960** See also: Destroy
66961*/
66962case OP_Clear: {
66963#if 0  /* local variables moved into u.bs */
66964  int nChange;
66965#endif /* local variables moved into u.bs */
66966
66967  u.bs.nChange = 0;
66968  assert( (p->btreeMask & (((yDbMask)1)<<pOp->p2))!=0 );
66969  rc = sqlite3BtreeClearTable(
66970      db->aDb[pOp->p2].pBt, pOp->p1, (pOp->p3 ? &u.bs.nChange : 0)
66971  );
66972  if( pOp->p3 ){
66973    p->nChange += u.bs.nChange;
66974    if( pOp->p3>0 ){
66975      assert( memIsValid(&aMem[pOp->p3]) );
66976      memAboutToChange(p, &aMem[pOp->p3]);
66977      aMem[pOp->p3].u.i += u.bs.nChange;
66978    }
66979  }
66980  break;
66981}
66982
66983/* Opcode: CreateTable P1 P2 * * *
66984**
66985** Allocate a new table in the main database file if P1==0 or in the
66986** auxiliary database file if P1==1 or in an attached database if
66987** P1>1.  Write the root page number of the new table into
66988** register P2
66989**
66990** The difference between a table and an index is this:  A table must
66991** have a 4-byte integer key and can have arbitrary data.  An index
66992** has an arbitrary key but no data.
66993**
66994** See also: CreateIndex
66995*/
66996/* Opcode: CreateIndex P1 P2 * * *
66997**
66998** Allocate a new index in the main database file if P1==0 or in the
66999** auxiliary database file if P1==1 or in an attached database if
67000** P1>1.  Write the root page number of the new table into
67001** register P2.
67002**
67003** See documentation on OP_CreateTable for additional information.
67004*/
67005case OP_CreateIndex:            /* out2-prerelease */
67006case OP_CreateTable: {          /* out2-prerelease */
67007#if 0  /* local variables moved into u.bt */
67008  int pgno;
67009  int flags;
67010  Db *pDb;
67011#endif /* local variables moved into u.bt */
67012
67013  u.bt.pgno = 0;
67014  assert( pOp->p1>=0 && pOp->p1<db->nDb );
67015  assert( (p->btreeMask & (((yDbMask)1)<<pOp->p1))!=0 );
67016  u.bt.pDb = &db->aDb[pOp->p1];
67017  assert( u.bt.pDb->pBt!=0 );
67018  if( pOp->opcode==OP_CreateTable ){
67019    /* u.bt.flags = BTREE_INTKEY; */
67020    u.bt.flags = BTREE_INTKEY;
67021  }else{
67022    u.bt.flags = BTREE_BLOBKEY;
67023  }
67024  rc = sqlite3BtreeCreateTable(u.bt.pDb->pBt, &u.bt.pgno, u.bt.flags);
67025  pOut->u.i = u.bt.pgno;
67026  break;
67027}
67028
67029/* Opcode: ParseSchema P1 * * P4 *
67030**
67031** Read and parse all entries from the SQLITE_MASTER table of database P1
67032** that match the WHERE clause P4.
67033**
67034** This opcode invokes the parser to create a new virtual machine,
67035** then runs the new virtual machine.  It is thus a re-entrant opcode.
67036*/
67037case OP_ParseSchema: {
67038#if 0  /* local variables moved into u.bu */
67039  int iDb;
67040  const char *zMaster;
67041  char *zSql;
67042  InitData initData;
67043#endif /* local variables moved into u.bu */
67044
67045  /* Any prepared statement that invokes this opcode will hold mutexes
67046  ** on every btree.  This is a prerequisite for invoking
67047  ** sqlite3InitCallback().
67048  */
67049#ifdef SQLITE_DEBUG
67050  for(u.bu.iDb=0; u.bu.iDb<db->nDb; u.bu.iDb++){
67051    assert( u.bu.iDb==1 || sqlite3BtreeHoldsMutex(db->aDb[u.bu.iDb].pBt) );
67052  }
67053#endif
67054
67055  u.bu.iDb = pOp->p1;
67056  assert( u.bu.iDb>=0 && u.bu.iDb<db->nDb );
67057  assert( DbHasProperty(db, u.bu.iDb, DB_SchemaLoaded) );
67058  /* Used to be a conditional */ {
67059    u.bu.zMaster = SCHEMA_TABLE(u.bu.iDb);
67060    u.bu.initData.db = db;
67061    u.bu.initData.iDb = pOp->p1;
67062    u.bu.initData.pzErrMsg = &p->zErrMsg;
67063    u.bu.zSql = sqlite3MPrintf(db,
67064       "SELECT name, rootpage, sql FROM '%q'.%s WHERE %s ORDER BY rowid",
67065       db->aDb[u.bu.iDb].zName, u.bu.zMaster, pOp->p4.z);
67066    if( u.bu.zSql==0 ){
67067      rc = SQLITE_NOMEM;
67068    }else{
67069      assert( db->init.busy==0 );
67070      db->init.busy = 1;
67071      u.bu.initData.rc = SQLITE_OK;
67072      assert( !db->mallocFailed );
67073      rc = sqlite3_exec(db, u.bu.zSql, sqlite3InitCallback, &u.bu.initData, 0);
67074      if( rc==SQLITE_OK ) rc = u.bu.initData.rc;
67075      sqlite3DbFree(db, u.bu.zSql);
67076      db->init.busy = 0;
67077    }
67078  }
67079  if( rc==SQLITE_NOMEM ){
67080    goto no_mem;
67081  }
67082  break;
67083}
67084
67085#if !defined(SQLITE_OMIT_ANALYZE)
67086/* Opcode: LoadAnalysis P1 * * * *
67087**
67088** Read the sqlite_stat1 table for database P1 and load the content
67089** of that table into the internal index hash table.  This will cause
67090** the analysis to be used when preparing all subsequent queries.
67091*/
67092case OP_LoadAnalysis: {
67093  assert( pOp->p1>=0 && pOp->p1<db->nDb );
67094  rc = sqlite3AnalysisLoad(db, pOp->p1);
67095  break;
67096}
67097#endif /* !defined(SQLITE_OMIT_ANALYZE) */
67098
67099/* Opcode: DropTable P1 * * P4 *
67100**
67101** Remove the internal (in-memory) data structures that describe
67102** the table named P4 in database P1.  This is called after a table
67103** is dropped in order to keep the internal representation of the
67104** schema consistent with what is on disk.
67105*/
67106case OP_DropTable: {
67107  sqlite3UnlinkAndDeleteTable(db, pOp->p1, pOp->p4.z);
67108  break;
67109}
67110
67111/* Opcode: DropIndex P1 * * P4 *
67112**
67113** Remove the internal (in-memory) data structures that describe
67114** the index named P4 in database P1.  This is called after an index
67115** is dropped in order to keep the internal representation of the
67116** schema consistent with what is on disk.
67117*/
67118case OP_DropIndex: {
67119  sqlite3UnlinkAndDeleteIndex(db, pOp->p1, pOp->p4.z);
67120  break;
67121}
67122
67123/* Opcode: DropTrigger P1 * * P4 *
67124**
67125** Remove the internal (in-memory) data structures that describe
67126** the trigger named P4 in database P1.  This is called after a trigger
67127** is dropped in order to keep the internal representation of the
67128** schema consistent with what is on disk.
67129*/
67130case OP_DropTrigger: {
67131  sqlite3UnlinkAndDeleteTrigger(db, pOp->p1, pOp->p4.z);
67132  break;
67133}
67134
67135
67136#ifndef SQLITE_OMIT_INTEGRITY_CHECK
67137/* Opcode: IntegrityCk P1 P2 P3 * P5
67138**
67139** Do an analysis of the currently open database.  Store in
67140** register P1 the text of an error message describing any problems.
67141** If no problems are found, store a NULL in register P1.
67142**
67143** The register P3 contains the maximum number of allowed errors.
67144** At most reg(P3) errors will be reported.
67145** In other words, the analysis stops as soon as reg(P1) errors are
67146** seen.  Reg(P1) is updated with the number of errors remaining.
67147**
67148** The root page numbers of all tables in the database are integer
67149** stored in reg(P1), reg(P1+1), reg(P1+2), ....  There are P2 tables
67150** total.
67151**
67152** If P5 is not zero, the check is done on the auxiliary database
67153** file, not the main database file.
67154**
67155** This opcode is used to implement the integrity_check pragma.
67156*/
67157case OP_IntegrityCk: {
67158#if 0  /* local variables moved into u.bv */
67159  int nRoot;      /* Number of tables to check.  (Number of root pages.) */
67160  int *aRoot;     /* Array of rootpage numbers for tables to be checked */
67161  int j;          /* Loop counter */
67162  int nErr;       /* Number of errors reported */
67163  char *z;        /* Text of the error report */
67164  Mem *pnErr;     /* Register keeping track of errors remaining */
67165#endif /* local variables moved into u.bv */
67166
67167  u.bv.nRoot = pOp->p2;
67168  assert( u.bv.nRoot>0 );
67169  u.bv.aRoot = sqlite3DbMallocRaw(db, sizeof(int)*(u.bv.nRoot+1) );
67170  if( u.bv.aRoot==0 ) goto no_mem;
67171  assert( pOp->p3>0 && pOp->p3<=p->nMem );
67172  u.bv.pnErr = &aMem[pOp->p3];
67173  assert( (u.bv.pnErr->flags & MEM_Int)!=0 );
67174  assert( (u.bv.pnErr->flags & (MEM_Str|MEM_Blob))==0 );
67175  pIn1 = &aMem[pOp->p1];
67176  for(u.bv.j=0; u.bv.j<u.bv.nRoot; u.bv.j++){
67177    u.bv.aRoot[u.bv.j] = (int)sqlite3VdbeIntValue(&pIn1[u.bv.j]);
67178  }
67179  u.bv.aRoot[u.bv.j] = 0;
67180  assert( pOp->p5<db->nDb );
67181  assert( (p->btreeMask & (((yDbMask)1)<<pOp->p5))!=0 );
67182  u.bv.z = sqlite3BtreeIntegrityCheck(db->aDb[pOp->p5].pBt, u.bv.aRoot, u.bv.nRoot,
67183                                 (int)u.bv.pnErr->u.i, &u.bv.nErr);
67184  sqlite3DbFree(db, u.bv.aRoot);
67185  u.bv.pnErr->u.i -= u.bv.nErr;
67186  sqlite3VdbeMemSetNull(pIn1);
67187  if( u.bv.nErr==0 ){
67188    assert( u.bv.z==0 );
67189  }else if( u.bv.z==0 ){
67190    goto no_mem;
67191  }else{
67192    sqlite3VdbeMemSetStr(pIn1, u.bv.z, -1, SQLITE_UTF8, sqlite3_free);
67193  }
67194  UPDATE_MAX_BLOBSIZE(pIn1);
67195  sqlite3VdbeChangeEncoding(pIn1, encoding);
67196  break;
67197}
67198#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
67199
67200/* Opcode: RowSetAdd P1 P2 * * *
67201**
67202** Insert the integer value held by register P2 into a boolean index
67203** held in register P1.
67204**
67205** An assertion fails if P2 is not an integer.
67206*/
67207case OP_RowSetAdd: {       /* in1, in2 */
67208  pIn1 = &aMem[pOp->p1];
67209  pIn2 = &aMem[pOp->p2];
67210  assert( (pIn2->flags & MEM_Int)!=0 );
67211  if( (pIn1->flags & MEM_RowSet)==0 ){
67212    sqlite3VdbeMemSetRowSet(pIn1);
67213    if( (pIn1->flags & MEM_RowSet)==0 ) goto no_mem;
67214  }
67215  sqlite3RowSetInsert(pIn1->u.pRowSet, pIn2->u.i);
67216  break;
67217}
67218
67219/* Opcode: RowSetRead P1 P2 P3 * *
67220**
67221** Extract the smallest value from boolean index P1 and put that value into
67222** register P3.  Or, if boolean index P1 is initially empty, leave P3
67223** unchanged and jump to instruction P2.
67224*/
67225case OP_RowSetRead: {       /* jump, in1, out3 */
67226#if 0  /* local variables moved into u.bw */
67227  i64 val;
67228#endif /* local variables moved into u.bw */
67229  CHECK_FOR_INTERRUPT;
67230  pIn1 = &aMem[pOp->p1];
67231  if( (pIn1->flags & MEM_RowSet)==0
67232   || sqlite3RowSetNext(pIn1->u.pRowSet, &u.bw.val)==0
67233  ){
67234    /* The boolean index is empty */
67235    sqlite3VdbeMemSetNull(pIn1);
67236    pc = pOp->p2 - 1;
67237  }else{
67238    /* A value was pulled from the index */
67239    sqlite3VdbeMemSetInt64(&aMem[pOp->p3], u.bw.val);
67240  }
67241  break;
67242}
67243
67244/* Opcode: RowSetTest P1 P2 P3 P4
67245**
67246** Register P3 is assumed to hold a 64-bit integer value. If register P1
67247** contains a RowSet object and that RowSet object contains
67248** the value held in P3, jump to register P2. Otherwise, insert the
67249** integer in P3 into the RowSet and continue on to the
67250** next opcode.
67251**
67252** The RowSet object is optimized for the case where successive sets
67253** of integers, where each set contains no duplicates. Each set
67254** of values is identified by a unique P4 value. The first set
67255** must have P4==0, the final set P4=-1.  P4 must be either -1 or
67256** non-negative.  For non-negative values of P4 only the lower 4
67257** bits are significant.
67258**
67259** This allows optimizations: (a) when P4==0 there is no need to test
67260** the rowset object for P3, as it is guaranteed not to contain it,
67261** (b) when P4==-1 there is no need to insert the value, as it will
67262** never be tested for, and (c) when a value that is part of set X is
67263** inserted, there is no need to search to see if the same value was
67264** previously inserted as part of set X (only if it was previously
67265** inserted as part of some other set).
67266*/
67267case OP_RowSetTest: {                     /* jump, in1, in3 */
67268#if 0  /* local variables moved into u.bx */
67269  int iSet;
67270  int exists;
67271#endif /* local variables moved into u.bx */
67272
67273  pIn1 = &aMem[pOp->p1];
67274  pIn3 = &aMem[pOp->p3];
67275  u.bx.iSet = pOp->p4.i;
67276  assert( pIn3->flags&MEM_Int );
67277
67278  /* If there is anything other than a rowset object in memory cell P1,
67279  ** delete it now and initialize P1 with an empty rowset
67280  */
67281  if( (pIn1->flags & MEM_RowSet)==0 ){
67282    sqlite3VdbeMemSetRowSet(pIn1);
67283    if( (pIn1->flags & MEM_RowSet)==0 ) goto no_mem;
67284  }
67285
67286  assert( pOp->p4type==P4_INT32 );
67287  assert( u.bx.iSet==-1 || u.bx.iSet>=0 );
67288  if( u.bx.iSet ){
67289    u.bx.exists = sqlite3RowSetTest(pIn1->u.pRowSet,
67290                               (u8)(u.bx.iSet>=0 ? u.bx.iSet & 0xf : 0xff),
67291                               pIn3->u.i);
67292    if( u.bx.exists ){
67293      pc = pOp->p2 - 1;
67294      break;
67295    }
67296  }
67297  if( u.bx.iSet>=0 ){
67298    sqlite3RowSetInsert(pIn1->u.pRowSet, pIn3->u.i);
67299  }
67300  break;
67301}
67302
67303
67304#ifndef SQLITE_OMIT_TRIGGER
67305
67306/* Opcode: Program P1 P2 P3 P4 *
67307**
67308** Execute the trigger program passed as P4 (type P4_SUBPROGRAM).
67309**
67310** P1 contains the address of the memory cell that contains the first memory
67311** cell in an array of values used as arguments to the sub-program. P2
67312** contains the address to jump to if the sub-program throws an IGNORE
67313** exception using the RAISE() function. Register P3 contains the address
67314** of a memory cell in this (the parent) VM that is used to allocate the
67315** memory required by the sub-vdbe at runtime.
67316**
67317** P4 is a pointer to the VM containing the trigger program.
67318*/
67319case OP_Program: {        /* jump */
67320#if 0  /* local variables moved into u.by */
67321  int nMem;               /* Number of memory registers for sub-program */
67322  int nByte;              /* Bytes of runtime space required for sub-program */
67323  Mem *pRt;               /* Register to allocate runtime space */
67324  Mem *pMem;              /* Used to iterate through memory cells */
67325  Mem *pEnd;              /* Last memory cell in new array */
67326  VdbeFrame *pFrame;      /* New vdbe frame to execute in */
67327  SubProgram *pProgram;   /* Sub-program to execute */
67328  void *t;                /* Token identifying trigger */
67329#endif /* local variables moved into u.by */
67330
67331  u.by.pProgram = pOp->p4.pProgram;
67332  u.by.pRt = &aMem[pOp->p3];
67333  assert( memIsValid(u.by.pRt) );
67334  assert( u.by.pProgram->nOp>0 );
67335
67336  /* If the p5 flag is clear, then recursive invocation of triggers is
67337  ** disabled for backwards compatibility (p5 is set if this sub-program
67338  ** is really a trigger, not a foreign key action, and the flag set
67339  ** and cleared by the "PRAGMA recursive_triggers" command is clear).
67340  **
67341  ** It is recursive invocation of triggers, at the SQL level, that is
67342  ** disabled. In some cases a single trigger may generate more than one
67343  ** SubProgram (if the trigger may be executed with more than one different
67344  ** ON CONFLICT algorithm). SubProgram structures associated with a
67345  ** single trigger all have the same value for the SubProgram.token
67346  ** variable.  */
67347  if( pOp->p5 ){
67348    u.by.t = u.by.pProgram->token;
67349    for(u.by.pFrame=p->pFrame; u.by.pFrame && u.by.pFrame->token!=u.by.t; u.by.pFrame=u.by.pFrame->pParent);
67350    if( u.by.pFrame ) break;
67351  }
67352
67353  if( p->nFrame>=db->aLimit[SQLITE_LIMIT_TRIGGER_DEPTH] ){
67354    rc = SQLITE_ERROR;
67355    sqlite3SetString(&p->zErrMsg, db, "too many levels of trigger recursion");
67356    break;
67357  }
67358
67359  /* Register u.by.pRt is used to store the memory required to save the state
67360  ** of the current program, and the memory required at runtime to execute
67361  ** the trigger program. If this trigger has been fired before, then u.by.pRt
67362  ** is already allocated. Otherwise, it must be initialized.  */
67363  if( (u.by.pRt->flags&MEM_Frame)==0 ){
67364    /* SubProgram.nMem is set to the number of memory cells used by the
67365    ** program stored in SubProgram.aOp. As well as these, one memory
67366    ** cell is required for each cursor used by the program. Set local
67367    ** variable u.by.nMem (and later, VdbeFrame.nChildMem) to this value.
67368    */
67369    u.by.nMem = u.by.pProgram->nMem + u.by.pProgram->nCsr;
67370    u.by.nByte = ROUND8(sizeof(VdbeFrame))
67371              + u.by.nMem * sizeof(Mem)
67372              + u.by.pProgram->nCsr * sizeof(VdbeCursor *);
67373    u.by.pFrame = sqlite3DbMallocZero(db, u.by.nByte);
67374    if( !u.by.pFrame ){
67375      goto no_mem;
67376    }
67377    sqlite3VdbeMemRelease(u.by.pRt);
67378    u.by.pRt->flags = MEM_Frame;
67379    u.by.pRt->u.pFrame = u.by.pFrame;
67380
67381    u.by.pFrame->v = p;
67382    u.by.pFrame->nChildMem = u.by.nMem;
67383    u.by.pFrame->nChildCsr = u.by.pProgram->nCsr;
67384    u.by.pFrame->pc = pc;
67385    u.by.pFrame->aMem = p->aMem;
67386    u.by.pFrame->nMem = p->nMem;
67387    u.by.pFrame->apCsr = p->apCsr;
67388    u.by.pFrame->nCursor = p->nCursor;
67389    u.by.pFrame->aOp = p->aOp;
67390    u.by.pFrame->nOp = p->nOp;
67391    u.by.pFrame->token = u.by.pProgram->token;
67392
67393    u.by.pEnd = &VdbeFrameMem(u.by.pFrame)[u.by.pFrame->nChildMem];
67394    for(u.by.pMem=VdbeFrameMem(u.by.pFrame); u.by.pMem!=u.by.pEnd; u.by.pMem++){
67395      u.by.pMem->flags = MEM_Null;
67396      u.by.pMem->db = db;
67397    }
67398  }else{
67399    u.by.pFrame = u.by.pRt->u.pFrame;
67400    assert( u.by.pProgram->nMem+u.by.pProgram->nCsr==u.by.pFrame->nChildMem );
67401    assert( u.by.pProgram->nCsr==u.by.pFrame->nChildCsr );
67402    assert( pc==u.by.pFrame->pc );
67403  }
67404
67405  p->nFrame++;
67406  u.by.pFrame->pParent = p->pFrame;
67407  u.by.pFrame->lastRowid = db->lastRowid;
67408  u.by.pFrame->nChange = p->nChange;
67409  p->nChange = 0;
67410  p->pFrame = u.by.pFrame;
67411  p->aMem = aMem = &VdbeFrameMem(u.by.pFrame)[-1];
67412  p->nMem = u.by.pFrame->nChildMem;
67413  p->nCursor = (u16)u.by.pFrame->nChildCsr;
67414  p->apCsr = (VdbeCursor **)&aMem[p->nMem+1];
67415  p->aOp = aOp = u.by.pProgram->aOp;
67416  p->nOp = u.by.pProgram->nOp;
67417  pc = -1;
67418
67419  break;
67420}
67421
67422/* Opcode: Param P1 P2 * * *
67423**
67424** This opcode is only ever present in sub-programs called via the
67425** OP_Program instruction. Copy a value currently stored in a memory
67426** cell of the calling (parent) frame to cell P2 in the current frames
67427** address space. This is used by trigger programs to access the new.*
67428** and old.* values.
67429**
67430** The address of the cell in the parent frame is determined by adding
67431** the value of the P1 argument to the value of the P1 argument to the
67432** calling OP_Program instruction.
67433*/
67434case OP_Param: {           /* out2-prerelease */
67435#if 0  /* local variables moved into u.bz */
67436  VdbeFrame *pFrame;
67437  Mem *pIn;
67438#endif /* local variables moved into u.bz */
67439  u.bz.pFrame = p->pFrame;
67440  u.bz.pIn = &u.bz.pFrame->aMem[pOp->p1 + u.bz.pFrame->aOp[u.bz.pFrame->pc].p1];
67441  sqlite3VdbeMemShallowCopy(pOut, u.bz.pIn, MEM_Ephem);
67442  break;
67443}
67444
67445#endif /* #ifndef SQLITE_OMIT_TRIGGER */
67446
67447#ifndef SQLITE_OMIT_FOREIGN_KEY
67448/* Opcode: FkCounter P1 P2 * * *
67449**
67450** Increment a "constraint counter" by P2 (P2 may be negative or positive).
67451** If P1 is non-zero, the database constraint counter is incremented
67452** (deferred foreign key constraints). Otherwise, if P1 is zero, the
67453** statement counter is incremented (immediate foreign key constraints).
67454*/
67455case OP_FkCounter: {
67456  if( pOp->p1 ){
67457    db->nDeferredCons += pOp->p2;
67458  }else{
67459    p->nFkConstraint += pOp->p2;
67460  }
67461  break;
67462}
67463
67464/* Opcode: FkIfZero P1 P2 * * *
67465**
67466** This opcode tests if a foreign key constraint-counter is currently zero.
67467** If so, jump to instruction P2. Otherwise, fall through to the next
67468** instruction.
67469**
67470** If P1 is non-zero, then the jump is taken if the database constraint-counter
67471** is zero (the one that counts deferred constraint violations). If P1 is
67472** zero, the jump is taken if the statement constraint-counter is zero
67473** (immediate foreign key constraint violations).
67474*/
67475case OP_FkIfZero: {         /* jump */
67476  if( pOp->p1 ){
67477    if( db->nDeferredCons==0 ) pc = pOp->p2-1;
67478  }else{
67479    if( p->nFkConstraint==0 ) pc = pOp->p2-1;
67480  }
67481  break;
67482}
67483#endif /* #ifndef SQLITE_OMIT_FOREIGN_KEY */
67484
67485#ifndef SQLITE_OMIT_AUTOINCREMENT
67486/* Opcode: MemMax P1 P2 * * *
67487**
67488** P1 is a register in the root frame of this VM (the root frame is
67489** different from the current frame if this instruction is being executed
67490** within a sub-program). Set the value of register P1 to the maximum of
67491** its current value and the value in register P2.
67492**
67493** This instruction throws an error if the memory cell is not initially
67494** an integer.
67495*/
67496case OP_MemMax: {        /* in2 */
67497#if 0  /* local variables moved into u.ca */
67498  Mem *pIn1;
67499  VdbeFrame *pFrame;
67500#endif /* local variables moved into u.ca */
67501  if( p->pFrame ){
67502    for(u.ca.pFrame=p->pFrame; u.ca.pFrame->pParent; u.ca.pFrame=u.ca.pFrame->pParent);
67503    u.ca.pIn1 = &u.ca.pFrame->aMem[pOp->p1];
67504  }else{
67505    u.ca.pIn1 = &aMem[pOp->p1];
67506  }
67507  assert( memIsValid(u.ca.pIn1) );
67508  sqlite3VdbeMemIntegerify(u.ca.pIn1);
67509  pIn2 = &aMem[pOp->p2];
67510  sqlite3VdbeMemIntegerify(pIn2);
67511  if( u.ca.pIn1->u.i<pIn2->u.i){
67512    u.ca.pIn1->u.i = pIn2->u.i;
67513  }
67514  break;
67515}
67516#endif /* SQLITE_OMIT_AUTOINCREMENT */
67517
67518/* Opcode: IfPos P1 P2 * * *
67519**
67520** If the value of register P1 is 1 or greater, jump to P2.
67521**
67522** It is illegal to use this instruction on a register that does
67523** not contain an integer.  An assertion fault will result if you try.
67524*/
67525case OP_IfPos: {        /* jump, in1 */
67526  pIn1 = &aMem[pOp->p1];
67527  assert( pIn1->flags&MEM_Int );
67528  if( pIn1->u.i>0 ){
67529     pc = pOp->p2 - 1;
67530  }
67531  break;
67532}
67533
67534/* Opcode: IfNeg P1 P2 * * *
67535**
67536** If the value of register P1 is less than zero, jump to P2.
67537**
67538** It is illegal to use this instruction on a register that does
67539** not contain an integer.  An assertion fault will result if you try.
67540*/
67541case OP_IfNeg: {        /* jump, in1 */
67542  pIn1 = &aMem[pOp->p1];
67543  assert( pIn1->flags&MEM_Int );
67544  if( pIn1->u.i<0 ){
67545     pc = pOp->p2 - 1;
67546  }
67547  break;
67548}
67549
67550/* Opcode: IfZero P1 P2 P3 * *
67551**
67552** The register P1 must contain an integer.  Add literal P3 to the
67553** value in register P1.  If the result is exactly 0, jump to P2.
67554**
67555** It is illegal to use this instruction on a register that does
67556** not contain an integer.  An assertion fault will result if you try.
67557*/
67558case OP_IfZero: {        /* jump, in1 */
67559  pIn1 = &aMem[pOp->p1];
67560  assert( pIn1->flags&MEM_Int );
67561  pIn1->u.i += pOp->p3;
67562  if( pIn1->u.i==0 ){
67563     pc = pOp->p2 - 1;
67564  }
67565  break;
67566}
67567
67568/* Opcode: AggStep * P2 P3 P4 P5
67569**
67570** Execute the step function for an aggregate.  The
67571** function has P5 arguments.   P4 is a pointer to the FuncDef
67572** structure that specifies the function.  Use register
67573** P3 as the accumulator.
67574**
67575** The P5 arguments are taken from register P2 and its
67576** successors.
67577*/
67578case OP_AggStep: {
67579#if 0  /* local variables moved into u.cb */
67580  int n;
67581  int i;
67582  Mem *pMem;
67583  Mem *pRec;
67584  sqlite3_context ctx;
67585  sqlite3_value **apVal;
67586#endif /* local variables moved into u.cb */
67587
67588  u.cb.n = pOp->p5;
67589  assert( u.cb.n>=0 );
67590  u.cb.pRec = &aMem[pOp->p2];
67591  u.cb.apVal = p->apArg;
67592  assert( u.cb.apVal || u.cb.n==0 );
67593  for(u.cb.i=0; u.cb.i<u.cb.n; u.cb.i++, u.cb.pRec++){
67594    assert( memIsValid(u.cb.pRec) );
67595    u.cb.apVal[u.cb.i] = u.cb.pRec;
67596    memAboutToChange(p, u.cb.pRec);
67597    sqlite3VdbeMemStoreType(u.cb.pRec);
67598  }
67599  u.cb.ctx.pFunc = pOp->p4.pFunc;
67600  assert( pOp->p3>0 && pOp->p3<=p->nMem );
67601  u.cb.ctx.pMem = u.cb.pMem = &aMem[pOp->p3];
67602  u.cb.pMem->n++;
67603  u.cb.ctx.s.flags = MEM_Null;
67604  u.cb.ctx.s.z = 0;
67605  u.cb.ctx.s.zMalloc = 0;
67606  u.cb.ctx.s.xDel = 0;
67607  u.cb.ctx.s.db = db;
67608  u.cb.ctx.isError = 0;
67609  u.cb.ctx.pColl = 0;
67610  if( u.cb.ctx.pFunc->flags & SQLITE_FUNC_NEEDCOLL ){
67611    assert( pOp>p->aOp );
67612    assert( pOp[-1].p4type==P4_COLLSEQ );
67613    assert( pOp[-1].opcode==OP_CollSeq );
67614    u.cb.ctx.pColl = pOp[-1].p4.pColl;
67615  }
67616  (u.cb.ctx.pFunc->xStep)(&u.cb.ctx, u.cb.n, u.cb.apVal); /* IMP: R-24505-23230 */
67617  if( u.cb.ctx.isError ){
67618    sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3_value_text(&u.cb.ctx.s));
67619    rc = u.cb.ctx.isError;
67620  }
67621
67622  sqlite3VdbeMemRelease(&u.cb.ctx.s);
67623
67624  break;
67625}
67626
67627/* Opcode: AggFinal P1 P2 * P4 *
67628**
67629** Execute the finalizer function for an aggregate.  P1 is
67630** the memory location that is the accumulator for the aggregate.
67631**
67632** P2 is the number of arguments that the step function takes and
67633** P4 is a pointer to the FuncDef for this function.  The P2
67634** argument is not used by this opcode.  It is only there to disambiguate
67635** functions that can take varying numbers of arguments.  The
67636** P4 argument is only needed for the degenerate case where
67637** the step function was not previously called.
67638*/
67639case OP_AggFinal: {
67640#if 0  /* local variables moved into u.cc */
67641  Mem *pMem;
67642#endif /* local variables moved into u.cc */
67643  assert( pOp->p1>0 && pOp->p1<=p->nMem );
67644  u.cc.pMem = &aMem[pOp->p1];
67645  assert( (u.cc.pMem->flags & ~(MEM_Null|MEM_Agg))==0 );
67646  rc = sqlite3VdbeMemFinalize(u.cc.pMem, pOp->p4.pFunc);
67647  if( rc ){
67648    sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3_value_text(u.cc.pMem));
67649  }
67650  sqlite3VdbeChangeEncoding(u.cc.pMem, encoding);
67651  UPDATE_MAX_BLOBSIZE(u.cc.pMem);
67652  if( sqlite3VdbeMemTooBig(u.cc.pMem) ){
67653    goto too_big;
67654  }
67655  break;
67656}
67657
67658#ifndef SQLITE_OMIT_WAL
67659/* Opcode: Checkpoint P1 P2 P3 * *
67660**
67661** Checkpoint database P1. This is a no-op if P1 is not currently in
67662** WAL mode. Parameter P2 is one of SQLITE_CHECKPOINT_PASSIVE, FULL
67663** or RESTART.  Write 1 or 0 into mem[P3] if the checkpoint returns
67664** SQLITE_BUSY or not, respectively.  Write the number of pages in the
67665** WAL after the checkpoint into mem[P3+1] and the number of pages
67666** in the WAL that have been checkpointed after the checkpoint
67667** completes into mem[P3+2].  However on an error, mem[P3+1] and
67668** mem[P3+2] are initialized to -1.
67669*/
67670case OP_Checkpoint: {
67671#if 0  /* local variables moved into u.cd */
67672  int i;                          /* Loop counter */
67673  int aRes[3];                    /* Results */
67674  Mem *pMem;                      /* Write results here */
67675#endif /* local variables moved into u.cd */
67676
67677  u.cd.aRes[0] = 0;
67678  u.cd.aRes[1] = u.cd.aRes[2] = -1;
67679  assert( pOp->p2==SQLITE_CHECKPOINT_PASSIVE
67680       || pOp->p2==SQLITE_CHECKPOINT_FULL
67681       || pOp->p2==SQLITE_CHECKPOINT_RESTART
67682  );
67683  rc = sqlite3Checkpoint(db, pOp->p1, pOp->p2, &u.cd.aRes[1], &u.cd.aRes[2]);
67684  if( rc==SQLITE_BUSY ){
67685    rc = SQLITE_OK;
67686    u.cd.aRes[0] = 1;
67687  }
67688  for(u.cd.i=0, u.cd.pMem = &aMem[pOp->p3]; u.cd.i<3; u.cd.i++, u.cd.pMem++){
67689    sqlite3VdbeMemSetInt64(u.cd.pMem, (i64)u.cd.aRes[u.cd.i]);
67690  }
67691  break;
67692};
67693#endif
67694
67695#ifndef SQLITE_OMIT_PRAGMA
67696/* Opcode: JournalMode P1 P2 P3 * P5
67697**
67698** Change the journal mode of database P1 to P3. P3 must be one of the
67699** PAGER_JOURNALMODE_XXX values. If changing between the various rollback
67700** modes (delete, truncate, persist, off and memory), this is a simple
67701** operation. No IO is required.
67702**
67703** If changing into or out of WAL mode the procedure is more complicated.
67704**
67705** Write a string containing the final journal-mode to register P2.
67706*/
67707case OP_JournalMode: {    /* out2-prerelease */
67708#if 0  /* local variables moved into u.ce */
67709  Btree *pBt;                     /* Btree to change journal mode of */
67710  Pager *pPager;                  /* Pager associated with pBt */
67711  int eNew;                       /* New journal mode */
67712  int eOld;                       /* The old journal mode */
67713  const char *zFilename;          /* Name of database file for pPager */
67714#endif /* local variables moved into u.ce */
67715
67716  u.ce.eNew = pOp->p3;
67717  assert( u.ce.eNew==PAGER_JOURNALMODE_DELETE
67718       || u.ce.eNew==PAGER_JOURNALMODE_TRUNCATE
67719       || u.ce.eNew==PAGER_JOURNALMODE_PERSIST
67720       || u.ce.eNew==PAGER_JOURNALMODE_OFF
67721       || u.ce.eNew==PAGER_JOURNALMODE_MEMORY
67722       || u.ce.eNew==PAGER_JOURNALMODE_WAL
67723       || u.ce.eNew==PAGER_JOURNALMODE_QUERY
67724  );
67725  assert( pOp->p1>=0 && pOp->p1<db->nDb );
67726
67727  u.ce.pBt = db->aDb[pOp->p1].pBt;
67728  u.ce.pPager = sqlite3BtreePager(u.ce.pBt);
67729  u.ce.eOld = sqlite3PagerGetJournalMode(u.ce.pPager);
67730  if( u.ce.eNew==PAGER_JOURNALMODE_QUERY ) u.ce.eNew = u.ce.eOld;
67731  if( !sqlite3PagerOkToChangeJournalMode(u.ce.pPager) ) u.ce.eNew = u.ce.eOld;
67732
67733#ifndef SQLITE_OMIT_WAL
67734  u.ce.zFilename = sqlite3PagerFilename(u.ce.pPager);
67735
67736  /* Do not allow a transition to journal_mode=WAL for a database
67737  ** in temporary storage or if the VFS does not support shared memory
67738  */
67739  if( u.ce.eNew==PAGER_JOURNALMODE_WAL
67740   && (u.ce.zFilename[0]==0                         /* Temp file */
67741       || !sqlite3PagerWalSupported(u.ce.pPager))   /* No shared-memory support */
67742  ){
67743    u.ce.eNew = u.ce.eOld;
67744  }
67745
67746  if( (u.ce.eNew!=u.ce.eOld)
67747   && (u.ce.eOld==PAGER_JOURNALMODE_WAL || u.ce.eNew==PAGER_JOURNALMODE_WAL)
67748  ){
67749    if( !db->autoCommit || db->activeVdbeCnt>1 ){
67750      rc = SQLITE_ERROR;
67751      sqlite3SetString(&p->zErrMsg, db,
67752          "cannot change %s wal mode from within a transaction",
67753          (u.ce.eNew==PAGER_JOURNALMODE_WAL ? "into" : "out of")
67754      );
67755      break;
67756    }else{
67757
67758      if( u.ce.eOld==PAGER_JOURNALMODE_WAL ){
67759        /* If leaving WAL mode, close the log file. If successful, the call
67760        ** to PagerCloseWal() checkpoints and deletes the write-ahead-log
67761        ** file. An EXCLUSIVE lock may still be held on the database file
67762        ** after a successful return.
67763        */
67764        rc = sqlite3PagerCloseWal(u.ce.pPager);
67765        if( rc==SQLITE_OK ){
67766          sqlite3PagerSetJournalMode(u.ce.pPager, u.ce.eNew);
67767        }
67768      }else if( u.ce.eOld==PAGER_JOURNALMODE_MEMORY ){
67769        /* Cannot transition directly from MEMORY to WAL.  Use mode OFF
67770        ** as an intermediate */
67771        sqlite3PagerSetJournalMode(u.ce.pPager, PAGER_JOURNALMODE_OFF);
67772      }
67773
67774      /* Open a transaction on the database file. Regardless of the journal
67775      ** mode, this transaction always uses a rollback journal.
67776      */
67777      assert( sqlite3BtreeIsInTrans(u.ce.pBt)==0 );
67778      if( rc==SQLITE_OK ){
67779        rc = sqlite3BtreeSetVersion(u.ce.pBt, (u.ce.eNew==PAGER_JOURNALMODE_WAL ? 2 : 1));
67780      }
67781    }
67782  }
67783#endif /* ifndef SQLITE_OMIT_WAL */
67784
67785  if( rc ){
67786    u.ce.eNew = u.ce.eOld;
67787  }
67788  u.ce.eNew = sqlite3PagerSetJournalMode(u.ce.pPager, u.ce.eNew);
67789
67790  pOut = &aMem[pOp->p2];
67791  pOut->flags = MEM_Str|MEM_Static|MEM_Term;
67792  pOut->z = (char *)sqlite3JournalModename(u.ce.eNew);
67793  pOut->n = sqlite3Strlen30(pOut->z);
67794  pOut->enc = SQLITE_UTF8;
67795  sqlite3VdbeChangeEncoding(pOut, encoding);
67796  break;
67797};
67798#endif /* SQLITE_OMIT_PRAGMA */
67799
67800#if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
67801/* Opcode: Vacuum * * * * *
67802**
67803** Vacuum the entire database.  This opcode will cause other virtual
67804** machines to be created and run.  It may not be called from within
67805** a transaction.
67806*/
67807case OP_Vacuum: {
67808  rc = sqlite3RunVacuum(&p->zErrMsg, db);
67809  break;
67810}
67811#endif
67812
67813#if !defined(SQLITE_OMIT_AUTOVACUUM)
67814/* Opcode: IncrVacuum P1 P2 * * *
67815**
67816** Perform a single step of the incremental vacuum procedure on
67817** the P1 database. If the vacuum has finished, jump to instruction
67818** P2. Otherwise, fall through to the next instruction.
67819*/
67820case OP_IncrVacuum: {        /* jump */
67821#if 0  /* local variables moved into u.cf */
67822  Btree *pBt;
67823#endif /* local variables moved into u.cf */
67824
67825  assert( pOp->p1>=0 && pOp->p1<db->nDb );
67826  assert( (p->btreeMask & (((yDbMask)1)<<pOp->p1))!=0 );
67827  u.cf.pBt = db->aDb[pOp->p1].pBt;
67828  rc = sqlite3BtreeIncrVacuum(u.cf.pBt);
67829  if( rc==SQLITE_DONE ){
67830    pc = pOp->p2 - 1;
67831    rc = SQLITE_OK;
67832  }
67833  break;
67834}
67835#endif
67836
67837/* Opcode: Expire P1 * * * *
67838**
67839** Cause precompiled statements to become expired. An expired statement
67840** fails with an error code of SQLITE_SCHEMA if it is ever executed
67841** (via sqlite3_step()).
67842**
67843** If P1 is 0, then all SQL statements become expired. If P1 is non-zero,
67844** then only the currently executing statement is affected.
67845*/
67846case OP_Expire: {
67847  if( !pOp->p1 ){
67848    sqlite3ExpirePreparedStatements(db);
67849  }else{
67850    p->expired = 1;
67851  }
67852  break;
67853}
67854
67855#ifndef SQLITE_OMIT_SHARED_CACHE
67856/* Opcode: TableLock P1 P2 P3 P4 *
67857**
67858** Obtain a lock on a particular table. This instruction is only used when
67859** the shared-cache feature is enabled.
67860**
67861** P1 is the index of the database in sqlite3.aDb[] of the database
67862** on which the lock is acquired.  A readlock is obtained if P3==0 or
67863** a write lock if P3==1.
67864**
67865** P2 contains the root-page of the table to lock.
67866**
67867** P4 contains a pointer to the name of the table being locked. This is only
67868** used to generate an error message if the lock cannot be obtained.
67869*/
67870case OP_TableLock: {
67871  u8 isWriteLock = (u8)pOp->p3;
67872  if( isWriteLock || 0==(db->flags&SQLITE_ReadUncommitted) ){
67873    int p1 = pOp->p1;
67874    assert( p1>=0 && p1<db->nDb );
67875    assert( (p->btreeMask & (((yDbMask)1)<<p1))!=0 );
67876    assert( isWriteLock==0 || isWriteLock==1 );
67877    rc = sqlite3BtreeLockTable(db->aDb[p1].pBt, pOp->p2, isWriteLock);
67878    if( (rc&0xFF)==SQLITE_LOCKED ){
67879      const char *z = pOp->p4.z;
67880      sqlite3SetString(&p->zErrMsg, db, "database table is locked: %s", z);
67881    }
67882  }
67883  break;
67884}
67885#endif /* SQLITE_OMIT_SHARED_CACHE */
67886
67887#ifndef SQLITE_OMIT_VIRTUALTABLE
67888/* Opcode: VBegin * * * P4 *
67889**
67890** P4 may be a pointer to an sqlite3_vtab structure. If so, call the
67891** xBegin method for that table.
67892**
67893** Also, whether or not P4 is set, check that this is not being called from
67894** within a callback to a virtual table xSync() method. If it is, the error
67895** code will be set to SQLITE_LOCKED.
67896*/
67897case OP_VBegin: {
67898#if 0  /* local variables moved into u.cg */
67899  VTable *pVTab;
67900#endif /* local variables moved into u.cg */
67901  u.cg.pVTab = pOp->p4.pVtab;
67902  rc = sqlite3VtabBegin(db, u.cg.pVTab);
67903  if( u.cg.pVTab ) importVtabErrMsg(p, u.cg.pVTab->pVtab);
67904  break;
67905}
67906#endif /* SQLITE_OMIT_VIRTUALTABLE */
67907
67908#ifndef SQLITE_OMIT_VIRTUALTABLE
67909/* Opcode: VCreate P1 * * P4 *
67910**
67911** P4 is the name of a virtual table in database P1. Call the xCreate method
67912** for that table.
67913*/
67914case OP_VCreate: {
67915  rc = sqlite3VtabCallCreate(db, pOp->p1, pOp->p4.z, &p->zErrMsg);
67916  break;
67917}
67918#endif /* SQLITE_OMIT_VIRTUALTABLE */
67919
67920#ifndef SQLITE_OMIT_VIRTUALTABLE
67921/* Opcode: VDestroy P1 * * P4 *
67922**
67923** P4 is the name of a virtual table in database P1.  Call the xDestroy method
67924** of that table.
67925*/
67926case OP_VDestroy: {
67927  p->inVtabMethod = 2;
67928  rc = sqlite3VtabCallDestroy(db, pOp->p1, pOp->p4.z);
67929  p->inVtabMethod = 0;
67930  break;
67931}
67932#endif /* SQLITE_OMIT_VIRTUALTABLE */
67933
67934#ifndef SQLITE_OMIT_VIRTUALTABLE
67935/* Opcode: VOpen P1 * * P4 *
67936**
67937** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
67938** P1 is a cursor number.  This opcode opens a cursor to the virtual
67939** table and stores that cursor in P1.
67940*/
67941case OP_VOpen: {
67942#if 0  /* local variables moved into u.ch */
67943  VdbeCursor *pCur;
67944  sqlite3_vtab_cursor *pVtabCursor;
67945  sqlite3_vtab *pVtab;
67946  sqlite3_module *pModule;
67947#endif /* local variables moved into u.ch */
67948
67949  u.ch.pCur = 0;
67950  u.ch.pVtabCursor = 0;
67951  u.ch.pVtab = pOp->p4.pVtab->pVtab;
67952  u.ch.pModule = (sqlite3_module *)u.ch.pVtab->pModule;
67953  assert(u.ch.pVtab && u.ch.pModule);
67954  rc = u.ch.pModule->xOpen(u.ch.pVtab, &u.ch.pVtabCursor);
67955  importVtabErrMsg(p, u.ch.pVtab);
67956  if( SQLITE_OK==rc ){
67957    /* Initialize sqlite3_vtab_cursor base class */
67958    u.ch.pVtabCursor->pVtab = u.ch.pVtab;
67959
67960    /* Initialise vdbe cursor object */
67961    u.ch.pCur = allocateCursor(p, pOp->p1, 0, -1, 0);
67962    if( u.ch.pCur ){
67963      u.ch.pCur->pVtabCursor = u.ch.pVtabCursor;
67964      u.ch.pCur->pModule = u.ch.pVtabCursor->pVtab->pModule;
67965    }else{
67966      db->mallocFailed = 1;
67967      u.ch.pModule->xClose(u.ch.pVtabCursor);
67968    }
67969  }
67970  break;
67971}
67972#endif /* SQLITE_OMIT_VIRTUALTABLE */
67973
67974#ifndef SQLITE_OMIT_VIRTUALTABLE
67975/* Opcode: VFilter P1 P2 P3 P4 *
67976**
67977** P1 is a cursor opened using VOpen.  P2 is an address to jump to if
67978** the filtered result set is empty.
67979**
67980** P4 is either NULL or a string that was generated by the xBestIndex
67981** method of the module.  The interpretation of the P4 string is left
67982** to the module implementation.
67983**
67984** This opcode invokes the xFilter method on the virtual table specified
67985** by P1.  The integer query plan parameter to xFilter is stored in register
67986** P3. Register P3+1 stores the argc parameter to be passed to the
67987** xFilter method. Registers P3+2..P3+1+argc are the argc
67988** additional parameters which are passed to
67989** xFilter as argv. Register P3+2 becomes argv[0] when passed to xFilter.
67990**
67991** A jump is made to P2 if the result set after filtering would be empty.
67992*/
67993case OP_VFilter: {   /* jump */
67994#if 0  /* local variables moved into u.ci */
67995  int nArg;
67996  int iQuery;
67997  const sqlite3_module *pModule;
67998  Mem *pQuery;
67999  Mem *pArgc;
68000  sqlite3_vtab_cursor *pVtabCursor;
68001  sqlite3_vtab *pVtab;
68002  VdbeCursor *pCur;
68003  int res;
68004  int i;
68005  Mem **apArg;
68006#endif /* local variables moved into u.ci */
68007
68008  u.ci.pQuery = &aMem[pOp->p3];
68009  u.ci.pArgc = &u.ci.pQuery[1];
68010  u.ci.pCur = p->apCsr[pOp->p1];
68011  assert( memIsValid(u.ci.pQuery) );
68012  REGISTER_TRACE(pOp->p3, u.ci.pQuery);
68013  assert( u.ci.pCur->pVtabCursor );
68014  u.ci.pVtabCursor = u.ci.pCur->pVtabCursor;
68015  u.ci.pVtab = u.ci.pVtabCursor->pVtab;
68016  u.ci.pModule = u.ci.pVtab->pModule;
68017
68018  /* Grab the index number and argc parameters */
68019  assert( (u.ci.pQuery->flags&MEM_Int)!=0 && u.ci.pArgc->flags==MEM_Int );
68020  u.ci.nArg = (int)u.ci.pArgc->u.i;
68021  u.ci.iQuery = (int)u.ci.pQuery->u.i;
68022
68023  /* Invoke the xFilter method */
68024  {
68025    u.ci.res = 0;
68026    u.ci.apArg = p->apArg;
68027    for(u.ci.i = 0; u.ci.i<u.ci.nArg; u.ci.i++){
68028      u.ci.apArg[u.ci.i] = &u.ci.pArgc[u.ci.i+1];
68029      sqlite3VdbeMemStoreType(u.ci.apArg[u.ci.i]);
68030    }
68031
68032    p->inVtabMethod = 1;
68033    rc = u.ci.pModule->xFilter(u.ci.pVtabCursor, u.ci.iQuery, pOp->p4.z, u.ci.nArg, u.ci.apArg);
68034    p->inVtabMethod = 0;
68035    importVtabErrMsg(p, u.ci.pVtab);
68036    if( rc==SQLITE_OK ){
68037      u.ci.res = u.ci.pModule->xEof(u.ci.pVtabCursor);
68038    }
68039
68040    if( u.ci.res ){
68041      pc = pOp->p2 - 1;
68042    }
68043  }
68044  u.ci.pCur->nullRow = 0;
68045
68046  break;
68047}
68048#endif /* SQLITE_OMIT_VIRTUALTABLE */
68049
68050#ifndef SQLITE_OMIT_VIRTUALTABLE
68051/* Opcode: VColumn P1 P2 P3 * *
68052**
68053** Store the value of the P2-th column of
68054** the row of the virtual-table that the
68055** P1 cursor is pointing to into register P3.
68056*/
68057case OP_VColumn: {
68058#if 0  /* local variables moved into u.cj */
68059  sqlite3_vtab *pVtab;
68060  const sqlite3_module *pModule;
68061  Mem *pDest;
68062  sqlite3_context sContext;
68063#endif /* local variables moved into u.cj */
68064
68065  VdbeCursor *pCur = p->apCsr[pOp->p1];
68066  assert( pCur->pVtabCursor );
68067  assert( pOp->p3>0 && pOp->p3<=p->nMem );
68068  u.cj.pDest = &aMem[pOp->p3];
68069  memAboutToChange(p, u.cj.pDest);
68070  if( pCur->nullRow ){
68071    sqlite3VdbeMemSetNull(u.cj.pDest);
68072    break;
68073  }
68074  u.cj.pVtab = pCur->pVtabCursor->pVtab;
68075  u.cj.pModule = u.cj.pVtab->pModule;
68076  assert( u.cj.pModule->xColumn );
68077  memset(&u.cj.sContext, 0, sizeof(u.cj.sContext));
68078
68079  /* The output cell may already have a buffer allocated. Move
68080  ** the current contents to u.cj.sContext.s so in case the user-function
68081  ** can use the already allocated buffer instead of allocating a
68082  ** new one.
68083  */
68084  sqlite3VdbeMemMove(&u.cj.sContext.s, u.cj.pDest);
68085  MemSetTypeFlag(&u.cj.sContext.s, MEM_Null);
68086
68087  rc = u.cj.pModule->xColumn(pCur->pVtabCursor, &u.cj.sContext, pOp->p2);
68088  importVtabErrMsg(p, u.cj.pVtab);
68089  if( u.cj.sContext.isError ){
68090    rc = u.cj.sContext.isError;
68091  }
68092
68093  /* Copy the result of the function to the P3 register. We
68094  ** do this regardless of whether or not an error occurred to ensure any
68095  ** dynamic allocation in u.cj.sContext.s (a Mem struct) is  released.
68096  */
68097  sqlite3VdbeChangeEncoding(&u.cj.sContext.s, encoding);
68098  sqlite3VdbeMemMove(u.cj.pDest, &u.cj.sContext.s);
68099  REGISTER_TRACE(pOp->p3, u.cj.pDest);
68100  UPDATE_MAX_BLOBSIZE(u.cj.pDest);
68101
68102  if( sqlite3VdbeMemTooBig(u.cj.pDest) ){
68103    goto too_big;
68104  }
68105  break;
68106}
68107#endif /* SQLITE_OMIT_VIRTUALTABLE */
68108
68109#ifndef SQLITE_OMIT_VIRTUALTABLE
68110/* Opcode: VNext P1 P2 * * *
68111**
68112** Advance virtual table P1 to the next row in its result set and
68113** jump to instruction P2.  Or, if the virtual table has reached
68114** the end of its result set, then fall through to the next instruction.
68115*/
68116case OP_VNext: {   /* jump */
68117#if 0  /* local variables moved into u.ck */
68118  sqlite3_vtab *pVtab;
68119  const sqlite3_module *pModule;
68120  int res;
68121  VdbeCursor *pCur;
68122#endif /* local variables moved into u.ck */
68123
68124  u.ck.res = 0;
68125  u.ck.pCur = p->apCsr[pOp->p1];
68126  assert( u.ck.pCur->pVtabCursor );
68127  if( u.ck.pCur->nullRow ){
68128    break;
68129  }
68130  u.ck.pVtab = u.ck.pCur->pVtabCursor->pVtab;
68131  u.ck.pModule = u.ck.pVtab->pModule;
68132  assert( u.ck.pModule->xNext );
68133
68134  /* Invoke the xNext() method of the module. There is no way for the
68135  ** underlying implementation to return an error if one occurs during
68136  ** xNext(). Instead, if an error occurs, true is returned (indicating that
68137  ** data is available) and the error code returned when xColumn or
68138  ** some other method is next invoked on the save virtual table cursor.
68139  */
68140  p->inVtabMethod = 1;
68141  rc = u.ck.pModule->xNext(u.ck.pCur->pVtabCursor);
68142  p->inVtabMethod = 0;
68143  importVtabErrMsg(p, u.ck.pVtab);
68144  if( rc==SQLITE_OK ){
68145    u.ck.res = u.ck.pModule->xEof(u.ck.pCur->pVtabCursor);
68146  }
68147
68148  if( !u.ck.res ){
68149    /* If there is data, jump to P2 */
68150    pc = pOp->p2 - 1;
68151  }
68152  break;
68153}
68154#endif /* SQLITE_OMIT_VIRTUALTABLE */
68155
68156#ifndef SQLITE_OMIT_VIRTUALTABLE
68157/* Opcode: VRename P1 * * P4 *
68158**
68159** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
68160** This opcode invokes the corresponding xRename method. The value
68161** in register P1 is passed as the zName argument to the xRename method.
68162*/
68163case OP_VRename: {
68164#if 0  /* local variables moved into u.cl */
68165  sqlite3_vtab *pVtab;
68166  Mem *pName;
68167#endif /* local variables moved into u.cl */
68168
68169  u.cl.pVtab = pOp->p4.pVtab->pVtab;
68170  u.cl.pName = &aMem[pOp->p1];
68171  assert( u.cl.pVtab->pModule->xRename );
68172  assert( memIsValid(u.cl.pName) );
68173  REGISTER_TRACE(pOp->p1, u.cl.pName);
68174  assert( u.cl.pName->flags & MEM_Str );
68175  rc = u.cl.pVtab->pModule->xRename(u.cl.pVtab, u.cl.pName->z);
68176  importVtabErrMsg(p, u.cl.pVtab);
68177  p->expired = 0;
68178
68179  break;
68180}
68181#endif
68182
68183#ifndef SQLITE_OMIT_VIRTUALTABLE
68184/* Opcode: VUpdate P1 P2 P3 P4 *
68185**
68186** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
68187** This opcode invokes the corresponding xUpdate method. P2 values
68188** are contiguous memory cells starting at P3 to pass to the xUpdate
68189** invocation. The value in register (P3+P2-1) corresponds to the
68190** p2th element of the argv array passed to xUpdate.
68191**
68192** The xUpdate method will do a DELETE or an INSERT or both.
68193** The argv[0] element (which corresponds to memory cell P3)
68194** is the rowid of a row to delete.  If argv[0] is NULL then no
68195** deletion occurs.  The argv[1] element is the rowid of the new
68196** row.  This can be NULL to have the virtual table select the new
68197** rowid for itself.  The subsequent elements in the array are
68198** the values of columns in the new row.
68199**
68200** If P2==1 then no insert is performed.  argv[0] is the rowid of
68201** a row to delete.
68202**
68203** P1 is a boolean flag. If it is set to true and the xUpdate call
68204** is successful, then the value returned by sqlite3_last_insert_rowid()
68205** is set to the value of the rowid for the row just inserted.
68206*/
68207case OP_VUpdate: {
68208#if 0  /* local variables moved into u.cm */
68209  sqlite3_vtab *pVtab;
68210  sqlite3_module *pModule;
68211  int nArg;
68212  int i;
68213  sqlite_int64 rowid;
68214  Mem **apArg;
68215  Mem *pX;
68216#endif /* local variables moved into u.cm */
68217
68218  u.cm.pVtab = pOp->p4.pVtab->pVtab;
68219  u.cm.pModule = (sqlite3_module *)u.cm.pVtab->pModule;
68220  u.cm.nArg = pOp->p2;
68221  assert( pOp->p4type==P4_VTAB );
68222  if( ALWAYS(u.cm.pModule->xUpdate) ){
68223    u.cm.apArg = p->apArg;
68224    u.cm.pX = &aMem[pOp->p3];
68225    for(u.cm.i=0; u.cm.i<u.cm.nArg; u.cm.i++){
68226      assert( memIsValid(u.cm.pX) );
68227      memAboutToChange(p, u.cm.pX);
68228      sqlite3VdbeMemStoreType(u.cm.pX);
68229      u.cm.apArg[u.cm.i] = u.cm.pX;
68230      u.cm.pX++;
68231    }
68232    rc = u.cm.pModule->xUpdate(u.cm.pVtab, u.cm.nArg, u.cm.apArg, &u.cm.rowid);
68233    importVtabErrMsg(p, u.cm.pVtab);
68234    if( rc==SQLITE_OK && pOp->p1 ){
68235      assert( u.cm.nArg>1 && u.cm.apArg[0] && (u.cm.apArg[0]->flags&MEM_Null) );
68236      db->lastRowid = u.cm.rowid;
68237    }
68238    p->nChange++;
68239  }
68240  break;
68241}
68242#endif /* SQLITE_OMIT_VIRTUALTABLE */
68243
68244#ifndef  SQLITE_OMIT_PAGER_PRAGMAS
68245/* Opcode: Pagecount P1 P2 * * *
68246**
68247** Write the current number of pages in database P1 to memory cell P2.
68248*/
68249case OP_Pagecount: {            /* out2-prerelease */
68250  pOut->u.i = sqlite3BtreeLastPage(db->aDb[pOp->p1].pBt);
68251  break;
68252}
68253#endif
68254
68255
68256#ifndef  SQLITE_OMIT_PAGER_PRAGMAS
68257/* Opcode: MaxPgcnt P1 P2 P3 * *
68258**
68259** Try to set the maximum page count for database P1 to the value in P3.
68260** Do not let the maximum page count fall below the current page count and
68261** do not change the maximum page count value if P3==0.
68262**
68263** Store the maximum page count after the change in register P2.
68264*/
68265case OP_MaxPgcnt: {            /* out2-prerelease */
68266  unsigned int newMax;
68267  Btree *pBt;
68268
68269  pBt = db->aDb[pOp->p1].pBt;
68270  newMax = 0;
68271  if( pOp->p3 ){
68272    newMax = sqlite3BtreeLastPage(pBt);
68273    if( newMax < (unsigned)pOp->p3 ) newMax = (unsigned)pOp->p3;
68274  }
68275  pOut->u.i = sqlite3BtreeMaxPageCount(pBt, newMax);
68276  break;
68277}
68278#endif
68279
68280
68281#ifndef SQLITE_OMIT_TRACE
68282/* Opcode: Trace * * * P4 *
68283**
68284** If tracing is enabled (by the sqlite3_trace()) interface, then
68285** the UTF-8 string contained in P4 is emitted on the trace callback.
68286*/
68287case OP_Trace: {
68288#if 0  /* local variables moved into u.cn */
68289  char *zTrace;
68290#endif /* local variables moved into u.cn */
68291
68292  u.cn.zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql);
68293  if( u.cn.zTrace ){
68294    if( db->xTrace ){
68295      char *z = sqlite3VdbeExpandSql(p, u.cn.zTrace);
68296      db->xTrace(db->pTraceArg, z);
68297      sqlite3DbFree(db, z);
68298    }
68299#ifdef SQLITE_DEBUG
68300    if( (db->flags & SQLITE_SqlTrace)!=0 ){
68301      sqlite3DebugPrintf("SQL-trace: %s\n", u.cn.zTrace);
68302    }
68303#endif /* SQLITE_DEBUG */
68304  }
68305  break;
68306}
68307#endif
68308
68309
68310/* Opcode: Noop * * * * *
68311**
68312** Do nothing.  This instruction is often useful as a jump
68313** destination.
68314*/
68315/*
68316** The magic Explain opcode are only inserted when explain==2 (which
68317** is to say when the EXPLAIN QUERY PLAN syntax is used.)
68318** This opcode records information from the optimizer.  It is the
68319** the same as a no-op.  This opcodesnever appears in a real VM program.
68320*/
68321default: {          /* This is really OP_Noop and OP_Explain */
68322  assert( pOp->opcode==OP_Noop || pOp->opcode==OP_Explain );
68323  break;
68324}
68325
68326/*****************************************************************************
68327** The cases of the switch statement above this line should all be indented
68328** by 6 spaces.  But the left-most 6 spaces have been removed to improve the
68329** readability.  From this point on down, the normal indentation rules are
68330** restored.
68331*****************************************************************************/
68332    }
68333
68334#ifdef VDBE_PROFILE
68335    {
68336      u64 elapsed = sqlite3Hwtime() - start;
68337      pOp->cycles += elapsed;
68338      pOp->cnt++;
68339#if 0
68340        fprintf(stdout, "%10llu ", elapsed);
68341        sqlite3VdbePrintOp(stdout, origPc, &aOp[origPc]);
68342#endif
68343    }
68344#endif
68345
68346    /* The following code adds nothing to the actual functionality
68347    ** of the program.  It is only here for testing and debugging.
68348    ** On the other hand, it does burn CPU cycles every time through
68349    ** the evaluator loop.  So we can leave it out when NDEBUG is defined.
68350    */
68351#ifndef NDEBUG
68352    assert( pc>=-1 && pc<p->nOp );
68353
68354#ifdef SQLITE_DEBUG
68355    if( p->trace ){
68356      if( rc!=0 ) fprintf(p->trace,"rc=%d\n",rc);
68357      if( pOp->opflags & (OPFLG_OUT2_PRERELEASE|OPFLG_OUT2) ){
68358        registerTrace(p->trace, pOp->p2, &aMem[pOp->p2]);
68359      }
68360      if( pOp->opflags & OPFLG_OUT3 ){
68361        registerTrace(p->trace, pOp->p3, &aMem[pOp->p3]);
68362      }
68363    }
68364#endif  /* SQLITE_DEBUG */
68365#endif  /* NDEBUG */
68366  }  /* The end of the for(;;) loop the loops through opcodes */
68367
68368  /* If we reach this point, it means that execution is finished with
68369  ** an error of some kind.
68370  */
68371vdbe_error_halt:
68372  assert( rc );
68373  p->rc = rc;
68374  testcase( sqlite3GlobalConfig.xLog!=0 );
68375  sqlite3_log(rc, "statement aborts at %d: [%s] %s",
68376                   pc, p->zSql, p->zErrMsg);
68377  sqlite3VdbeHalt(p);
68378  if( rc==SQLITE_IOERR_NOMEM ) db->mallocFailed = 1;
68379  rc = SQLITE_ERROR;
68380  if( resetSchemaOnFault>0 ){
68381    sqlite3ResetInternalSchema(db, resetSchemaOnFault-1);
68382  }
68383
68384  /* This is the only way out of this procedure.  We have to
68385  ** release the mutexes on btrees that were acquired at the
68386  ** top. */
68387vdbe_return:
68388  sqlite3VdbeLeave(p);
68389  return rc;
68390
68391  /* Jump to here if a string or blob larger than SQLITE_MAX_LENGTH
68392  ** is encountered.
68393  */
68394too_big:
68395  sqlite3SetString(&p->zErrMsg, db, "string or blob too big");
68396  rc = SQLITE_TOOBIG;
68397  goto vdbe_error_halt;
68398
68399  /* Jump to here if a malloc() fails.
68400  */
68401no_mem:
68402  db->mallocFailed = 1;
68403  sqlite3SetString(&p->zErrMsg, db, "out of memory");
68404  rc = SQLITE_NOMEM;
68405  goto vdbe_error_halt;
68406
68407  /* Jump to here for any other kind of fatal error.  The "rc" variable
68408  ** should hold the error number.
68409  */
68410abort_due_to_error:
68411  assert( p->zErrMsg==0 );
68412  if( db->mallocFailed ) rc = SQLITE_NOMEM;
68413  if( rc!=SQLITE_IOERR_NOMEM ){
68414    sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3ErrStr(rc));
68415  }
68416  goto vdbe_error_halt;
68417
68418  /* Jump to here if the sqlite3_interrupt() API sets the interrupt
68419  ** flag.
68420  */
68421abort_due_to_interrupt:
68422  assert( db->u1.isInterrupted );
68423  rc = SQLITE_INTERRUPT;
68424  p->rc = rc;
68425  sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3ErrStr(rc));
68426  goto vdbe_error_halt;
68427}
68428
68429/************** End of vdbe.c ************************************************/
68430/************** Begin file vdbeblob.c ****************************************/
68431/*
68432** 2007 May 1
68433**
68434** The author disclaims copyright to this source code.  In place of
68435** a legal notice, here is a blessing:
68436**
68437**    May you do good and not evil.
68438**    May you find forgiveness for yourself and forgive others.
68439**    May you share freely, never taking more than you give.
68440**
68441*************************************************************************
68442**
68443** This file contains code used to implement incremental BLOB I/O.
68444*/
68445
68446
68447#ifndef SQLITE_OMIT_INCRBLOB
68448
68449/*
68450** Valid sqlite3_blob* handles point to Incrblob structures.
68451*/
68452typedef struct Incrblob Incrblob;
68453struct Incrblob {
68454  int flags;              /* Copy of "flags" passed to sqlite3_blob_open() */
68455  int nByte;              /* Size of open blob, in bytes */
68456  int iOffset;            /* Byte offset of blob in cursor data */
68457  int iCol;               /* Table column this handle is open on */
68458  BtCursor *pCsr;         /* Cursor pointing at blob row */
68459  sqlite3_stmt *pStmt;    /* Statement holding cursor open */
68460  sqlite3 *db;            /* The associated database */
68461};
68462
68463
68464/*
68465** This function is used by both blob_open() and blob_reopen(). It seeks
68466** the b-tree cursor associated with blob handle p to point to row iRow.
68467** If successful, SQLITE_OK is returned and subsequent calls to
68468** sqlite3_blob_read() or sqlite3_blob_write() access the specified row.
68469**
68470** If an error occurs, or if the specified row does not exist or does not
68471** contain a value of type TEXT or BLOB in the column nominated when the
68472** blob handle was opened, then an error code is returned and *pzErr may
68473** be set to point to a buffer containing an error message. It is the
68474** responsibility of the caller to free the error message buffer using
68475** sqlite3DbFree().
68476**
68477** If an error does occur, then the b-tree cursor is closed. All subsequent
68478** calls to sqlite3_blob_read(), blob_write() or blob_reopen() will
68479** immediately return SQLITE_ABORT.
68480*/
68481static int blobSeekToRow(Incrblob *p, sqlite3_int64 iRow, char **pzErr){
68482  int rc;                         /* Error code */
68483  char *zErr = 0;                 /* Error message */
68484  Vdbe *v = (Vdbe *)p->pStmt;
68485
68486  /* Set the value of the SQL statements only variable to integer iRow.
68487  ** This is done directly instead of using sqlite3_bind_int64() to avoid
68488  ** triggering asserts related to mutexes.
68489  */
68490  assert( v->aVar[0].flags&MEM_Int );
68491  v->aVar[0].u.i = iRow;
68492
68493  rc = sqlite3_step(p->pStmt);
68494  if( rc==SQLITE_ROW ){
68495    u32 type = v->apCsr[0]->aType[p->iCol];
68496    if( type<12 ){
68497      zErr = sqlite3MPrintf(p->db, "cannot open value of type %s",
68498          type==0?"null": type==7?"real": "integer"
68499      );
68500      rc = SQLITE_ERROR;
68501      sqlite3_finalize(p->pStmt);
68502      p->pStmt = 0;
68503    }else{
68504      p->iOffset = v->apCsr[0]->aOffset[p->iCol];
68505      p->nByte = sqlite3VdbeSerialTypeLen(type);
68506      p->pCsr =  v->apCsr[0]->pCursor;
68507      sqlite3BtreeEnterCursor(p->pCsr);
68508      sqlite3BtreeCacheOverflow(p->pCsr);
68509      sqlite3BtreeLeaveCursor(p->pCsr);
68510    }
68511  }
68512
68513  if( rc==SQLITE_ROW ){
68514    rc = SQLITE_OK;
68515  }else if( p->pStmt ){
68516    rc = sqlite3_finalize(p->pStmt);
68517    p->pStmt = 0;
68518    if( rc==SQLITE_OK ){
68519      zErr = sqlite3MPrintf(p->db, "no such rowid: %lld", iRow);
68520      rc = SQLITE_ERROR;
68521    }else{
68522      zErr = sqlite3MPrintf(p->db, "%s", sqlite3_errmsg(p->db));
68523    }
68524  }
68525
68526  assert( rc!=SQLITE_OK || zErr==0 );
68527  assert( rc!=SQLITE_ROW && rc!=SQLITE_DONE );
68528
68529  *pzErr = zErr;
68530  return rc;
68531}
68532
68533/*
68534** Open a blob handle.
68535*/
68536SQLITE_API int sqlite3_blob_open(
68537  sqlite3* db,            /* The database connection */
68538  const char *zDb,        /* The attached database containing the blob */
68539  const char *zTable,     /* The table containing the blob */
68540  const char *zColumn,    /* The column containing the blob */
68541  sqlite_int64 iRow,      /* The row containing the glob */
68542  int flags,              /* True -> read/write access, false -> read-only */
68543  sqlite3_blob **ppBlob   /* Handle for accessing the blob returned here */
68544){
68545  int nAttempt = 0;
68546  int iCol;               /* Index of zColumn in row-record */
68547
68548  /* This VDBE program seeks a btree cursor to the identified
68549  ** db/table/row entry. The reason for using a vdbe program instead
68550  ** of writing code to use the b-tree layer directly is that the
68551  ** vdbe program will take advantage of the various transaction,
68552  ** locking and error handling infrastructure built into the vdbe.
68553  **
68554  ** After seeking the cursor, the vdbe executes an OP_ResultRow.
68555  ** Code external to the Vdbe then "borrows" the b-tree cursor and
68556  ** uses it to implement the blob_read(), blob_write() and
68557  ** blob_bytes() functions.
68558  **
68559  ** The sqlite3_blob_close() function finalizes the vdbe program,
68560  ** which closes the b-tree cursor and (possibly) commits the
68561  ** transaction.
68562  */
68563  static const VdbeOpList openBlob[] = {
68564    {OP_Transaction, 0, 0, 0},     /* 0: Start a transaction */
68565    {OP_VerifyCookie, 0, 0, 0},    /* 1: Check the schema cookie */
68566    {OP_TableLock, 0, 0, 0},       /* 2: Acquire a read or write lock */
68567
68568    /* One of the following two instructions is replaced by an OP_Noop. */
68569    {OP_OpenRead, 0, 0, 0},        /* 3: Open cursor 0 for reading */
68570    {OP_OpenWrite, 0, 0, 0},       /* 4: Open cursor 0 for read/write */
68571
68572    {OP_Variable, 1, 1, 1},        /* 5: Push the rowid to the stack */
68573    {OP_NotExists, 0, 10, 1},      /* 6: Seek the cursor */
68574    {OP_Column, 0, 0, 1},          /* 7  */
68575    {OP_ResultRow, 1, 0, 0},       /* 8  */
68576    {OP_Goto, 0, 5, 0},            /* 9  */
68577    {OP_Close, 0, 0, 0},           /* 10 */
68578    {OP_Halt, 0, 0, 0},            /* 11 */
68579  };
68580
68581  int rc = SQLITE_OK;
68582  char *zErr = 0;
68583  Table *pTab;
68584  Parse *pParse = 0;
68585  Incrblob *pBlob = 0;
68586
68587  flags = !!flags;                /* flags = (flags ? 1 : 0); */
68588  *ppBlob = 0;
68589
68590  sqlite3_mutex_enter(db->mutex);
68591
68592  pBlob = (Incrblob *)sqlite3DbMallocZero(db, sizeof(Incrblob));
68593  if( !pBlob ) goto blob_open_out;
68594  pParse = sqlite3StackAllocRaw(db, sizeof(*pParse));
68595  if( !pParse ) goto blob_open_out;
68596
68597  do {
68598    memset(pParse, 0, sizeof(Parse));
68599    pParse->db = db;
68600    sqlite3DbFree(db, zErr);
68601    zErr = 0;
68602
68603    sqlite3BtreeEnterAll(db);
68604    pTab = sqlite3LocateTable(pParse, 0, zTable, zDb);
68605    if( pTab && IsVirtual(pTab) ){
68606      pTab = 0;
68607      sqlite3ErrorMsg(pParse, "cannot open virtual table: %s", zTable);
68608    }
68609#ifndef SQLITE_OMIT_VIEW
68610    if( pTab && pTab->pSelect ){
68611      pTab = 0;
68612      sqlite3ErrorMsg(pParse, "cannot open view: %s", zTable);
68613    }
68614#endif
68615    if( !pTab ){
68616      if( pParse->zErrMsg ){
68617        sqlite3DbFree(db, zErr);
68618        zErr = pParse->zErrMsg;
68619        pParse->zErrMsg = 0;
68620      }
68621      rc = SQLITE_ERROR;
68622      sqlite3BtreeLeaveAll(db);
68623      goto blob_open_out;
68624    }
68625
68626    /* Now search pTab for the exact column. */
68627    for(iCol=0; iCol<pTab->nCol; iCol++) {
68628      if( sqlite3StrICmp(pTab->aCol[iCol].zName, zColumn)==0 ){
68629        break;
68630      }
68631    }
68632    if( iCol==pTab->nCol ){
68633      sqlite3DbFree(db, zErr);
68634      zErr = sqlite3MPrintf(db, "no such column: \"%s\"", zColumn);
68635      rc = SQLITE_ERROR;
68636      sqlite3BtreeLeaveAll(db);
68637      goto blob_open_out;
68638    }
68639
68640    /* If the value is being opened for writing, check that the
68641    ** column is not indexed, and that it is not part of a foreign key.
68642    ** It is against the rules to open a column to which either of these
68643    ** descriptions applies for writing.  */
68644    if( flags ){
68645      const char *zFault = 0;
68646      Index *pIdx;
68647#ifndef SQLITE_OMIT_FOREIGN_KEY
68648      if( db->flags&SQLITE_ForeignKeys ){
68649        /* Check that the column is not part of an FK child key definition. It
68650        ** is not necessary to check if it is part of a parent key, as parent
68651        ** key columns must be indexed. The check below will pick up this
68652        ** case.  */
68653        FKey *pFKey;
68654        for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
68655          int j;
68656          for(j=0; j<pFKey->nCol; j++){
68657            if( pFKey->aCol[j].iFrom==iCol ){
68658              zFault = "foreign key";
68659            }
68660          }
68661        }
68662      }
68663#endif
68664      for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
68665        int j;
68666        for(j=0; j<pIdx->nColumn; j++){
68667          if( pIdx->aiColumn[j]==iCol ){
68668            zFault = "indexed";
68669          }
68670        }
68671      }
68672      if( zFault ){
68673        sqlite3DbFree(db, zErr);
68674        zErr = sqlite3MPrintf(db, "cannot open %s column for writing", zFault);
68675        rc = SQLITE_ERROR;
68676        sqlite3BtreeLeaveAll(db);
68677        goto blob_open_out;
68678      }
68679    }
68680
68681    pBlob->pStmt = (sqlite3_stmt *)sqlite3VdbeCreate(db);
68682    assert( pBlob->pStmt || db->mallocFailed );
68683    if( pBlob->pStmt ){
68684      Vdbe *v = (Vdbe *)pBlob->pStmt;
68685      int iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
68686
68687      sqlite3VdbeAddOpList(v, sizeof(openBlob)/sizeof(VdbeOpList), openBlob);
68688
68689
68690      /* Configure the OP_Transaction */
68691      sqlite3VdbeChangeP1(v, 0, iDb);
68692      sqlite3VdbeChangeP2(v, 0, flags);
68693
68694      /* Configure the OP_VerifyCookie */
68695      sqlite3VdbeChangeP1(v, 1, iDb);
68696      sqlite3VdbeChangeP2(v, 1, pTab->pSchema->schema_cookie);
68697      sqlite3VdbeChangeP3(v, 1, pTab->pSchema->iGeneration);
68698
68699      /* Make sure a mutex is held on the table to be accessed */
68700      sqlite3VdbeUsesBtree(v, iDb);
68701
68702      /* Configure the OP_TableLock instruction */
68703#ifdef SQLITE_OMIT_SHARED_CACHE
68704      sqlite3VdbeChangeToNoop(v, 2, 1);
68705#else
68706      sqlite3VdbeChangeP1(v, 2, iDb);
68707      sqlite3VdbeChangeP2(v, 2, pTab->tnum);
68708      sqlite3VdbeChangeP3(v, 2, flags);
68709      sqlite3VdbeChangeP4(v, 2, pTab->zName, P4_TRANSIENT);
68710#endif
68711
68712      /* Remove either the OP_OpenWrite or OpenRead. Set the P2
68713      ** parameter of the other to pTab->tnum.  */
68714      sqlite3VdbeChangeToNoop(v, 4 - flags, 1);
68715      sqlite3VdbeChangeP2(v, 3 + flags, pTab->tnum);
68716      sqlite3VdbeChangeP3(v, 3 + flags, iDb);
68717
68718      /* Configure the number of columns. Configure the cursor to
68719      ** think that the table has one more column than it really
68720      ** does. An OP_Column to retrieve this imaginary column will
68721      ** always return an SQL NULL. This is useful because it means
68722      ** we can invoke OP_Column to fill in the vdbe cursors type
68723      ** and offset cache without causing any IO.
68724      */
68725      sqlite3VdbeChangeP4(v, 3+flags, SQLITE_INT_TO_PTR(pTab->nCol+1),P4_INT32);
68726      sqlite3VdbeChangeP2(v, 7, pTab->nCol);
68727      if( !db->mallocFailed ){
68728        sqlite3VdbeMakeReady(v, 1, 1, 1, 0, 0, 0);
68729      }
68730    }
68731
68732    pBlob->flags = flags;
68733    pBlob->iCol = iCol;
68734    pBlob->db = db;
68735    sqlite3BtreeLeaveAll(db);
68736    if( db->mallocFailed ){
68737      goto blob_open_out;
68738    }
68739    sqlite3_bind_int64(pBlob->pStmt, 1, iRow);
68740    rc = blobSeekToRow(pBlob, iRow, &zErr);
68741  } while( (++nAttempt)<5 && rc==SQLITE_SCHEMA );
68742
68743blob_open_out:
68744  if( rc==SQLITE_OK && db->mallocFailed==0 ){
68745    *ppBlob = (sqlite3_blob *)pBlob;
68746  }else{
68747    if( pBlob && pBlob->pStmt ) sqlite3VdbeFinalize((Vdbe *)pBlob->pStmt);
68748    sqlite3DbFree(db, pBlob);
68749  }
68750  sqlite3Error(db, rc, (zErr ? "%s" : 0), zErr);
68751  sqlite3DbFree(db, zErr);
68752  sqlite3StackFree(db, pParse);
68753  rc = sqlite3ApiExit(db, rc);
68754  sqlite3_mutex_leave(db->mutex);
68755  return rc;
68756}
68757
68758/*
68759** Close a blob handle that was previously created using
68760** sqlite3_blob_open().
68761*/
68762SQLITE_API int sqlite3_blob_close(sqlite3_blob *pBlob){
68763  Incrblob *p = (Incrblob *)pBlob;
68764  int rc;
68765  sqlite3 *db;
68766
68767  if( p ){
68768    db = p->db;
68769    sqlite3_mutex_enter(db->mutex);
68770    rc = sqlite3_finalize(p->pStmt);
68771    sqlite3DbFree(db, p);
68772    sqlite3_mutex_leave(db->mutex);
68773  }else{
68774    rc = SQLITE_OK;
68775  }
68776  return rc;
68777}
68778
68779/*
68780** Perform a read or write operation on a blob
68781*/
68782static int blobReadWrite(
68783  sqlite3_blob *pBlob,
68784  void *z,
68785  int n,
68786  int iOffset,
68787  int (*xCall)(BtCursor*, u32, u32, void*)
68788){
68789  int rc;
68790  Incrblob *p = (Incrblob *)pBlob;
68791  Vdbe *v;
68792  sqlite3 *db;
68793
68794  if( p==0 ) return SQLITE_MISUSE_BKPT;
68795  db = p->db;
68796  sqlite3_mutex_enter(db->mutex);
68797  v = (Vdbe*)p->pStmt;
68798
68799  if( n<0 || iOffset<0 || (iOffset+n)>p->nByte ){
68800    /* Request is out of range. Return a transient error. */
68801    rc = SQLITE_ERROR;
68802    sqlite3Error(db, SQLITE_ERROR, 0);
68803  }else if( v==0 ){
68804    /* If there is no statement handle, then the blob-handle has
68805    ** already been invalidated. Return SQLITE_ABORT in this case.
68806    */
68807    rc = SQLITE_ABORT;
68808  }else{
68809    /* Call either BtreeData() or BtreePutData(). If SQLITE_ABORT is
68810    ** returned, clean-up the statement handle.
68811    */
68812    assert( db == v->db );
68813    sqlite3BtreeEnterCursor(p->pCsr);
68814    rc = xCall(p->pCsr, iOffset+p->iOffset, n, z);
68815    sqlite3BtreeLeaveCursor(p->pCsr);
68816    if( rc==SQLITE_ABORT ){
68817      sqlite3VdbeFinalize(v);
68818      p->pStmt = 0;
68819    }else{
68820      db->errCode = rc;
68821      v->rc = rc;
68822    }
68823  }
68824  rc = sqlite3ApiExit(db, rc);
68825  sqlite3_mutex_leave(db->mutex);
68826  return rc;
68827}
68828
68829/*
68830** Read data from a blob handle.
68831*/
68832SQLITE_API int sqlite3_blob_read(sqlite3_blob *pBlob, void *z, int n, int iOffset){
68833  return blobReadWrite(pBlob, z, n, iOffset, sqlite3BtreeData);
68834}
68835
68836/*
68837** Write data to a blob handle.
68838*/
68839SQLITE_API int sqlite3_blob_write(sqlite3_blob *pBlob, const void *z, int n, int iOffset){
68840  return blobReadWrite(pBlob, (void *)z, n, iOffset, sqlite3BtreePutData);
68841}
68842
68843/*
68844** Query a blob handle for the size of the data.
68845**
68846** The Incrblob.nByte field is fixed for the lifetime of the Incrblob
68847** so no mutex is required for access.
68848*/
68849SQLITE_API int sqlite3_blob_bytes(sqlite3_blob *pBlob){
68850  Incrblob *p = (Incrblob *)pBlob;
68851  return (p && p->pStmt) ? p->nByte : 0;
68852}
68853
68854/*
68855** Move an existing blob handle to point to a different row of the same
68856** database table.
68857**
68858** If an error occurs, or if the specified row does not exist or does not
68859** contain a blob or text value, then an error code is returned and the
68860** database handle error code and message set. If this happens, then all
68861** subsequent calls to sqlite3_blob_xxx() functions (except blob_close())
68862** immediately return SQLITE_ABORT.
68863*/
68864SQLITE_API int sqlite3_blob_reopen(sqlite3_blob *pBlob, sqlite3_int64 iRow){
68865  int rc;
68866  Incrblob *p = (Incrblob *)pBlob;
68867  sqlite3 *db;
68868
68869  if( p==0 ) return SQLITE_MISUSE_BKPT;
68870  db = p->db;
68871  sqlite3_mutex_enter(db->mutex);
68872
68873  if( p->pStmt==0 ){
68874    /* If there is no statement handle, then the blob-handle has
68875    ** already been invalidated. Return SQLITE_ABORT in this case.
68876    */
68877    rc = SQLITE_ABORT;
68878  }else{
68879    char *zErr;
68880    rc = blobSeekToRow(p, iRow, &zErr);
68881    if( rc!=SQLITE_OK ){
68882      sqlite3Error(db, rc, (zErr ? "%s" : 0), zErr);
68883      sqlite3DbFree(db, zErr);
68884    }
68885    assert( rc!=SQLITE_SCHEMA );
68886  }
68887
68888  rc = sqlite3ApiExit(db, rc);
68889  assert( rc==SQLITE_OK || p->pStmt==0 );
68890  sqlite3_mutex_leave(db->mutex);
68891  return rc;
68892}
68893
68894#endif /* #ifndef SQLITE_OMIT_INCRBLOB */
68895
68896/************** End of vdbeblob.c ********************************************/
68897/************** Begin file journal.c *****************************************/
68898/*
68899** 2007 August 22
68900**
68901** The author disclaims copyright to this source code.  In place of
68902** a legal notice, here is a blessing:
68903**
68904**    May you do good and not evil.
68905**    May you find forgiveness for yourself and forgive others.
68906**    May you share freely, never taking more than you give.
68907**
68908*************************************************************************
68909**
68910** This file implements a special kind of sqlite3_file object used
68911** by SQLite to create journal files if the atomic-write optimization
68912** is enabled.
68913**
68914** The distinctive characteristic of this sqlite3_file is that the
68915** actual on disk file is created lazily. When the file is created,
68916** the caller specifies a buffer size for an in-memory buffer to
68917** be used to service read() and write() requests. The actual file
68918** on disk is not created or populated until either:
68919**
68920**   1) The in-memory representation grows too large for the allocated
68921**      buffer, or
68922**   2) The sqlite3JournalCreate() function is called.
68923*/
68924#ifdef SQLITE_ENABLE_ATOMIC_WRITE
68925
68926
68927/*
68928** A JournalFile object is a subclass of sqlite3_file used by
68929** as an open file handle for journal files.
68930*/
68931struct JournalFile {
68932  sqlite3_io_methods *pMethod;    /* I/O methods on journal files */
68933  int nBuf;                       /* Size of zBuf[] in bytes */
68934  char *zBuf;                     /* Space to buffer journal writes */
68935  int iSize;                      /* Amount of zBuf[] currently used */
68936  int flags;                      /* xOpen flags */
68937  sqlite3_vfs *pVfs;              /* The "real" underlying VFS */
68938  sqlite3_file *pReal;            /* The "real" underlying file descriptor */
68939  const char *zJournal;           /* Name of the journal file */
68940};
68941typedef struct JournalFile JournalFile;
68942
68943/*
68944** If it does not already exists, create and populate the on-disk file
68945** for JournalFile p.
68946*/
68947static int createFile(JournalFile *p){
68948  int rc = SQLITE_OK;
68949  if( !p->pReal ){
68950    sqlite3_file *pReal = (sqlite3_file *)&p[1];
68951    rc = sqlite3OsOpen(p->pVfs, p->zJournal, pReal, p->flags, 0);
68952    if( rc==SQLITE_OK ){
68953      p->pReal = pReal;
68954      if( p->iSize>0 ){
68955        assert(p->iSize<=p->nBuf);
68956        rc = sqlite3OsWrite(p->pReal, p->zBuf, p->iSize, 0);
68957      }
68958    }
68959  }
68960  return rc;
68961}
68962
68963/*
68964** Close the file.
68965*/
68966static int jrnlClose(sqlite3_file *pJfd){
68967  JournalFile *p = (JournalFile *)pJfd;
68968  if( p->pReal ){
68969    sqlite3OsClose(p->pReal);
68970  }
68971  sqlite3_free(p->zBuf);
68972  return SQLITE_OK;
68973}
68974
68975/*
68976** Read data from the file.
68977*/
68978static int jrnlRead(
68979  sqlite3_file *pJfd,    /* The journal file from which to read */
68980  void *zBuf,            /* Put the results here */
68981  int iAmt,              /* Number of bytes to read */
68982  sqlite_int64 iOfst     /* Begin reading at this offset */
68983){
68984  int rc = SQLITE_OK;
68985  JournalFile *p = (JournalFile *)pJfd;
68986  if( p->pReal ){
68987    rc = sqlite3OsRead(p->pReal, zBuf, iAmt, iOfst);
68988  }else if( (iAmt+iOfst)>p->iSize ){
68989    rc = SQLITE_IOERR_SHORT_READ;
68990  }else{
68991    memcpy(zBuf, &p->zBuf[iOfst], iAmt);
68992  }
68993  return rc;
68994}
68995
68996/*
68997** Write data to the file.
68998*/
68999static int jrnlWrite(
69000  sqlite3_file *pJfd,    /* The journal file into which to write */
69001  const void *zBuf,      /* Take data to be written from here */
69002  int iAmt,              /* Number of bytes to write */
69003  sqlite_int64 iOfst     /* Begin writing at this offset into the file */
69004){
69005  int rc = SQLITE_OK;
69006  JournalFile *p = (JournalFile *)pJfd;
69007  if( !p->pReal && (iOfst+iAmt)>p->nBuf ){
69008    rc = createFile(p);
69009  }
69010  if( rc==SQLITE_OK ){
69011    if( p->pReal ){
69012      rc = sqlite3OsWrite(p->pReal, zBuf, iAmt, iOfst);
69013    }else{
69014      memcpy(&p->zBuf[iOfst], zBuf, iAmt);
69015      if( p->iSize<(iOfst+iAmt) ){
69016        p->iSize = (iOfst+iAmt);
69017      }
69018    }
69019  }
69020  return rc;
69021}
69022
69023/*
69024** Truncate the file.
69025*/
69026static int jrnlTruncate(sqlite3_file *pJfd, sqlite_int64 size){
69027  int rc = SQLITE_OK;
69028  JournalFile *p = (JournalFile *)pJfd;
69029  if( p->pReal ){
69030    rc = sqlite3OsTruncate(p->pReal, size);
69031  }else if( size<p->iSize ){
69032    p->iSize = size;
69033  }
69034  return rc;
69035}
69036
69037/*
69038** Sync the file.
69039*/
69040static int jrnlSync(sqlite3_file *pJfd, int flags){
69041  int rc;
69042  JournalFile *p = (JournalFile *)pJfd;
69043  if( p->pReal ){
69044    rc = sqlite3OsSync(p->pReal, flags);
69045  }else{
69046    rc = SQLITE_OK;
69047  }
69048  return rc;
69049}
69050
69051/*
69052** Query the size of the file in bytes.
69053*/
69054static int jrnlFileSize(sqlite3_file *pJfd, sqlite_int64 *pSize){
69055  int rc = SQLITE_OK;
69056  JournalFile *p = (JournalFile *)pJfd;
69057  if( p->pReal ){
69058    rc = sqlite3OsFileSize(p->pReal, pSize);
69059  }else{
69060    *pSize = (sqlite_int64) p->iSize;
69061  }
69062  return rc;
69063}
69064
69065/*
69066** Table of methods for JournalFile sqlite3_file object.
69067*/
69068static struct sqlite3_io_methods JournalFileMethods = {
69069  1,             /* iVersion */
69070  jrnlClose,     /* xClose */
69071  jrnlRead,      /* xRead */
69072  jrnlWrite,     /* xWrite */
69073  jrnlTruncate,  /* xTruncate */
69074  jrnlSync,      /* xSync */
69075  jrnlFileSize,  /* xFileSize */
69076  0,             /* xLock */
69077  0,             /* xUnlock */
69078  0,             /* xCheckReservedLock */
69079  0,             /* xFileControl */
69080  0,             /* xSectorSize */
69081  0,             /* xDeviceCharacteristics */
69082  0,             /* xShmMap */
69083  0,             /* xShmLock */
69084  0,             /* xShmBarrier */
69085  0              /* xShmUnmap */
69086};
69087
69088/*
69089** Open a journal file.
69090*/
69091SQLITE_PRIVATE int sqlite3JournalOpen(
69092  sqlite3_vfs *pVfs,         /* The VFS to use for actual file I/O */
69093  const char *zName,         /* Name of the journal file */
69094  sqlite3_file *pJfd,        /* Preallocated, blank file handle */
69095  int flags,                 /* Opening flags */
69096  int nBuf                   /* Bytes buffered before opening the file */
69097){
69098  JournalFile *p = (JournalFile *)pJfd;
69099  memset(p, 0, sqlite3JournalSize(pVfs));
69100  if( nBuf>0 ){
69101    p->zBuf = sqlite3MallocZero(nBuf);
69102    if( !p->zBuf ){
69103      return SQLITE_NOMEM;
69104    }
69105  }else{
69106    return sqlite3OsOpen(pVfs, zName, pJfd, flags, 0);
69107  }
69108  p->pMethod = &JournalFileMethods;
69109  p->nBuf = nBuf;
69110  p->flags = flags;
69111  p->zJournal = zName;
69112  p->pVfs = pVfs;
69113  return SQLITE_OK;
69114}
69115
69116/*
69117** If the argument p points to a JournalFile structure, and the underlying
69118** file has not yet been created, create it now.
69119*/
69120SQLITE_PRIVATE int sqlite3JournalCreate(sqlite3_file *p){
69121  if( p->pMethods!=&JournalFileMethods ){
69122    return SQLITE_OK;
69123  }
69124  return createFile((JournalFile *)p);
69125}
69126
69127/*
69128** Return the number of bytes required to store a JournalFile that uses vfs
69129** pVfs to create the underlying on-disk files.
69130*/
69131SQLITE_PRIVATE int sqlite3JournalSize(sqlite3_vfs *pVfs){
69132  return (pVfs->szOsFile+sizeof(JournalFile));
69133}
69134#endif
69135
69136/************** End of journal.c *********************************************/
69137/************** Begin file memjournal.c **************************************/
69138/*
69139** 2008 October 7
69140**
69141** The author disclaims copyright to this source code.  In place of
69142** a legal notice, here is a blessing:
69143**
69144**    May you do good and not evil.
69145**    May you find forgiveness for yourself and forgive others.
69146**    May you share freely, never taking more than you give.
69147**
69148*************************************************************************
69149**
69150** This file contains code use to implement an in-memory rollback journal.
69151** The in-memory rollback journal is used to journal transactions for
69152** ":memory:" databases and when the journal_mode=MEMORY pragma is used.
69153*/
69154
69155/* Forward references to internal structures */
69156typedef struct MemJournal MemJournal;
69157typedef struct FilePoint FilePoint;
69158typedef struct FileChunk FileChunk;
69159
69160/* Space to hold the rollback journal is allocated in increments of
69161** this many bytes.
69162**
69163** The size chosen is a little less than a power of two.  That way,
69164** the FileChunk object will have a size that almost exactly fills
69165** a power-of-two allocation.  This mimimizes wasted space in power-of-two
69166** memory allocators.
69167*/
69168#define JOURNAL_CHUNKSIZE ((int)(1024-sizeof(FileChunk*)))
69169
69170/* Macro to find the minimum of two numeric values.
69171*/
69172#ifndef MIN
69173# define MIN(x,y) ((x)<(y)?(x):(y))
69174#endif
69175
69176/*
69177** The rollback journal is composed of a linked list of these structures.
69178*/
69179struct FileChunk {
69180  FileChunk *pNext;               /* Next chunk in the journal */
69181  u8 zChunk[JOURNAL_CHUNKSIZE];   /* Content of this chunk */
69182};
69183
69184/*
69185** An instance of this object serves as a cursor into the rollback journal.
69186** The cursor can be either for reading or writing.
69187*/
69188struct FilePoint {
69189  sqlite3_int64 iOffset;          /* Offset from the beginning of the file */
69190  FileChunk *pChunk;              /* Specific chunk into which cursor points */
69191};
69192
69193/*
69194** This subclass is a subclass of sqlite3_file.  Each open memory-journal
69195** is an instance of this class.
69196*/
69197struct MemJournal {
69198  sqlite3_io_methods *pMethod;    /* Parent class. MUST BE FIRST */
69199  FileChunk *pFirst;              /* Head of in-memory chunk-list */
69200  FilePoint endpoint;             /* Pointer to the end of the file */
69201  FilePoint readpoint;            /* Pointer to the end of the last xRead() */
69202};
69203
69204/*
69205** Read data from the in-memory journal file.  This is the implementation
69206** of the sqlite3_vfs.xRead method.
69207*/
69208static int memjrnlRead(
69209  sqlite3_file *pJfd,    /* The journal file from which to read */
69210  void *zBuf,            /* Put the results here */
69211  int iAmt,              /* Number of bytes to read */
69212  sqlite_int64 iOfst     /* Begin reading at this offset */
69213){
69214  MemJournal *p = (MemJournal *)pJfd;
69215  u8 *zOut = zBuf;
69216  int nRead = iAmt;
69217  int iChunkOffset;
69218  FileChunk *pChunk;
69219
69220  /* SQLite never tries to read past the end of a rollback journal file */
69221  assert( iOfst+iAmt<=p->endpoint.iOffset );
69222
69223  if( p->readpoint.iOffset!=iOfst || iOfst==0 ){
69224    sqlite3_int64 iOff = 0;
69225    for(pChunk=p->pFirst;
69226        ALWAYS(pChunk) && (iOff+JOURNAL_CHUNKSIZE)<=iOfst;
69227        pChunk=pChunk->pNext
69228    ){
69229      iOff += JOURNAL_CHUNKSIZE;
69230    }
69231  }else{
69232    pChunk = p->readpoint.pChunk;
69233  }
69234
69235  iChunkOffset = (int)(iOfst%JOURNAL_CHUNKSIZE);
69236  do {
69237    int iSpace = JOURNAL_CHUNKSIZE - iChunkOffset;
69238    int nCopy = MIN(nRead, (JOURNAL_CHUNKSIZE - iChunkOffset));
69239    memcpy(zOut, &pChunk->zChunk[iChunkOffset], nCopy);
69240    zOut += nCopy;
69241    nRead -= iSpace;
69242    iChunkOffset = 0;
69243  } while( nRead>=0 && (pChunk=pChunk->pNext)!=0 && nRead>0 );
69244  p->readpoint.iOffset = iOfst+iAmt;
69245  p->readpoint.pChunk = pChunk;
69246
69247  return SQLITE_OK;
69248}
69249
69250/*
69251** Write data to the file.
69252*/
69253static int memjrnlWrite(
69254  sqlite3_file *pJfd,    /* The journal file into which to write */
69255  const void *zBuf,      /* Take data to be written from here */
69256  int iAmt,              /* Number of bytes to write */
69257  sqlite_int64 iOfst     /* Begin writing at this offset into the file */
69258){
69259  MemJournal *p = (MemJournal *)pJfd;
69260  int nWrite = iAmt;
69261  u8 *zWrite = (u8 *)zBuf;
69262
69263  /* An in-memory journal file should only ever be appended to. Random
69264  ** access writes are not required by sqlite.
69265  */
69266  assert( iOfst==p->endpoint.iOffset );
69267  UNUSED_PARAMETER(iOfst);
69268
69269  while( nWrite>0 ){
69270    FileChunk *pChunk = p->endpoint.pChunk;
69271    int iChunkOffset = (int)(p->endpoint.iOffset%JOURNAL_CHUNKSIZE);
69272    int iSpace = MIN(nWrite, JOURNAL_CHUNKSIZE - iChunkOffset);
69273
69274    if( iChunkOffset==0 ){
69275      /* New chunk is required to extend the file. */
69276      FileChunk *pNew = sqlite3_malloc(sizeof(FileChunk));
69277      if( !pNew ){
69278        return SQLITE_IOERR_NOMEM;
69279      }
69280      pNew->pNext = 0;
69281      if( pChunk ){
69282        assert( p->pFirst );
69283        pChunk->pNext = pNew;
69284      }else{
69285        assert( !p->pFirst );
69286        p->pFirst = pNew;
69287      }
69288      p->endpoint.pChunk = pNew;
69289    }
69290
69291    memcpy(&p->endpoint.pChunk->zChunk[iChunkOffset], zWrite, iSpace);
69292    zWrite += iSpace;
69293    nWrite -= iSpace;
69294    p->endpoint.iOffset += iSpace;
69295  }
69296
69297  return SQLITE_OK;
69298}
69299
69300/*
69301** Truncate the file.
69302*/
69303static int memjrnlTruncate(sqlite3_file *pJfd, sqlite_int64 size){
69304  MemJournal *p = (MemJournal *)pJfd;
69305  FileChunk *pChunk;
69306  assert(size==0);
69307  UNUSED_PARAMETER(size);
69308  pChunk = p->pFirst;
69309  while( pChunk ){
69310    FileChunk *pTmp = pChunk;
69311    pChunk = pChunk->pNext;
69312    sqlite3_free(pTmp);
69313  }
69314  sqlite3MemJournalOpen(pJfd);
69315  return SQLITE_OK;
69316}
69317
69318/*
69319** Close the file.
69320*/
69321static int memjrnlClose(sqlite3_file *pJfd){
69322  memjrnlTruncate(pJfd, 0);
69323  return SQLITE_OK;
69324}
69325
69326
69327/*
69328** Sync the file.
69329**
69330** Syncing an in-memory journal is a no-op.  And, in fact, this routine
69331** is never called in a working implementation.  This implementation
69332** exists purely as a contingency, in case some malfunction in some other
69333** part of SQLite causes Sync to be called by mistake.
69334*/
69335static int memjrnlSync(sqlite3_file *NotUsed, int NotUsed2){
69336  UNUSED_PARAMETER2(NotUsed, NotUsed2);
69337  return SQLITE_OK;
69338}
69339
69340/*
69341** Query the size of the file in bytes.
69342*/
69343static int memjrnlFileSize(sqlite3_file *pJfd, sqlite_int64 *pSize){
69344  MemJournal *p = (MemJournal *)pJfd;
69345  *pSize = (sqlite_int64) p->endpoint.iOffset;
69346  return SQLITE_OK;
69347}
69348
69349/*
69350** Table of methods for MemJournal sqlite3_file object.
69351*/
69352static const struct sqlite3_io_methods MemJournalMethods = {
69353  1,                /* iVersion */
69354  memjrnlClose,     /* xClose */
69355  memjrnlRead,      /* xRead */
69356  memjrnlWrite,     /* xWrite */
69357  memjrnlTruncate,  /* xTruncate */
69358  memjrnlSync,      /* xSync */
69359  memjrnlFileSize,  /* xFileSize */
69360  0,                /* xLock */
69361  0,                /* xUnlock */
69362  0,                /* xCheckReservedLock */
69363  0,                /* xFileControl */
69364  0,                /* xSectorSize */
69365  0,                /* xDeviceCharacteristics */
69366  0,                /* xShmMap */
69367  0,                /* xShmLock */
69368  0,                /* xShmBarrier */
69369  0                 /* xShmUnlock */
69370};
69371
69372/*
69373** Open a journal file.
69374*/
69375SQLITE_PRIVATE void sqlite3MemJournalOpen(sqlite3_file *pJfd){
69376  MemJournal *p = (MemJournal *)pJfd;
69377  assert( EIGHT_BYTE_ALIGNMENT(p) );
69378  memset(p, 0, sqlite3MemJournalSize());
69379  p->pMethod = (sqlite3_io_methods*)&MemJournalMethods;
69380}
69381
69382/*
69383** Return true if the file-handle passed as an argument is
69384** an in-memory journal
69385*/
69386SQLITE_PRIVATE int sqlite3IsMemJournal(sqlite3_file *pJfd){
69387  return pJfd->pMethods==&MemJournalMethods;
69388}
69389
69390/*
69391** Return the number of bytes required to store a MemJournal file descriptor.
69392*/
69393SQLITE_PRIVATE int sqlite3MemJournalSize(void){
69394  return sizeof(MemJournal);
69395}
69396
69397/************** End of memjournal.c ******************************************/
69398/************** Begin file walker.c ******************************************/
69399/*
69400** 2008 August 16
69401**
69402** The author disclaims copyright to this source code.  In place of
69403** a legal notice, here is a blessing:
69404**
69405**    May you do good and not evil.
69406**    May you find forgiveness for yourself and forgive others.
69407**    May you share freely, never taking more than you give.
69408**
69409*************************************************************************
69410** This file contains routines used for walking the parser tree for
69411** an SQL statement.
69412*/
69413
69414
69415/*
69416** Walk an expression tree.  Invoke the callback once for each node
69417** of the expression, while decending.  (In other words, the callback
69418** is invoked before visiting children.)
69419**
69420** The return value from the callback should be one of the WRC_*
69421** constants to specify how to proceed with the walk.
69422**
69423**    WRC_Continue      Continue descending down the tree.
69424**
69425**    WRC_Prune         Do not descend into child nodes.  But allow
69426**                      the walk to continue with sibling nodes.
69427**
69428**    WRC_Abort         Do no more callbacks.  Unwind the stack and
69429**                      return the top-level walk call.
69430**
69431** The return value from this routine is WRC_Abort to abandon the tree walk
69432** and WRC_Continue to continue.
69433*/
69434SQLITE_PRIVATE int sqlite3WalkExpr(Walker *pWalker, Expr *pExpr){
69435  int rc;
69436  if( pExpr==0 ) return WRC_Continue;
69437  testcase( ExprHasProperty(pExpr, EP_TokenOnly) );
69438  testcase( ExprHasProperty(pExpr, EP_Reduced) );
69439  rc = pWalker->xExprCallback(pWalker, pExpr);
69440  if( rc==WRC_Continue
69441              && !ExprHasAnyProperty(pExpr,EP_TokenOnly) ){
69442    if( sqlite3WalkExpr(pWalker, pExpr->pLeft) ) return WRC_Abort;
69443    if( sqlite3WalkExpr(pWalker, pExpr->pRight) ) return WRC_Abort;
69444    if( ExprHasProperty(pExpr, EP_xIsSelect) ){
69445      if( sqlite3WalkSelect(pWalker, pExpr->x.pSelect) ) return WRC_Abort;
69446    }else{
69447      if( sqlite3WalkExprList(pWalker, pExpr->x.pList) ) return WRC_Abort;
69448    }
69449  }
69450  return rc & WRC_Abort;
69451}
69452
69453/*
69454** Call sqlite3WalkExpr() for every expression in list p or until
69455** an abort request is seen.
69456*/
69457SQLITE_PRIVATE int sqlite3WalkExprList(Walker *pWalker, ExprList *p){
69458  int i;
69459  struct ExprList_item *pItem;
69460  if( p ){
69461    for(i=p->nExpr, pItem=p->a; i>0; i--, pItem++){
69462      if( sqlite3WalkExpr(pWalker, pItem->pExpr) ) return WRC_Abort;
69463    }
69464  }
69465  return WRC_Continue;
69466}
69467
69468/*
69469** Walk all expressions associated with SELECT statement p.  Do
69470** not invoke the SELECT callback on p, but do (of course) invoke
69471** any expr callbacks and SELECT callbacks that come from subqueries.
69472** Return WRC_Abort or WRC_Continue.
69473*/
69474SQLITE_PRIVATE int sqlite3WalkSelectExpr(Walker *pWalker, Select *p){
69475  if( sqlite3WalkExprList(pWalker, p->pEList) ) return WRC_Abort;
69476  if( sqlite3WalkExpr(pWalker, p->pWhere) ) return WRC_Abort;
69477  if( sqlite3WalkExprList(pWalker, p->pGroupBy) ) return WRC_Abort;
69478  if( sqlite3WalkExpr(pWalker, p->pHaving) ) return WRC_Abort;
69479  if( sqlite3WalkExprList(pWalker, p->pOrderBy) ) return WRC_Abort;
69480  if( sqlite3WalkExpr(pWalker, p->pLimit) ) return WRC_Abort;
69481  if( sqlite3WalkExpr(pWalker, p->pOffset) ) return WRC_Abort;
69482  return WRC_Continue;
69483}
69484
69485/*
69486** Walk the parse trees associated with all subqueries in the
69487** FROM clause of SELECT statement p.  Do not invoke the select
69488** callback on p, but do invoke it on each FROM clause subquery
69489** and on any subqueries further down in the tree.  Return
69490** WRC_Abort or WRC_Continue;
69491*/
69492SQLITE_PRIVATE int sqlite3WalkSelectFrom(Walker *pWalker, Select *p){
69493  SrcList *pSrc;
69494  int i;
69495  struct SrcList_item *pItem;
69496
69497  pSrc = p->pSrc;
69498  if( ALWAYS(pSrc) ){
69499    for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){
69500      if( sqlite3WalkSelect(pWalker, pItem->pSelect) ){
69501        return WRC_Abort;
69502      }
69503    }
69504  }
69505  return WRC_Continue;
69506}
69507
69508/*
69509** Call sqlite3WalkExpr() for every expression in Select statement p.
69510** Invoke sqlite3WalkSelect() for subqueries in the FROM clause and
69511** on the compound select chain, p->pPrior.
69512**
69513** Return WRC_Continue under normal conditions.  Return WRC_Abort if
69514** there is an abort request.
69515**
69516** If the Walker does not have an xSelectCallback() then this routine
69517** is a no-op returning WRC_Continue.
69518*/
69519SQLITE_PRIVATE int sqlite3WalkSelect(Walker *pWalker, Select *p){
69520  int rc;
69521  if( p==0 || pWalker->xSelectCallback==0 ) return WRC_Continue;
69522  rc = WRC_Continue;
69523  while( p  ){
69524    rc = pWalker->xSelectCallback(pWalker, p);
69525    if( rc ) break;
69526    if( sqlite3WalkSelectExpr(pWalker, p) ) return WRC_Abort;
69527    if( sqlite3WalkSelectFrom(pWalker, p) ) return WRC_Abort;
69528    p = p->pPrior;
69529  }
69530  return rc & WRC_Abort;
69531}
69532
69533/************** End of walker.c **********************************************/
69534/************** Begin file resolve.c *****************************************/
69535/*
69536** 2008 August 18
69537**
69538** The author disclaims copyright to this source code.  In place of
69539** a legal notice, here is a blessing:
69540**
69541**    May you do good and not evil.
69542**    May you find forgiveness for yourself and forgive others.
69543**    May you share freely, never taking more than you give.
69544**
69545*************************************************************************
69546**
69547** This file contains routines used for walking the parser tree and
69548** resolve all identifiers by associating them with a particular
69549** table and column.
69550*/
69551
69552/*
69553** Turn the pExpr expression into an alias for the iCol-th column of the
69554** result set in pEList.
69555**
69556** If the result set column is a simple column reference, then this routine
69557** makes an exact copy.  But for any other kind of expression, this
69558** routine make a copy of the result set column as the argument to the
69559** TK_AS operator.  The TK_AS operator causes the expression to be
69560** evaluated just once and then reused for each alias.
69561**
69562** The reason for suppressing the TK_AS term when the expression is a simple
69563** column reference is so that the column reference will be recognized as
69564** usable by indices within the WHERE clause processing logic.
69565**
69566** Hack:  The TK_AS operator is inhibited if zType[0]=='G'.  This means
69567** that in a GROUP BY clause, the expression is evaluated twice.  Hence:
69568**
69569**     SELECT random()%5 AS x, count(*) FROM tab GROUP BY x
69570**
69571** Is equivalent to:
69572**
69573**     SELECT random()%5 AS x, count(*) FROM tab GROUP BY random()%5
69574**
69575** The result of random()%5 in the GROUP BY clause is probably different
69576** from the result in the result-set.  We might fix this someday.  Or
69577** then again, we might not...
69578*/
69579static void resolveAlias(
69580  Parse *pParse,         /* Parsing context */
69581  ExprList *pEList,      /* A result set */
69582  int iCol,              /* A column in the result set.  0..pEList->nExpr-1 */
69583  Expr *pExpr,           /* Transform this into an alias to the result set */
69584  const char *zType      /* "GROUP" or "ORDER" or "" */
69585){
69586  Expr *pOrig;           /* The iCol-th column of the result set */
69587  Expr *pDup;            /* Copy of pOrig */
69588  sqlite3 *db;           /* The database connection */
69589
69590  assert( iCol>=0 && iCol<pEList->nExpr );
69591  pOrig = pEList->a[iCol].pExpr;
69592  assert( pOrig!=0 );
69593  assert( pOrig->flags & EP_Resolved );
69594  db = pParse->db;
69595  if( pOrig->op!=TK_COLUMN && zType[0]!='G' ){
69596    pDup = sqlite3ExprDup(db, pOrig, 0);
69597    pDup = sqlite3PExpr(pParse, TK_AS, pDup, 0, 0);
69598    if( pDup==0 ) return;
69599    if( pEList->a[iCol].iAlias==0 ){
69600      pEList->a[iCol].iAlias = (u16)(++pParse->nAlias);
69601    }
69602    pDup->iTable = pEList->a[iCol].iAlias;
69603  }else if( ExprHasProperty(pOrig, EP_IntValue) || pOrig->u.zToken==0 ){
69604    pDup = sqlite3ExprDup(db, pOrig, 0);
69605    if( pDup==0 ) return;
69606  }else{
69607    char *zToken = pOrig->u.zToken;
69608    assert( zToken!=0 );
69609    pOrig->u.zToken = 0;
69610    pDup = sqlite3ExprDup(db, pOrig, 0);
69611    pOrig->u.zToken = zToken;
69612    if( pDup==0 ) return;
69613    assert( (pDup->flags & (EP_Reduced|EP_TokenOnly))==0 );
69614    pDup->flags2 |= EP2_MallocedToken;
69615    pDup->u.zToken = sqlite3DbStrDup(db, zToken);
69616  }
69617  if( pExpr->flags & EP_ExpCollate ){
69618    pDup->pColl = pExpr->pColl;
69619    pDup->flags |= EP_ExpCollate;
69620  }
69621
69622  /* Before calling sqlite3ExprDelete(), set the EP_Static flag. This
69623  ** prevents ExprDelete() from deleting the Expr structure itself,
69624  ** allowing it to be repopulated by the memcpy() on the following line.
69625  */
69626  ExprSetProperty(pExpr, EP_Static);
69627  sqlite3ExprDelete(db, pExpr);
69628  memcpy(pExpr, pDup, sizeof(*pExpr));
69629  sqlite3DbFree(db, pDup);
69630}
69631
69632/*
69633** Given the name of a column of the form X.Y.Z or Y.Z or just Z, look up
69634** that name in the set of source tables in pSrcList and make the pExpr
69635** expression node refer back to that source column.  The following changes
69636** are made to pExpr:
69637**
69638**    pExpr->iDb           Set the index in db->aDb[] of the database X
69639**                         (even if X is implied).
69640**    pExpr->iTable        Set to the cursor number for the table obtained
69641**                         from pSrcList.
69642**    pExpr->pTab          Points to the Table structure of X.Y (even if
69643**                         X and/or Y are implied.)
69644**    pExpr->iColumn       Set to the column number within the table.
69645**    pExpr->op            Set to TK_COLUMN.
69646**    pExpr->pLeft         Any expression this points to is deleted
69647**    pExpr->pRight        Any expression this points to is deleted.
69648**
69649** The zDb variable is the name of the database (the "X").  This value may be
69650** NULL meaning that name is of the form Y.Z or Z.  Any available database
69651** can be used.  The zTable variable is the name of the table (the "Y").  This
69652** value can be NULL if zDb is also NULL.  If zTable is NULL it
69653** means that the form of the name is Z and that columns from any table
69654** can be used.
69655**
69656** If the name cannot be resolved unambiguously, leave an error message
69657** in pParse and return WRC_Abort.  Return WRC_Prune on success.
69658*/
69659static int lookupName(
69660  Parse *pParse,       /* The parsing context */
69661  const char *zDb,     /* Name of the database containing table, or NULL */
69662  const char *zTab,    /* Name of table containing column, or NULL */
69663  const char *zCol,    /* Name of the column. */
69664  NameContext *pNC,    /* The name context used to resolve the name */
69665  Expr *pExpr          /* Make this EXPR node point to the selected column */
69666){
69667  int i, j;            /* Loop counters */
69668  int cnt = 0;                      /* Number of matching column names */
69669  int cntTab = 0;                   /* Number of matching table names */
69670  sqlite3 *db = pParse->db;         /* The database connection */
69671  struct SrcList_item *pItem;       /* Use for looping over pSrcList items */
69672  struct SrcList_item *pMatch = 0;  /* The matching pSrcList item */
69673  NameContext *pTopNC = pNC;        /* First namecontext in the list */
69674  Schema *pSchema = 0;              /* Schema of the expression */
69675  int isTrigger = 0;
69676
69677  assert( pNC );     /* the name context cannot be NULL. */
69678  assert( zCol );    /* The Z in X.Y.Z cannot be NULL */
69679  assert( ~ExprHasAnyProperty(pExpr, EP_TokenOnly|EP_Reduced) );
69680
69681  /* Initialize the node to no-match */
69682  pExpr->iTable = -1;
69683  pExpr->pTab = 0;
69684  ExprSetIrreducible(pExpr);
69685
69686  /* Start at the inner-most context and move outward until a match is found */
69687  while( pNC && cnt==0 ){
69688    ExprList *pEList;
69689    SrcList *pSrcList = pNC->pSrcList;
69690
69691    if( pSrcList ){
69692      for(i=0, pItem=pSrcList->a; i<pSrcList->nSrc; i++, pItem++){
69693        Table *pTab;
69694        int iDb;
69695        Column *pCol;
69696
69697        pTab = pItem->pTab;
69698        assert( pTab!=0 && pTab->zName!=0 );
69699        iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
69700        assert( pTab->nCol>0 );
69701        if( zTab ){
69702          if( pItem->zAlias ){
69703            char *zTabName = pItem->zAlias;
69704            if( sqlite3StrICmp(zTabName, zTab)!=0 ) continue;
69705          }else{
69706            char *zTabName = pTab->zName;
69707            if( NEVER(zTabName==0) || sqlite3StrICmp(zTabName, zTab)!=0 ){
69708              continue;
69709            }
69710            if( zDb!=0 && sqlite3StrICmp(db->aDb[iDb].zName, zDb)!=0 ){
69711              continue;
69712            }
69713          }
69714        }
69715        if( 0==(cntTab++) ){
69716          pExpr->iTable = pItem->iCursor;
69717          pExpr->pTab = pTab;
69718          pSchema = pTab->pSchema;
69719          pMatch = pItem;
69720        }
69721        for(j=0, pCol=pTab->aCol; j<pTab->nCol; j++, pCol++){
69722          if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
69723            IdList *pUsing;
69724            cnt++;
69725            pExpr->iTable = pItem->iCursor;
69726            pExpr->pTab = pTab;
69727            pMatch = pItem;
69728            pSchema = pTab->pSchema;
69729            /* Substitute the rowid (column -1) for the INTEGER PRIMARY KEY */
69730            pExpr->iColumn = j==pTab->iPKey ? -1 : (i16)j;
69731            if( i<pSrcList->nSrc-1 ){
69732              if( pItem[1].jointype & JT_NATURAL ){
69733                /* If this match occurred in the left table of a natural join,
69734                ** then skip the right table to avoid a duplicate match */
69735                pItem++;
69736                i++;
69737              }else if( (pUsing = pItem[1].pUsing)!=0 ){
69738                /* If this match occurs on a column that is in the USING clause
69739                ** of a join, skip the search of the right table of the join
69740                ** to avoid a duplicate match there. */
69741                int k;
69742                for(k=0; k<pUsing->nId; k++){
69743                  if( sqlite3StrICmp(pUsing->a[k].zName, zCol)==0 ){
69744                    pItem++;
69745                    i++;
69746                    break;
69747                  }
69748                }
69749              }
69750            }
69751            break;
69752          }
69753        }
69754      }
69755    }
69756
69757#ifndef SQLITE_OMIT_TRIGGER
69758    /* If we have not already resolved the name, then maybe
69759    ** it is a new.* or old.* trigger argument reference
69760    */
69761    if( zDb==0 && zTab!=0 && cnt==0 && pParse->pTriggerTab!=0 ){
69762      int op = pParse->eTriggerOp;
69763      Table *pTab = 0;
69764      assert( op==TK_DELETE || op==TK_UPDATE || op==TK_INSERT );
69765      if( op!=TK_DELETE && sqlite3StrICmp("new",zTab) == 0 ){
69766        pExpr->iTable = 1;
69767        pTab = pParse->pTriggerTab;
69768      }else if( op!=TK_INSERT && sqlite3StrICmp("old",zTab)==0 ){
69769        pExpr->iTable = 0;
69770        pTab = pParse->pTriggerTab;
69771      }
69772
69773      if( pTab ){
69774        int iCol;
69775        pSchema = pTab->pSchema;
69776        cntTab++;
69777        for(iCol=0; iCol<pTab->nCol; iCol++){
69778          Column *pCol = &pTab->aCol[iCol];
69779          if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
69780            if( iCol==pTab->iPKey ){
69781              iCol = -1;
69782            }
69783            break;
69784          }
69785        }
69786        if( iCol>=pTab->nCol && sqlite3IsRowid(zCol) ){
69787          iCol = -1;        /* IMP: R-44911-55124 */
69788        }
69789        if( iCol<pTab->nCol ){
69790          cnt++;
69791          if( iCol<0 ){
69792            pExpr->affinity = SQLITE_AFF_INTEGER;
69793          }else if( pExpr->iTable==0 ){
69794            testcase( iCol==31 );
69795            testcase( iCol==32 );
69796            pParse->oldmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
69797          }else{
69798            testcase( iCol==31 );
69799            testcase( iCol==32 );
69800            pParse->newmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
69801          }
69802          pExpr->iColumn = (i16)iCol;
69803          pExpr->pTab = pTab;
69804          isTrigger = 1;
69805        }
69806      }
69807    }
69808#endif /* !defined(SQLITE_OMIT_TRIGGER) */
69809
69810    /*
69811    ** Perhaps the name is a reference to the ROWID
69812    */
69813    if( cnt==0 && cntTab==1 && sqlite3IsRowid(zCol) ){
69814      cnt = 1;
69815      pExpr->iColumn = -1;     /* IMP: R-44911-55124 */
69816      pExpr->affinity = SQLITE_AFF_INTEGER;
69817    }
69818
69819    /*
69820    ** If the input is of the form Z (not Y.Z or X.Y.Z) then the name Z
69821    ** might refer to an result-set alias.  This happens, for example, when
69822    ** we are resolving names in the WHERE clause of the following command:
69823    **
69824    **     SELECT a+b AS x FROM table WHERE x<10;
69825    **
69826    ** In cases like this, replace pExpr with a copy of the expression that
69827    ** forms the result set entry ("a+b" in the example) and return immediately.
69828    ** Note that the expression in the result set should have already been
69829    ** resolved by the time the WHERE clause is resolved.
69830    */
69831    if( cnt==0 && (pEList = pNC->pEList)!=0 && zTab==0 ){
69832      for(j=0; j<pEList->nExpr; j++){
69833        char *zAs = pEList->a[j].zName;
69834        if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
69835          Expr *pOrig;
69836          assert( pExpr->pLeft==0 && pExpr->pRight==0 );
69837          assert( pExpr->x.pList==0 );
69838          assert( pExpr->x.pSelect==0 );
69839          pOrig = pEList->a[j].pExpr;
69840          if( !pNC->allowAgg && ExprHasProperty(pOrig, EP_Agg) ){
69841            sqlite3ErrorMsg(pParse, "misuse of aliased aggregate %s", zAs);
69842            return WRC_Abort;
69843          }
69844          resolveAlias(pParse, pEList, j, pExpr, "");
69845          cnt = 1;
69846          pMatch = 0;
69847          assert( zTab==0 && zDb==0 );
69848          goto lookupname_end;
69849        }
69850      }
69851    }
69852
69853    /* Advance to the next name context.  The loop will exit when either
69854    ** we have a match (cnt>0) or when we run out of name contexts.
69855    */
69856    if( cnt==0 ){
69857      pNC = pNC->pNext;
69858    }
69859  }
69860
69861  /*
69862  ** If X and Y are NULL (in other words if only the column name Z is
69863  ** supplied) and the value of Z is enclosed in double-quotes, then
69864  ** Z is a string literal if it doesn't match any column names.  In that
69865  ** case, we need to return right away and not make any changes to
69866  ** pExpr.
69867  **
69868  ** Because no reference was made to outer contexts, the pNC->nRef
69869  ** fields are not changed in any context.
69870  */
69871  if( cnt==0 && zTab==0 && ExprHasProperty(pExpr,EP_DblQuoted) ){
69872    pExpr->op = TK_STRING;
69873    pExpr->pTab = 0;
69874    return WRC_Prune;
69875  }
69876
69877  /*
69878  ** cnt==0 means there was not match.  cnt>1 means there were two or
69879  ** more matches.  Either way, we have an error.
69880  */
69881  if( cnt!=1 ){
69882    const char *zErr;
69883    zErr = cnt==0 ? "no such column" : "ambiguous column name";
69884    if( zDb ){
69885      sqlite3ErrorMsg(pParse, "%s: %s.%s.%s", zErr, zDb, zTab, zCol);
69886    }else if( zTab ){
69887      sqlite3ErrorMsg(pParse, "%s: %s.%s", zErr, zTab, zCol);
69888    }else{
69889      sqlite3ErrorMsg(pParse, "%s: %s", zErr, zCol);
69890    }
69891    pParse->checkSchema = 1;
69892    pTopNC->nErr++;
69893  }
69894
69895  /* If a column from a table in pSrcList is referenced, then record
69896  ** this fact in the pSrcList.a[].colUsed bitmask.  Column 0 causes
69897  ** bit 0 to be set.  Column 1 sets bit 1.  And so forth.  If the
69898  ** column number is greater than the number of bits in the bitmask
69899  ** then set the high-order bit of the bitmask.
69900  */
69901  if( pExpr->iColumn>=0 && pMatch!=0 ){
69902    int n = pExpr->iColumn;
69903    testcase( n==BMS-1 );
69904    if( n>=BMS ){
69905      n = BMS-1;
69906    }
69907    assert( pMatch->iCursor==pExpr->iTable );
69908    pMatch->colUsed |= ((Bitmask)1)<<n;
69909  }
69910
69911  /* Clean up and return
69912  */
69913  sqlite3ExprDelete(db, pExpr->pLeft);
69914  pExpr->pLeft = 0;
69915  sqlite3ExprDelete(db, pExpr->pRight);
69916  pExpr->pRight = 0;
69917  pExpr->op = (isTrigger ? TK_TRIGGER : TK_COLUMN);
69918lookupname_end:
69919  if( cnt==1 ){
69920    assert( pNC!=0 );
69921    sqlite3AuthRead(pParse, pExpr, pSchema, pNC->pSrcList);
69922    /* Increment the nRef value on all name contexts from TopNC up to
69923    ** the point where the name matched. */
69924    for(;;){
69925      assert( pTopNC!=0 );
69926      pTopNC->nRef++;
69927      if( pTopNC==pNC ) break;
69928      pTopNC = pTopNC->pNext;
69929    }
69930    return WRC_Prune;
69931  } else {
69932    return WRC_Abort;
69933  }
69934}
69935
69936/*
69937** Allocate and return a pointer to an expression to load the column iCol
69938** from datasource iSrc in SrcList pSrc.
69939*/
69940SQLITE_PRIVATE Expr *sqlite3CreateColumnExpr(sqlite3 *db, SrcList *pSrc, int iSrc, int iCol){
69941  Expr *p = sqlite3ExprAlloc(db, TK_COLUMN, 0, 0);
69942  if( p ){
69943    struct SrcList_item *pItem = &pSrc->a[iSrc];
69944    p->pTab = pItem->pTab;
69945    p->iTable = pItem->iCursor;
69946    if( p->pTab->iPKey==iCol ){
69947      p->iColumn = -1;
69948    }else{
69949      p->iColumn = (ynVar)iCol;
69950      testcase( iCol==BMS );
69951      testcase( iCol==BMS-1 );
69952      pItem->colUsed |= ((Bitmask)1)<<(iCol>=BMS ? BMS-1 : iCol);
69953    }
69954    ExprSetProperty(p, EP_Resolved);
69955  }
69956  return p;
69957}
69958
69959/*
69960** This routine is callback for sqlite3WalkExpr().
69961**
69962** Resolve symbolic names into TK_COLUMN operators for the current
69963** node in the expression tree.  Return 0 to continue the search down
69964** the tree or 2 to abort the tree walk.
69965**
69966** This routine also does error checking and name resolution for
69967** function names.  The operator for aggregate functions is changed
69968** to TK_AGG_FUNCTION.
69969*/
69970static int resolveExprStep(Walker *pWalker, Expr *pExpr){
69971  NameContext *pNC;
69972  Parse *pParse;
69973
69974  pNC = pWalker->u.pNC;
69975  assert( pNC!=0 );
69976  pParse = pNC->pParse;
69977  assert( pParse==pWalker->pParse );
69978
69979  if( ExprHasAnyProperty(pExpr, EP_Resolved) ) return WRC_Prune;
69980  ExprSetProperty(pExpr, EP_Resolved);
69981#ifndef NDEBUG
69982  if( pNC->pSrcList && pNC->pSrcList->nAlloc>0 ){
69983    SrcList *pSrcList = pNC->pSrcList;
69984    int i;
69985    for(i=0; i<pNC->pSrcList->nSrc; i++){
69986      assert( pSrcList->a[i].iCursor>=0 && pSrcList->a[i].iCursor<pParse->nTab);
69987    }
69988  }
69989#endif
69990  switch( pExpr->op ){
69991
69992#if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
69993    /* The special operator TK_ROW means use the rowid for the first
69994    ** column in the FROM clause.  This is used by the LIMIT and ORDER BY
69995    ** clause processing on UPDATE and DELETE statements.
69996    */
69997    case TK_ROW: {
69998      SrcList *pSrcList = pNC->pSrcList;
69999      struct SrcList_item *pItem;
70000      assert( pSrcList && pSrcList->nSrc==1 );
70001      pItem = pSrcList->a;
70002      pExpr->op = TK_COLUMN;
70003      pExpr->pTab = pItem->pTab;
70004      pExpr->iTable = pItem->iCursor;
70005      pExpr->iColumn = -1;
70006      pExpr->affinity = SQLITE_AFF_INTEGER;
70007      break;
70008    }
70009#endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY) */
70010
70011    /* A lone identifier is the name of a column.
70012    */
70013    case TK_ID: {
70014      return lookupName(pParse, 0, 0, pExpr->u.zToken, pNC, pExpr);
70015    }
70016
70017    /* A table name and column name:     ID.ID
70018    ** Or a database, table and column:  ID.ID.ID
70019    */
70020    case TK_DOT: {
70021      const char *zColumn;
70022      const char *zTable;
70023      const char *zDb;
70024      Expr *pRight;
70025
70026      /* if( pSrcList==0 ) break; */
70027      pRight = pExpr->pRight;
70028      if( pRight->op==TK_ID ){
70029        zDb = 0;
70030        zTable = pExpr->pLeft->u.zToken;
70031        zColumn = pRight->u.zToken;
70032      }else{
70033        assert( pRight->op==TK_DOT );
70034        zDb = pExpr->pLeft->u.zToken;
70035        zTable = pRight->pLeft->u.zToken;
70036        zColumn = pRight->pRight->u.zToken;
70037      }
70038      return lookupName(pParse, zDb, zTable, zColumn, pNC, pExpr);
70039    }
70040
70041    /* Resolve function names
70042    */
70043    case TK_CONST_FUNC:
70044    case TK_FUNCTION: {
70045      ExprList *pList = pExpr->x.pList;    /* The argument list */
70046      int n = pList ? pList->nExpr : 0;    /* Number of arguments */
70047      int no_such_func = 0;       /* True if no such function exists */
70048      int wrong_num_args = 0;     /* True if wrong number of arguments */
70049      int is_agg = 0;             /* True if is an aggregate function */
70050      int auth;                   /* Authorization to use the function */
70051      int nId;                    /* Number of characters in function name */
70052      const char *zId;            /* The function name. */
70053      FuncDef *pDef;              /* Information about the function */
70054      u8 enc = ENC(pParse->db);   /* The database encoding */
70055
70056      testcase( pExpr->op==TK_CONST_FUNC );
70057      assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
70058      zId = pExpr->u.zToken;
70059      nId = sqlite3Strlen30(zId);
70060      pDef = sqlite3FindFunction(pParse->db, zId, nId, n, enc, 0);
70061      if( pDef==0 ){
70062        pDef = sqlite3FindFunction(pParse->db, zId, nId, -1, enc, 0);
70063        if( pDef==0 ){
70064          no_such_func = 1;
70065        }else{
70066          wrong_num_args = 1;
70067        }
70068      }else{
70069        is_agg = pDef->xFunc==0;
70070      }
70071#ifndef SQLITE_OMIT_AUTHORIZATION
70072      if( pDef ){
70073        auth = sqlite3AuthCheck(pParse, SQLITE_FUNCTION, 0, pDef->zName, 0);
70074        if( auth!=SQLITE_OK ){
70075          if( auth==SQLITE_DENY ){
70076            sqlite3ErrorMsg(pParse, "not authorized to use function: %s",
70077                                    pDef->zName);
70078            pNC->nErr++;
70079          }
70080          pExpr->op = TK_NULL;
70081          return WRC_Prune;
70082        }
70083      }
70084#endif
70085      if( is_agg && !pNC->allowAgg ){
70086        sqlite3ErrorMsg(pParse, "misuse of aggregate function %.*s()", nId,zId);
70087        pNC->nErr++;
70088        is_agg = 0;
70089      }else if( no_such_func ){
70090        sqlite3ErrorMsg(pParse, "no such function: %.*s", nId, zId);
70091        pNC->nErr++;
70092      }else if( wrong_num_args ){
70093        sqlite3ErrorMsg(pParse,"wrong number of arguments to function %.*s()",
70094             nId, zId);
70095        pNC->nErr++;
70096      }
70097      if( is_agg ){
70098        pExpr->op = TK_AGG_FUNCTION;
70099        pNC->hasAgg = 1;
70100      }
70101      if( is_agg ) pNC->allowAgg = 0;
70102      sqlite3WalkExprList(pWalker, pList);
70103      if( is_agg ) pNC->allowAgg = 1;
70104      /* FIX ME:  Compute pExpr->affinity based on the expected return
70105      ** type of the function
70106      */
70107      return WRC_Prune;
70108    }
70109#ifndef SQLITE_OMIT_SUBQUERY
70110    case TK_SELECT:
70111    case TK_EXISTS:  testcase( pExpr->op==TK_EXISTS );
70112#endif
70113    case TK_IN: {
70114      testcase( pExpr->op==TK_IN );
70115      if( ExprHasProperty(pExpr, EP_xIsSelect) ){
70116        int nRef = pNC->nRef;
70117#ifndef SQLITE_OMIT_CHECK
70118        if( pNC->isCheck ){
70119          sqlite3ErrorMsg(pParse,"subqueries prohibited in CHECK constraints");
70120        }
70121#endif
70122        sqlite3WalkSelect(pWalker, pExpr->x.pSelect);
70123        assert( pNC->nRef>=nRef );
70124        if( nRef!=pNC->nRef ){
70125          ExprSetProperty(pExpr, EP_VarSelect);
70126        }
70127      }
70128      break;
70129    }
70130#ifndef SQLITE_OMIT_CHECK
70131    case TK_VARIABLE: {
70132      if( pNC->isCheck ){
70133        sqlite3ErrorMsg(pParse,"parameters prohibited in CHECK constraints");
70134      }
70135      break;
70136    }
70137#endif
70138  }
70139  return (pParse->nErr || pParse->db->mallocFailed) ? WRC_Abort : WRC_Continue;
70140}
70141
70142/*
70143** pEList is a list of expressions which are really the result set of the
70144** a SELECT statement.  pE is a term in an ORDER BY or GROUP BY clause.
70145** This routine checks to see if pE is a simple identifier which corresponds
70146** to the AS-name of one of the terms of the expression list.  If it is,
70147** this routine return an integer between 1 and N where N is the number of
70148** elements in pEList, corresponding to the matching entry.  If there is
70149** no match, or if pE is not a simple identifier, then this routine
70150** return 0.
70151**
70152** pEList has been resolved.  pE has not.
70153*/
70154static int resolveAsName(
70155  Parse *pParse,     /* Parsing context for error messages */
70156  ExprList *pEList,  /* List of expressions to scan */
70157  Expr *pE           /* Expression we are trying to match */
70158){
70159  int i;             /* Loop counter */
70160
70161  UNUSED_PARAMETER(pParse);
70162
70163  if( pE->op==TK_ID ){
70164    char *zCol = pE->u.zToken;
70165    for(i=0; i<pEList->nExpr; i++){
70166      char *zAs = pEList->a[i].zName;
70167      if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
70168        return i+1;
70169      }
70170    }
70171  }
70172  return 0;
70173}
70174
70175/*
70176** pE is a pointer to an expression which is a single term in the
70177** ORDER BY of a compound SELECT.  The expression has not been
70178** name resolved.
70179**
70180** At the point this routine is called, we already know that the
70181** ORDER BY term is not an integer index into the result set.  That
70182** case is handled by the calling routine.
70183**
70184** Attempt to match pE against result set columns in the left-most
70185** SELECT statement.  Return the index i of the matching column,
70186** as an indication to the caller that it should sort by the i-th column.
70187** The left-most column is 1.  In other words, the value returned is the
70188** same integer value that would be used in the SQL statement to indicate
70189** the column.
70190**
70191** If there is no match, return 0.  Return -1 if an error occurs.
70192*/
70193static int resolveOrderByTermToExprList(
70194  Parse *pParse,     /* Parsing context for error messages */
70195  Select *pSelect,   /* The SELECT statement with the ORDER BY clause */
70196  Expr *pE           /* The specific ORDER BY term */
70197){
70198  int i;             /* Loop counter */
70199  ExprList *pEList;  /* The columns of the result set */
70200  NameContext nc;    /* Name context for resolving pE */
70201  sqlite3 *db;       /* Database connection */
70202  int rc;            /* Return code from subprocedures */
70203  u8 savedSuppErr;   /* Saved value of db->suppressErr */
70204
70205  assert( sqlite3ExprIsInteger(pE, &i)==0 );
70206  pEList = pSelect->pEList;
70207
70208  /* Resolve all names in the ORDER BY term expression
70209  */
70210  memset(&nc, 0, sizeof(nc));
70211  nc.pParse = pParse;
70212  nc.pSrcList = pSelect->pSrc;
70213  nc.pEList = pEList;
70214  nc.allowAgg = 1;
70215  nc.nErr = 0;
70216  db = pParse->db;
70217  savedSuppErr = db->suppressErr;
70218  db->suppressErr = 1;
70219  rc = sqlite3ResolveExprNames(&nc, pE);
70220  db->suppressErr = savedSuppErr;
70221  if( rc ) return 0;
70222
70223  /* Try to match the ORDER BY expression against an expression
70224  ** in the result set.  Return an 1-based index of the matching
70225  ** result-set entry.
70226  */
70227  for(i=0; i<pEList->nExpr; i++){
70228    if( sqlite3ExprCompare(pEList->a[i].pExpr, pE)<2 ){
70229      return i+1;
70230    }
70231  }
70232
70233  /* If no match, return 0. */
70234  return 0;
70235}
70236
70237/*
70238** Generate an ORDER BY or GROUP BY term out-of-range error.
70239*/
70240static void resolveOutOfRangeError(
70241  Parse *pParse,         /* The error context into which to write the error */
70242  const char *zType,     /* "ORDER" or "GROUP" */
70243  int i,                 /* The index (1-based) of the term out of range */
70244  int mx                 /* Largest permissible value of i */
70245){
70246  sqlite3ErrorMsg(pParse,
70247    "%r %s BY term out of range - should be "
70248    "between 1 and %d", i, zType, mx);
70249}
70250
70251/*
70252** Analyze the ORDER BY clause in a compound SELECT statement.   Modify
70253** each term of the ORDER BY clause is a constant integer between 1
70254** and N where N is the number of columns in the compound SELECT.
70255**
70256** ORDER BY terms that are already an integer between 1 and N are
70257** unmodified.  ORDER BY terms that are integers outside the range of
70258** 1 through N generate an error.  ORDER BY terms that are expressions
70259** are matched against result set expressions of compound SELECT
70260** beginning with the left-most SELECT and working toward the right.
70261** At the first match, the ORDER BY expression is transformed into
70262** the integer column number.
70263**
70264** Return the number of errors seen.
70265*/
70266static int resolveCompoundOrderBy(
70267  Parse *pParse,        /* Parsing context.  Leave error messages here */
70268  Select *pSelect       /* The SELECT statement containing the ORDER BY */
70269){
70270  int i;
70271  ExprList *pOrderBy;
70272  ExprList *pEList;
70273  sqlite3 *db;
70274  int moreToDo = 1;
70275
70276  pOrderBy = pSelect->pOrderBy;
70277  if( pOrderBy==0 ) return 0;
70278  db = pParse->db;
70279#if SQLITE_MAX_COLUMN
70280  if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
70281    sqlite3ErrorMsg(pParse, "too many terms in ORDER BY clause");
70282    return 1;
70283  }
70284#endif
70285  for(i=0; i<pOrderBy->nExpr; i++){
70286    pOrderBy->a[i].done = 0;
70287  }
70288  pSelect->pNext = 0;
70289  while( pSelect->pPrior ){
70290    pSelect->pPrior->pNext = pSelect;
70291    pSelect = pSelect->pPrior;
70292  }
70293  while( pSelect && moreToDo ){
70294    struct ExprList_item *pItem;
70295    moreToDo = 0;
70296    pEList = pSelect->pEList;
70297    assert( pEList!=0 );
70298    for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
70299      int iCol = -1;
70300      Expr *pE, *pDup;
70301      if( pItem->done ) continue;
70302      pE = pItem->pExpr;
70303      if( sqlite3ExprIsInteger(pE, &iCol) ){
70304        if( iCol<=0 || iCol>pEList->nExpr ){
70305          resolveOutOfRangeError(pParse, "ORDER", i+1, pEList->nExpr);
70306          return 1;
70307        }
70308      }else{
70309        iCol = resolveAsName(pParse, pEList, pE);
70310        if( iCol==0 ){
70311          pDup = sqlite3ExprDup(db, pE, 0);
70312          if( !db->mallocFailed ){
70313            assert(pDup);
70314            iCol = resolveOrderByTermToExprList(pParse, pSelect, pDup);
70315          }
70316          sqlite3ExprDelete(db, pDup);
70317        }
70318      }
70319      if( iCol>0 ){
70320        CollSeq *pColl = pE->pColl;
70321        int flags = pE->flags & EP_ExpCollate;
70322        sqlite3ExprDelete(db, pE);
70323        pItem->pExpr = pE = sqlite3Expr(db, TK_INTEGER, 0);
70324        if( pE==0 ) return 1;
70325        pE->pColl = pColl;
70326        pE->flags |= EP_IntValue | flags;
70327        pE->u.iValue = iCol;
70328        pItem->iCol = (u16)iCol;
70329        pItem->done = 1;
70330      }else{
70331        moreToDo = 1;
70332      }
70333    }
70334    pSelect = pSelect->pNext;
70335  }
70336  for(i=0; i<pOrderBy->nExpr; i++){
70337    if( pOrderBy->a[i].done==0 ){
70338      sqlite3ErrorMsg(pParse, "%r ORDER BY term does not match any "
70339            "column in the result set", i+1);
70340      return 1;
70341    }
70342  }
70343  return 0;
70344}
70345
70346/*
70347** Check every term in the ORDER BY or GROUP BY clause pOrderBy of
70348** the SELECT statement pSelect.  If any term is reference to a
70349** result set expression (as determined by the ExprList.a.iCol field)
70350** then convert that term into a copy of the corresponding result set
70351** column.
70352**
70353** If any errors are detected, add an error message to pParse and
70354** return non-zero.  Return zero if no errors are seen.
70355*/
70356SQLITE_PRIVATE int sqlite3ResolveOrderGroupBy(
70357  Parse *pParse,        /* Parsing context.  Leave error messages here */
70358  Select *pSelect,      /* The SELECT statement containing the clause */
70359  ExprList *pOrderBy,   /* The ORDER BY or GROUP BY clause to be processed */
70360  const char *zType     /* "ORDER" or "GROUP" */
70361){
70362  int i;
70363  sqlite3 *db = pParse->db;
70364  ExprList *pEList;
70365  struct ExprList_item *pItem;
70366
70367  if( pOrderBy==0 || pParse->db->mallocFailed ) return 0;
70368#if SQLITE_MAX_COLUMN
70369  if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
70370    sqlite3ErrorMsg(pParse, "too many terms in %s BY clause", zType);
70371    return 1;
70372  }
70373#endif
70374  pEList = pSelect->pEList;
70375  assert( pEList!=0 );  /* sqlite3SelectNew() guarantees this */
70376  for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
70377    if( pItem->iCol ){
70378      if( pItem->iCol>pEList->nExpr ){
70379        resolveOutOfRangeError(pParse, zType, i+1, pEList->nExpr);
70380        return 1;
70381      }
70382      resolveAlias(pParse, pEList, pItem->iCol-1, pItem->pExpr, zType);
70383    }
70384  }
70385  return 0;
70386}
70387
70388/*
70389** pOrderBy is an ORDER BY or GROUP BY clause in SELECT statement pSelect.
70390** The Name context of the SELECT statement is pNC.  zType is either
70391** "ORDER" or "GROUP" depending on which type of clause pOrderBy is.
70392**
70393** This routine resolves each term of the clause into an expression.
70394** If the order-by term is an integer I between 1 and N (where N is the
70395** number of columns in the result set of the SELECT) then the expression
70396** in the resolution is a copy of the I-th result-set expression.  If
70397** the order-by term is an identify that corresponds to the AS-name of
70398** a result-set expression, then the term resolves to a copy of the
70399** result-set expression.  Otherwise, the expression is resolved in
70400** the usual way - using sqlite3ResolveExprNames().
70401**
70402** This routine returns the number of errors.  If errors occur, then
70403** an appropriate error message might be left in pParse.  (OOM errors
70404** excepted.)
70405*/
70406static int resolveOrderGroupBy(
70407  NameContext *pNC,     /* The name context of the SELECT statement */
70408  Select *pSelect,      /* The SELECT statement holding pOrderBy */
70409  ExprList *pOrderBy,   /* An ORDER BY or GROUP BY clause to resolve */
70410  const char *zType     /* Either "ORDER" or "GROUP", as appropriate */
70411){
70412  int i;                         /* Loop counter */
70413  int iCol;                      /* Column number */
70414  struct ExprList_item *pItem;   /* A term of the ORDER BY clause */
70415  Parse *pParse;                 /* Parsing context */
70416  int nResult;                   /* Number of terms in the result set */
70417
70418  if( pOrderBy==0 ) return 0;
70419  nResult = pSelect->pEList->nExpr;
70420  pParse = pNC->pParse;
70421  for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
70422    Expr *pE = pItem->pExpr;
70423    iCol = resolveAsName(pParse, pSelect->pEList, pE);
70424    if( iCol>0 ){
70425      /* If an AS-name match is found, mark this ORDER BY column as being
70426      ** a copy of the iCol-th result-set column.  The subsequent call to
70427      ** sqlite3ResolveOrderGroupBy() will convert the expression to a
70428      ** copy of the iCol-th result-set expression. */
70429      pItem->iCol = (u16)iCol;
70430      continue;
70431    }
70432    if( sqlite3ExprIsInteger(pE, &iCol) ){
70433      /* The ORDER BY term is an integer constant.  Again, set the column
70434      ** number so that sqlite3ResolveOrderGroupBy() will convert the
70435      ** order-by term to a copy of the result-set expression */
70436      if( iCol<1 ){
70437        resolveOutOfRangeError(pParse, zType, i+1, nResult);
70438        return 1;
70439      }
70440      pItem->iCol = (u16)iCol;
70441      continue;
70442    }
70443
70444    /* Otherwise, treat the ORDER BY term as an ordinary expression */
70445    pItem->iCol = 0;
70446    if( sqlite3ResolveExprNames(pNC, pE) ){
70447      return 1;
70448    }
70449  }
70450  return sqlite3ResolveOrderGroupBy(pParse, pSelect, pOrderBy, zType);
70451}
70452
70453/*
70454** Resolve names in the SELECT statement p and all of its descendents.
70455*/
70456static int resolveSelectStep(Walker *pWalker, Select *p){
70457  NameContext *pOuterNC;  /* Context that contains this SELECT */
70458  NameContext sNC;        /* Name context of this SELECT */
70459  int isCompound;         /* True if p is a compound select */
70460  int nCompound;          /* Number of compound terms processed so far */
70461  Parse *pParse;          /* Parsing context */
70462  ExprList *pEList;       /* Result set expression list */
70463  int i;                  /* Loop counter */
70464  ExprList *pGroupBy;     /* The GROUP BY clause */
70465  Select *pLeftmost;      /* Left-most of SELECT of a compound */
70466  sqlite3 *db;            /* Database connection */
70467
70468
70469  assert( p!=0 );
70470  if( p->selFlags & SF_Resolved ){
70471    return WRC_Prune;
70472  }
70473  pOuterNC = pWalker->u.pNC;
70474  pParse = pWalker->pParse;
70475  db = pParse->db;
70476
70477  /* Normally sqlite3SelectExpand() will be called first and will have
70478  ** already expanded this SELECT.  However, if this is a subquery within
70479  ** an expression, sqlite3ResolveExprNames() will be called without a
70480  ** prior call to sqlite3SelectExpand().  When that happens, let
70481  ** sqlite3SelectPrep() do all of the processing for this SELECT.
70482  ** sqlite3SelectPrep() will invoke both sqlite3SelectExpand() and
70483  ** this routine in the correct order.
70484  */
70485  if( (p->selFlags & SF_Expanded)==0 ){
70486    sqlite3SelectPrep(pParse, p, pOuterNC);
70487    return (pParse->nErr || db->mallocFailed) ? WRC_Abort : WRC_Prune;
70488  }
70489
70490  isCompound = p->pPrior!=0;
70491  nCompound = 0;
70492  pLeftmost = p;
70493  while( p ){
70494    assert( (p->selFlags & SF_Expanded)!=0 );
70495    assert( (p->selFlags & SF_Resolved)==0 );
70496    p->selFlags |= SF_Resolved;
70497
70498    /* Resolve the expressions in the LIMIT and OFFSET clauses. These
70499    ** are not allowed to refer to any names, so pass an empty NameContext.
70500    */
70501    memset(&sNC, 0, sizeof(sNC));
70502    sNC.pParse = pParse;
70503    if( sqlite3ResolveExprNames(&sNC, p->pLimit) ||
70504        sqlite3ResolveExprNames(&sNC, p->pOffset) ){
70505      return WRC_Abort;
70506    }
70507
70508    /* Set up the local name-context to pass to sqlite3ResolveExprNames() to
70509    ** resolve the result-set expression list.
70510    */
70511    sNC.allowAgg = 1;
70512    sNC.pSrcList = p->pSrc;
70513    sNC.pNext = pOuterNC;
70514
70515    /* Resolve names in the result set. */
70516    pEList = p->pEList;
70517    assert( pEList!=0 );
70518    for(i=0; i<pEList->nExpr; i++){
70519      Expr *pX = pEList->a[i].pExpr;
70520      if( sqlite3ResolveExprNames(&sNC, pX) ){
70521        return WRC_Abort;
70522      }
70523    }
70524
70525    /* Recursively resolve names in all subqueries
70526    */
70527    for(i=0; i<p->pSrc->nSrc; i++){
70528      struct SrcList_item *pItem = &p->pSrc->a[i];
70529      if( pItem->pSelect ){
70530        const char *zSavedContext = pParse->zAuthContext;
70531        if( pItem->zName ) pParse->zAuthContext = pItem->zName;
70532        sqlite3ResolveSelectNames(pParse, pItem->pSelect, pOuterNC);
70533        pParse->zAuthContext = zSavedContext;
70534        if( pParse->nErr || db->mallocFailed ) return WRC_Abort;
70535      }
70536    }
70537
70538    /* If there are no aggregate functions in the result-set, and no GROUP BY
70539    ** expression, do not allow aggregates in any of the other expressions.
70540    */
70541    assert( (p->selFlags & SF_Aggregate)==0 );
70542    pGroupBy = p->pGroupBy;
70543    if( pGroupBy || sNC.hasAgg ){
70544      p->selFlags |= SF_Aggregate;
70545    }else{
70546      sNC.allowAgg = 0;
70547    }
70548
70549    /* If a HAVING clause is present, then there must be a GROUP BY clause.
70550    */
70551    if( p->pHaving && !pGroupBy ){
70552      sqlite3ErrorMsg(pParse, "a GROUP BY clause is required before HAVING");
70553      return WRC_Abort;
70554    }
70555
70556    /* Add the expression list to the name-context before parsing the
70557    ** other expressions in the SELECT statement. This is so that
70558    ** expressions in the WHERE clause (etc.) can refer to expressions by
70559    ** aliases in the result set.
70560    **
70561    ** Minor point: If this is the case, then the expression will be
70562    ** re-evaluated for each reference to it.
70563    */
70564    sNC.pEList = p->pEList;
70565    if( sqlite3ResolveExprNames(&sNC, p->pWhere) ||
70566       sqlite3ResolveExprNames(&sNC, p->pHaving)
70567    ){
70568      return WRC_Abort;
70569    }
70570
70571    /* The ORDER BY and GROUP BY clauses may not refer to terms in
70572    ** outer queries
70573    */
70574    sNC.pNext = 0;
70575    sNC.allowAgg = 1;
70576
70577    /* Process the ORDER BY clause for singleton SELECT statements.
70578    ** The ORDER BY clause for compounds SELECT statements is handled
70579    ** below, after all of the result-sets for all of the elements of
70580    ** the compound have been resolved.
70581    */
70582    if( !isCompound && resolveOrderGroupBy(&sNC, p, p->pOrderBy, "ORDER") ){
70583      return WRC_Abort;
70584    }
70585    if( db->mallocFailed ){
70586      return WRC_Abort;
70587    }
70588
70589    /* Resolve the GROUP BY clause.  At the same time, make sure
70590    ** the GROUP BY clause does not contain aggregate functions.
70591    */
70592    if( pGroupBy ){
70593      struct ExprList_item *pItem;
70594
70595      if( resolveOrderGroupBy(&sNC, p, pGroupBy, "GROUP") || db->mallocFailed ){
70596        return WRC_Abort;
70597      }
70598      for(i=0, pItem=pGroupBy->a; i<pGroupBy->nExpr; i++, pItem++){
70599        if( ExprHasProperty(pItem->pExpr, EP_Agg) ){
70600          sqlite3ErrorMsg(pParse, "aggregate functions are not allowed in "
70601              "the GROUP BY clause");
70602          return WRC_Abort;
70603        }
70604      }
70605    }
70606
70607    /* Advance to the next term of the compound
70608    */
70609    p = p->pPrior;
70610    nCompound++;
70611  }
70612
70613  /* Resolve the ORDER BY on a compound SELECT after all terms of
70614  ** the compound have been resolved.
70615  */
70616  if( isCompound && resolveCompoundOrderBy(pParse, pLeftmost) ){
70617    return WRC_Abort;
70618  }
70619
70620  return WRC_Prune;
70621}
70622
70623/*
70624** This routine walks an expression tree and resolves references to
70625** table columns and result-set columns.  At the same time, do error
70626** checking on function usage and set a flag if any aggregate functions
70627** are seen.
70628**
70629** To resolve table columns references we look for nodes (or subtrees) of the
70630** form X.Y.Z or Y.Z or just Z where
70631**
70632**      X:   The name of a database.  Ex:  "main" or "temp" or
70633**           the symbolic name assigned to an ATTACH-ed database.
70634**
70635**      Y:   The name of a table in a FROM clause.  Or in a trigger
70636**           one of the special names "old" or "new".
70637**
70638**      Z:   The name of a column in table Y.
70639**
70640** The node at the root of the subtree is modified as follows:
70641**
70642**    Expr.op        Changed to TK_COLUMN
70643**    Expr.pTab      Points to the Table object for X.Y
70644**    Expr.iColumn   The column index in X.Y.  -1 for the rowid.
70645**    Expr.iTable    The VDBE cursor number for X.Y
70646**
70647**
70648** To resolve result-set references, look for expression nodes of the
70649** form Z (with no X and Y prefix) where the Z matches the right-hand
70650** size of an AS clause in the result-set of a SELECT.  The Z expression
70651** is replaced by a copy of the left-hand side of the result-set expression.
70652** Table-name and function resolution occurs on the substituted expression
70653** tree.  For example, in:
70654**
70655**      SELECT a+b AS x, c+d AS y FROM t1 ORDER BY x;
70656**
70657** The "x" term of the order by is replaced by "a+b" to render:
70658**
70659**      SELECT a+b AS x, c+d AS y FROM t1 ORDER BY a+b;
70660**
70661** Function calls are checked to make sure that the function is
70662** defined and that the correct number of arguments are specified.
70663** If the function is an aggregate function, then the pNC->hasAgg is
70664** set and the opcode is changed from TK_FUNCTION to TK_AGG_FUNCTION.
70665** If an expression contains aggregate functions then the EP_Agg
70666** property on the expression is set.
70667**
70668** An error message is left in pParse if anything is amiss.  The number
70669** if errors is returned.
70670*/
70671SQLITE_PRIVATE int sqlite3ResolveExprNames(
70672  NameContext *pNC,       /* Namespace to resolve expressions in. */
70673  Expr *pExpr             /* The expression to be analyzed. */
70674){
70675  int savedHasAgg;
70676  Walker w;
70677
70678  if( pExpr==0 ) return 0;
70679#if SQLITE_MAX_EXPR_DEPTH>0
70680  {
70681    Parse *pParse = pNC->pParse;
70682    if( sqlite3ExprCheckHeight(pParse, pExpr->nHeight+pNC->pParse->nHeight) ){
70683      return 1;
70684    }
70685    pParse->nHeight += pExpr->nHeight;
70686  }
70687#endif
70688  savedHasAgg = pNC->hasAgg;
70689  pNC->hasAgg = 0;
70690  w.xExprCallback = resolveExprStep;
70691  w.xSelectCallback = resolveSelectStep;
70692  w.pParse = pNC->pParse;
70693  w.u.pNC = pNC;
70694  sqlite3WalkExpr(&w, pExpr);
70695#if SQLITE_MAX_EXPR_DEPTH>0
70696  pNC->pParse->nHeight -= pExpr->nHeight;
70697#endif
70698  if( pNC->nErr>0 || w.pParse->nErr>0 ){
70699    ExprSetProperty(pExpr, EP_Error);
70700  }
70701  if( pNC->hasAgg ){
70702    ExprSetProperty(pExpr, EP_Agg);
70703  }else if( savedHasAgg ){
70704    pNC->hasAgg = 1;
70705  }
70706  return ExprHasProperty(pExpr, EP_Error);
70707}
70708
70709
70710/*
70711** Resolve all names in all expressions of a SELECT and in all
70712** decendents of the SELECT, including compounds off of p->pPrior,
70713** subqueries in expressions, and subqueries used as FROM clause
70714** terms.
70715**
70716** See sqlite3ResolveExprNames() for a description of the kinds of
70717** transformations that occur.
70718**
70719** All SELECT statements should have been expanded using
70720** sqlite3SelectExpand() prior to invoking this routine.
70721*/
70722SQLITE_PRIVATE void sqlite3ResolveSelectNames(
70723  Parse *pParse,         /* The parser context */
70724  Select *p,             /* The SELECT statement being coded. */
70725  NameContext *pOuterNC  /* Name context for parent SELECT statement */
70726){
70727  Walker w;
70728
70729  assert( p!=0 );
70730  w.xExprCallback = resolveExprStep;
70731  w.xSelectCallback = resolveSelectStep;
70732  w.pParse = pParse;
70733  w.u.pNC = pOuterNC;
70734  sqlite3WalkSelect(&w, p);
70735}
70736
70737/************** End of resolve.c *********************************************/
70738/************** Begin file expr.c ********************************************/
70739/*
70740** 2001 September 15
70741**
70742** The author disclaims copyright to this source code.  In place of
70743** a legal notice, here is a blessing:
70744**
70745**    May you do good and not evil.
70746**    May you find forgiveness for yourself and forgive others.
70747**    May you share freely, never taking more than you give.
70748**
70749*************************************************************************
70750** This file contains routines used for analyzing expressions and
70751** for generating VDBE code that evaluates expressions in SQLite.
70752*/
70753
70754/*
70755** Return the 'affinity' of the expression pExpr if any.
70756**
70757** If pExpr is a column, a reference to a column via an 'AS' alias,
70758** or a sub-select with a column as the return value, then the
70759** affinity of that column is returned. Otherwise, 0x00 is returned,
70760** indicating no affinity for the expression.
70761**
70762** i.e. the WHERE clause expresssions in the following statements all
70763** have an affinity:
70764**
70765** CREATE TABLE t1(a);
70766** SELECT * FROM t1 WHERE a;
70767** SELECT a AS b FROM t1 WHERE b;
70768** SELECT * FROM t1 WHERE (select a from t1);
70769*/
70770SQLITE_PRIVATE char sqlite3ExprAffinity(Expr *pExpr){
70771  int op = pExpr->op;
70772  if( op==TK_SELECT ){
70773    assert( pExpr->flags&EP_xIsSelect );
70774    return sqlite3ExprAffinity(pExpr->x.pSelect->pEList->a[0].pExpr);
70775  }
70776#ifndef SQLITE_OMIT_CAST
70777  if( op==TK_CAST ){
70778    assert( !ExprHasProperty(pExpr, EP_IntValue) );
70779    return sqlite3AffinityType(pExpr->u.zToken);
70780  }
70781#endif
70782  if( (op==TK_AGG_COLUMN || op==TK_COLUMN || op==TK_REGISTER)
70783   && pExpr->pTab!=0
70784  ){
70785    /* op==TK_REGISTER && pExpr->pTab!=0 happens when pExpr was originally
70786    ** a TK_COLUMN but was previously evaluated and cached in a register */
70787    int j = pExpr->iColumn;
70788    if( j<0 ) return SQLITE_AFF_INTEGER;
70789    assert( pExpr->pTab && j<pExpr->pTab->nCol );
70790    return pExpr->pTab->aCol[j].affinity;
70791  }
70792  return pExpr->affinity;
70793}
70794
70795/*
70796** Set the explicit collating sequence for an expression to the
70797** collating sequence supplied in the second argument.
70798*/
70799SQLITE_PRIVATE Expr *sqlite3ExprSetColl(Expr *pExpr, CollSeq *pColl){
70800  if( pExpr && pColl ){
70801    pExpr->pColl = pColl;
70802    pExpr->flags |= EP_ExpCollate;
70803  }
70804  return pExpr;
70805}
70806
70807/*
70808** Set the collating sequence for expression pExpr to be the collating
70809** sequence named by pToken.   Return a pointer to the revised expression.
70810** The collating sequence is marked as "explicit" using the EP_ExpCollate
70811** flag.  An explicit collating sequence will override implicit
70812** collating sequences.
70813*/
70814SQLITE_PRIVATE Expr *sqlite3ExprSetCollByToken(Parse *pParse, Expr *pExpr, Token *pCollName){
70815  char *zColl = 0;            /* Dequoted name of collation sequence */
70816  CollSeq *pColl;
70817  sqlite3 *db = pParse->db;
70818  zColl = sqlite3NameFromToken(db, pCollName);
70819  pColl = sqlite3LocateCollSeq(pParse, zColl);
70820  sqlite3ExprSetColl(pExpr, pColl);
70821  sqlite3DbFree(db, zColl);
70822  return pExpr;
70823}
70824
70825/*
70826** Return the default collation sequence for the expression pExpr. If
70827** there is no default collation type, return 0.
70828*/
70829SQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr){
70830  CollSeq *pColl = 0;
70831  Expr *p = pExpr;
70832  while( p ){
70833    int op;
70834    pColl = p->pColl;
70835    if( pColl ) break;
70836    op = p->op;
70837    if( p->pTab!=0 && (
70838        op==TK_AGG_COLUMN || op==TK_COLUMN || op==TK_REGISTER || op==TK_TRIGGER
70839    )){
70840      /* op==TK_REGISTER && p->pTab!=0 happens when pExpr was originally
70841      ** a TK_COLUMN but was previously evaluated and cached in a register */
70842      const char *zColl;
70843      int j = p->iColumn;
70844      if( j>=0 ){
70845        sqlite3 *db = pParse->db;
70846        zColl = p->pTab->aCol[j].zColl;
70847        pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
70848        pExpr->pColl = pColl;
70849      }
70850      break;
70851    }
70852    if( op!=TK_CAST && op!=TK_UPLUS ){
70853      break;
70854    }
70855    p = p->pLeft;
70856  }
70857  if( sqlite3CheckCollSeq(pParse, pColl) ){
70858    pColl = 0;
70859  }
70860  return pColl;
70861}
70862
70863/*
70864** pExpr is an operand of a comparison operator.  aff2 is the
70865** type affinity of the other operand.  This routine returns the
70866** type affinity that should be used for the comparison operator.
70867*/
70868SQLITE_PRIVATE char sqlite3CompareAffinity(Expr *pExpr, char aff2){
70869  char aff1 = sqlite3ExprAffinity(pExpr);
70870  if( aff1 && aff2 ){
70871    /* Both sides of the comparison are columns. If one has numeric
70872    ** affinity, use that. Otherwise use no affinity.
70873    */
70874    if( sqlite3IsNumericAffinity(aff1) || sqlite3IsNumericAffinity(aff2) ){
70875      return SQLITE_AFF_NUMERIC;
70876    }else{
70877      return SQLITE_AFF_NONE;
70878    }
70879  }else if( !aff1 && !aff2 ){
70880    /* Neither side of the comparison is a column.  Compare the
70881    ** results directly.
70882    */
70883    return SQLITE_AFF_NONE;
70884  }else{
70885    /* One side is a column, the other is not. Use the columns affinity. */
70886    assert( aff1==0 || aff2==0 );
70887    return (aff1 + aff2);
70888  }
70889}
70890
70891/*
70892** pExpr is a comparison operator.  Return the type affinity that should
70893** be applied to both operands prior to doing the comparison.
70894*/
70895static char comparisonAffinity(Expr *pExpr){
70896  char aff;
70897  assert( pExpr->op==TK_EQ || pExpr->op==TK_IN || pExpr->op==TK_LT ||
70898          pExpr->op==TK_GT || pExpr->op==TK_GE || pExpr->op==TK_LE ||
70899          pExpr->op==TK_NE || pExpr->op==TK_IS || pExpr->op==TK_ISNOT );
70900  assert( pExpr->pLeft );
70901  aff = sqlite3ExprAffinity(pExpr->pLeft);
70902  if( pExpr->pRight ){
70903    aff = sqlite3CompareAffinity(pExpr->pRight, aff);
70904  }else if( ExprHasProperty(pExpr, EP_xIsSelect) ){
70905    aff = sqlite3CompareAffinity(pExpr->x.pSelect->pEList->a[0].pExpr, aff);
70906  }else if( !aff ){
70907    aff = SQLITE_AFF_NONE;
70908  }
70909  return aff;
70910}
70911
70912/*
70913** pExpr is a comparison expression, eg. '=', '<', IN(...) etc.
70914** idx_affinity is the affinity of an indexed column. Return true
70915** if the index with affinity idx_affinity may be used to implement
70916** the comparison in pExpr.
70917*/
70918SQLITE_PRIVATE int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity){
70919  char aff = comparisonAffinity(pExpr);
70920  switch( aff ){
70921    case SQLITE_AFF_NONE:
70922      return 1;
70923    case SQLITE_AFF_TEXT:
70924      return idx_affinity==SQLITE_AFF_TEXT;
70925    default:
70926      return sqlite3IsNumericAffinity(idx_affinity);
70927  }
70928}
70929
70930/*
70931** Return the P5 value that should be used for a binary comparison
70932** opcode (OP_Eq, OP_Ge etc.) used to compare pExpr1 and pExpr2.
70933*/
70934static u8 binaryCompareP5(Expr *pExpr1, Expr *pExpr2, int jumpIfNull){
70935  u8 aff = (char)sqlite3ExprAffinity(pExpr2);
70936  aff = (u8)sqlite3CompareAffinity(pExpr1, aff) | (u8)jumpIfNull;
70937  return aff;
70938}
70939
70940/*
70941** Return a pointer to the collation sequence that should be used by
70942** a binary comparison operator comparing pLeft and pRight.
70943**
70944** If the left hand expression has a collating sequence type, then it is
70945** used. Otherwise the collation sequence for the right hand expression
70946** is used, or the default (BINARY) if neither expression has a collating
70947** type.
70948**
70949** Argument pRight (but not pLeft) may be a null pointer. In this case,
70950** it is not considered.
70951*/
70952SQLITE_PRIVATE CollSeq *sqlite3BinaryCompareCollSeq(
70953  Parse *pParse,
70954  Expr *pLeft,
70955  Expr *pRight
70956){
70957  CollSeq *pColl;
70958  assert( pLeft );
70959  if( pLeft->flags & EP_ExpCollate ){
70960    assert( pLeft->pColl );
70961    pColl = pLeft->pColl;
70962  }else if( pRight && pRight->flags & EP_ExpCollate ){
70963    assert( pRight->pColl );
70964    pColl = pRight->pColl;
70965  }else{
70966    pColl = sqlite3ExprCollSeq(pParse, pLeft);
70967    if( !pColl ){
70968      pColl = sqlite3ExprCollSeq(pParse, pRight);
70969    }
70970  }
70971  return pColl;
70972}
70973
70974/*
70975** Generate code for a comparison operator.
70976*/
70977static int codeCompare(
70978  Parse *pParse,    /* The parsing (and code generating) context */
70979  Expr *pLeft,      /* The left operand */
70980  Expr *pRight,     /* The right operand */
70981  int opcode,       /* The comparison opcode */
70982  int in1, int in2, /* Register holding operands */
70983  int dest,         /* Jump here if true.  */
70984  int jumpIfNull    /* If true, jump if either operand is NULL */
70985){
70986  int p5;
70987  int addr;
70988  CollSeq *p4;
70989
70990  p4 = sqlite3BinaryCompareCollSeq(pParse, pLeft, pRight);
70991  p5 = binaryCompareP5(pLeft, pRight, jumpIfNull);
70992  addr = sqlite3VdbeAddOp4(pParse->pVdbe, opcode, in2, dest, in1,
70993                           (void*)p4, P4_COLLSEQ);
70994  sqlite3VdbeChangeP5(pParse->pVdbe, (u8)p5);
70995  return addr;
70996}
70997
70998#if SQLITE_MAX_EXPR_DEPTH>0
70999/*
71000** Check that argument nHeight is less than or equal to the maximum
71001** expression depth allowed. If it is not, leave an error message in
71002** pParse.
71003*/
71004SQLITE_PRIVATE int sqlite3ExprCheckHeight(Parse *pParse, int nHeight){
71005  int rc = SQLITE_OK;
71006  int mxHeight = pParse->db->aLimit[SQLITE_LIMIT_EXPR_DEPTH];
71007  if( nHeight>mxHeight ){
71008    sqlite3ErrorMsg(pParse,
71009       "Expression tree is too large (maximum depth %d)", mxHeight
71010    );
71011    rc = SQLITE_ERROR;
71012  }
71013  return rc;
71014}
71015
71016/* The following three functions, heightOfExpr(), heightOfExprList()
71017** and heightOfSelect(), are used to determine the maximum height
71018** of any expression tree referenced by the structure passed as the
71019** first argument.
71020**
71021** If this maximum height is greater than the current value pointed
71022** to by pnHeight, the second parameter, then set *pnHeight to that
71023** value.
71024*/
71025static void heightOfExpr(Expr *p, int *pnHeight){
71026  if( p ){
71027    if( p->nHeight>*pnHeight ){
71028      *pnHeight = p->nHeight;
71029    }
71030  }
71031}
71032static void heightOfExprList(ExprList *p, int *pnHeight){
71033  if( p ){
71034    int i;
71035    for(i=0; i<p->nExpr; i++){
71036      heightOfExpr(p->a[i].pExpr, pnHeight);
71037    }
71038  }
71039}
71040static void heightOfSelect(Select *p, int *pnHeight){
71041  if( p ){
71042    heightOfExpr(p->pWhere, pnHeight);
71043    heightOfExpr(p->pHaving, pnHeight);
71044    heightOfExpr(p->pLimit, pnHeight);
71045    heightOfExpr(p->pOffset, pnHeight);
71046    heightOfExprList(p->pEList, pnHeight);
71047    heightOfExprList(p->pGroupBy, pnHeight);
71048    heightOfExprList(p->pOrderBy, pnHeight);
71049    heightOfSelect(p->pPrior, pnHeight);
71050  }
71051}
71052
71053/*
71054** Set the Expr.nHeight variable in the structure passed as an
71055** argument. An expression with no children, Expr.pList or
71056** Expr.pSelect member has a height of 1. Any other expression
71057** has a height equal to the maximum height of any other
71058** referenced Expr plus one.
71059*/
71060static void exprSetHeight(Expr *p){
71061  int nHeight = 0;
71062  heightOfExpr(p->pLeft, &nHeight);
71063  heightOfExpr(p->pRight, &nHeight);
71064  if( ExprHasProperty(p, EP_xIsSelect) ){
71065    heightOfSelect(p->x.pSelect, &nHeight);
71066  }else{
71067    heightOfExprList(p->x.pList, &nHeight);
71068  }
71069  p->nHeight = nHeight + 1;
71070}
71071
71072/*
71073** Set the Expr.nHeight variable using the exprSetHeight() function. If
71074** the height is greater than the maximum allowed expression depth,
71075** leave an error in pParse.
71076*/
71077SQLITE_PRIVATE void sqlite3ExprSetHeight(Parse *pParse, Expr *p){
71078  exprSetHeight(p);
71079  sqlite3ExprCheckHeight(pParse, p->nHeight);
71080}
71081
71082/*
71083** Return the maximum height of any expression tree referenced
71084** by the select statement passed as an argument.
71085*/
71086SQLITE_PRIVATE int sqlite3SelectExprHeight(Select *p){
71087  int nHeight = 0;
71088  heightOfSelect(p, &nHeight);
71089  return nHeight;
71090}
71091#else
71092  #define exprSetHeight(y)
71093#endif /* SQLITE_MAX_EXPR_DEPTH>0 */
71094
71095/*
71096** This routine is the core allocator for Expr nodes.
71097**
71098** Construct a new expression node and return a pointer to it.  Memory
71099** for this node and for the pToken argument is a single allocation
71100** obtained from sqlite3DbMalloc().  The calling function
71101** is responsible for making sure the node eventually gets freed.
71102**
71103** If dequote is true, then the token (if it exists) is dequoted.
71104** If dequote is false, no dequoting is performance.  The deQuote
71105** parameter is ignored if pToken is NULL or if the token does not
71106** appear to be quoted.  If the quotes were of the form "..." (double-quotes)
71107** then the EP_DblQuoted flag is set on the expression node.
71108**
71109** Special case:  If op==TK_INTEGER and pToken points to a string that
71110** can be translated into a 32-bit integer, then the token is not
71111** stored in u.zToken.  Instead, the integer values is written
71112** into u.iValue and the EP_IntValue flag is set.  No extra storage
71113** is allocated to hold the integer text and the dequote flag is ignored.
71114*/
71115SQLITE_PRIVATE Expr *sqlite3ExprAlloc(
71116  sqlite3 *db,            /* Handle for sqlite3DbMallocZero() (may be null) */
71117  int op,                 /* Expression opcode */
71118  const Token *pToken,    /* Token argument.  Might be NULL */
71119  int dequote             /* True to dequote */
71120){
71121  Expr *pNew;
71122  int nExtra = 0;
71123  int iValue = 0;
71124
71125  if( pToken ){
71126    if( op!=TK_INTEGER || pToken->z==0
71127          || sqlite3GetInt32(pToken->z, &iValue)==0 ){
71128      nExtra = pToken->n+1;
71129      assert( iValue>=0 );
71130    }
71131  }
71132  pNew = sqlite3DbMallocZero(db, sizeof(Expr)+nExtra);
71133  if( pNew ){
71134    pNew->op = (u8)op;
71135    pNew->iAgg = -1;
71136    if( pToken ){
71137      if( nExtra==0 ){
71138        pNew->flags |= EP_IntValue;
71139        pNew->u.iValue = iValue;
71140      }else{
71141        int c;
71142        pNew->u.zToken = (char*)&pNew[1];
71143        memcpy(pNew->u.zToken, pToken->z, pToken->n);
71144        pNew->u.zToken[pToken->n] = 0;
71145        if( dequote && nExtra>=3
71146             && ((c = pToken->z[0])=='\'' || c=='"' || c=='[' || c=='`') ){
71147          sqlite3Dequote(pNew->u.zToken);
71148          if( c=='"' ) pNew->flags |= EP_DblQuoted;
71149        }
71150      }
71151    }
71152#if SQLITE_MAX_EXPR_DEPTH>0
71153    pNew->nHeight = 1;
71154#endif
71155  }
71156  return pNew;
71157}
71158
71159/*
71160** Allocate a new expression node from a zero-terminated token that has
71161** already been dequoted.
71162*/
71163SQLITE_PRIVATE Expr *sqlite3Expr(
71164  sqlite3 *db,            /* Handle for sqlite3DbMallocZero() (may be null) */
71165  int op,                 /* Expression opcode */
71166  const char *zToken      /* Token argument.  Might be NULL */
71167){
71168  Token x;
71169  x.z = zToken;
71170  x.n = zToken ? sqlite3Strlen30(zToken) : 0;
71171  return sqlite3ExprAlloc(db, op, &x, 0);
71172}
71173
71174/*
71175** Attach subtrees pLeft and pRight to the Expr node pRoot.
71176**
71177** If pRoot==NULL that means that a memory allocation error has occurred.
71178** In that case, delete the subtrees pLeft and pRight.
71179*/
71180SQLITE_PRIVATE void sqlite3ExprAttachSubtrees(
71181  sqlite3 *db,
71182  Expr *pRoot,
71183  Expr *pLeft,
71184  Expr *pRight
71185){
71186  if( pRoot==0 ){
71187    assert( db->mallocFailed );
71188    sqlite3ExprDelete(db, pLeft);
71189    sqlite3ExprDelete(db, pRight);
71190  }else{
71191    if( pRight ){
71192      pRoot->pRight = pRight;
71193      if( pRight->flags & EP_ExpCollate ){
71194        pRoot->flags |= EP_ExpCollate;
71195        pRoot->pColl = pRight->pColl;
71196      }
71197    }
71198    if( pLeft ){
71199      pRoot->pLeft = pLeft;
71200      if( pLeft->flags & EP_ExpCollate ){
71201        pRoot->flags |= EP_ExpCollate;
71202        pRoot->pColl = pLeft->pColl;
71203      }
71204    }
71205    exprSetHeight(pRoot);
71206  }
71207}
71208
71209/*
71210** Allocate a Expr node which joins as many as two subtrees.
71211**
71212** One or both of the subtrees can be NULL.  Return a pointer to the new
71213** Expr node.  Or, if an OOM error occurs, set pParse->db->mallocFailed,
71214** free the subtrees and return NULL.
71215*/
71216SQLITE_PRIVATE Expr *sqlite3PExpr(
71217  Parse *pParse,          /* Parsing context */
71218  int op,                 /* Expression opcode */
71219  Expr *pLeft,            /* Left operand */
71220  Expr *pRight,           /* Right operand */
71221  const Token *pToken     /* Argument token */
71222){
71223  Expr *p = sqlite3ExprAlloc(pParse->db, op, pToken, 1);
71224  sqlite3ExprAttachSubtrees(pParse->db, p, pLeft, pRight);
71225  if( p ) {
71226    sqlite3ExprCheckHeight(pParse, p->nHeight);
71227  }
71228  return p;
71229}
71230
71231/*
71232** Join two expressions using an AND operator.  If either expression is
71233** NULL, then just return the other expression.
71234*/
71235SQLITE_PRIVATE Expr *sqlite3ExprAnd(sqlite3 *db, Expr *pLeft, Expr *pRight){
71236  if( pLeft==0 ){
71237    return pRight;
71238  }else if( pRight==0 ){
71239    return pLeft;
71240  }else{
71241    Expr *pNew = sqlite3ExprAlloc(db, TK_AND, 0, 0);
71242    sqlite3ExprAttachSubtrees(db, pNew, pLeft, pRight);
71243    return pNew;
71244  }
71245}
71246
71247/*
71248** Construct a new expression node for a function with multiple
71249** arguments.
71250*/
71251SQLITE_PRIVATE Expr *sqlite3ExprFunction(Parse *pParse, ExprList *pList, Token *pToken){
71252  Expr *pNew;
71253  sqlite3 *db = pParse->db;
71254  assert( pToken );
71255  pNew = sqlite3ExprAlloc(db, TK_FUNCTION, pToken, 1);
71256  if( pNew==0 ){
71257    sqlite3ExprListDelete(db, pList); /* Avoid memory leak when malloc fails */
71258    return 0;
71259  }
71260  pNew->x.pList = pList;
71261  assert( !ExprHasProperty(pNew, EP_xIsSelect) );
71262  sqlite3ExprSetHeight(pParse, pNew);
71263  return pNew;
71264}
71265
71266/*
71267** Assign a variable number to an expression that encodes a wildcard
71268** in the original SQL statement.
71269**
71270** Wildcards consisting of a single "?" are assigned the next sequential
71271** variable number.
71272**
71273** Wildcards of the form "?nnn" are assigned the number "nnn".  We make
71274** sure "nnn" is not too be to avoid a denial of service attack when
71275** the SQL statement comes from an external source.
71276**
71277** Wildcards of the form ":aaa", "@aaa", or "$aaa" are assigned the same number
71278** as the previous instance of the same wildcard.  Or if this is the first
71279** instance of the wildcard, the next sequenial variable number is
71280** assigned.
71281*/
71282SQLITE_PRIVATE void sqlite3ExprAssignVarNumber(Parse *pParse, Expr *pExpr){
71283  sqlite3 *db = pParse->db;
71284  const char *z;
71285
71286  if( pExpr==0 ) return;
71287  assert( !ExprHasAnyProperty(pExpr, EP_IntValue|EP_Reduced|EP_TokenOnly) );
71288  z = pExpr->u.zToken;
71289  assert( z!=0 );
71290  assert( z[0]!=0 );
71291  if( z[1]==0 ){
71292    /* Wildcard of the form "?".  Assign the next variable number */
71293    assert( z[0]=='?' );
71294    pExpr->iColumn = (ynVar)(++pParse->nVar);
71295  }else if( z[0]=='?' ){
71296    /* Wildcard of the form "?nnn".  Convert "nnn" to an integer and
71297    ** use it as the variable number */
71298    i64 i;
71299    int bOk = 0==sqlite3Atoi64(&z[1], &i, sqlite3Strlen30(&z[1]), SQLITE_UTF8);
71300    pExpr->iColumn = (ynVar)i;
71301    testcase( i==0 );
71302    testcase( i==1 );
71303    testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]-1 );
71304    testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] );
71305    if( bOk==0 || i<1 || i>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
71306      sqlite3ErrorMsg(pParse, "variable number must be between ?1 and ?%d",
71307          db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]);
71308    }
71309    if( i>pParse->nVar ){
71310      pParse->nVar = (int)i;
71311    }
71312  }else{
71313    /* Wildcards like ":aaa", "$aaa" or "@aaa".  Reuse the same variable
71314    ** number as the prior appearance of the same name, or if the name
71315    ** has never appeared before, reuse the same variable number
71316    */
71317    int i;
71318    for(i=0; i<pParse->nVarExpr; i++){
71319      Expr *pE = pParse->apVarExpr[i];
71320      assert( pE!=0 );
71321      if( strcmp(pE->u.zToken, z)==0 ){
71322        pExpr->iColumn = pE->iColumn;
71323        break;
71324      }
71325    }
71326    if( i>=pParse->nVarExpr ){
71327      pExpr->iColumn = (ynVar)(++pParse->nVar);
71328      if( pParse->nVarExpr>=pParse->nVarExprAlloc-1 ){
71329        pParse->nVarExprAlloc += pParse->nVarExprAlloc + 10;
71330        pParse->apVarExpr =
71331            sqlite3DbReallocOrFree(
71332              db,
71333              pParse->apVarExpr,
71334              pParse->nVarExprAlloc*sizeof(pParse->apVarExpr[0])
71335            );
71336      }
71337      if( !db->mallocFailed ){
71338        assert( pParse->apVarExpr!=0 );
71339        pParse->apVarExpr[pParse->nVarExpr++] = pExpr;
71340      }
71341    }
71342  }
71343  if( !pParse->nErr && pParse->nVar>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
71344    sqlite3ErrorMsg(pParse, "too many SQL variables");
71345  }
71346}
71347
71348/*
71349** Recursively delete an expression tree.
71350*/
71351SQLITE_PRIVATE void sqlite3ExprDelete(sqlite3 *db, Expr *p){
71352  if( p==0 ) return;
71353  /* Sanity check: Assert that the IntValue is non-negative if it exists */
71354  assert( !ExprHasProperty(p, EP_IntValue) || p->u.iValue>=0 );
71355  if( !ExprHasAnyProperty(p, EP_TokenOnly) ){
71356    sqlite3ExprDelete(db, p->pLeft);
71357    sqlite3ExprDelete(db, p->pRight);
71358    if( !ExprHasProperty(p, EP_Reduced) && (p->flags2 & EP2_MallocedToken)!=0 ){
71359      sqlite3DbFree(db, p->u.zToken);
71360    }
71361    if( ExprHasProperty(p, EP_xIsSelect) ){
71362      sqlite3SelectDelete(db, p->x.pSelect);
71363    }else{
71364      sqlite3ExprListDelete(db, p->x.pList);
71365    }
71366  }
71367  if( !ExprHasProperty(p, EP_Static) ){
71368    sqlite3DbFree(db, p);
71369  }
71370}
71371
71372/*
71373** Return the number of bytes allocated for the expression structure
71374** passed as the first argument. This is always one of EXPR_FULLSIZE,
71375** EXPR_REDUCEDSIZE or EXPR_TOKENONLYSIZE.
71376*/
71377static int exprStructSize(Expr *p){
71378  if( ExprHasProperty(p, EP_TokenOnly) ) return EXPR_TOKENONLYSIZE;
71379  if( ExprHasProperty(p, EP_Reduced) ) return EXPR_REDUCEDSIZE;
71380  return EXPR_FULLSIZE;
71381}
71382
71383/*
71384** The dupedExpr*Size() routines each return the number of bytes required
71385** to store a copy of an expression or expression tree.  They differ in
71386** how much of the tree is measured.
71387**
71388**     dupedExprStructSize()     Size of only the Expr structure
71389**     dupedExprNodeSize()       Size of Expr + space for token
71390**     dupedExprSize()           Expr + token + subtree components
71391**
71392***************************************************************************
71393**
71394** The dupedExprStructSize() function returns two values OR-ed together:
71395** (1) the space required for a copy of the Expr structure only and
71396** (2) the EP_xxx flags that indicate what the structure size should be.
71397** The return values is always one of:
71398**
71399**      EXPR_FULLSIZE
71400**      EXPR_REDUCEDSIZE   | EP_Reduced
71401**      EXPR_TOKENONLYSIZE | EP_TokenOnly
71402**
71403** The size of the structure can be found by masking the return value
71404** of this routine with 0xfff.  The flags can be found by masking the
71405** return value with EP_Reduced|EP_TokenOnly.
71406**
71407** Note that with flags==EXPRDUP_REDUCE, this routines works on full-size
71408** (unreduced) Expr objects as they or originally constructed by the parser.
71409** During expression analysis, extra information is computed and moved into
71410** later parts of teh Expr object and that extra information might get chopped
71411** off if the expression is reduced.  Note also that it does not work to
71412** make a EXPRDUP_REDUCE copy of a reduced expression.  It is only legal
71413** to reduce a pristine expression tree from the parser.  The implementation
71414** of dupedExprStructSize() contain multiple assert() statements that attempt
71415** to enforce this constraint.
71416*/
71417static int dupedExprStructSize(Expr *p, int flags){
71418  int nSize;
71419  assert( flags==EXPRDUP_REDUCE || flags==0 ); /* Only one flag value allowed */
71420  if( 0==(flags&EXPRDUP_REDUCE) ){
71421    nSize = EXPR_FULLSIZE;
71422  }else{
71423    assert( !ExprHasAnyProperty(p, EP_TokenOnly|EP_Reduced) );
71424    assert( !ExprHasProperty(p, EP_FromJoin) );
71425    assert( (p->flags2 & EP2_MallocedToken)==0 );
71426    assert( (p->flags2 & EP2_Irreducible)==0 );
71427    if( p->pLeft || p->pRight || p->pColl || p->x.pList ){
71428      nSize = EXPR_REDUCEDSIZE | EP_Reduced;
71429    }else{
71430      nSize = EXPR_TOKENONLYSIZE | EP_TokenOnly;
71431    }
71432  }
71433  return nSize;
71434}
71435
71436/*
71437** This function returns the space in bytes required to store the copy
71438** of the Expr structure and a copy of the Expr.u.zToken string (if that
71439** string is defined.)
71440*/
71441static int dupedExprNodeSize(Expr *p, int flags){
71442  int nByte = dupedExprStructSize(p, flags) & 0xfff;
71443  if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
71444    nByte += sqlite3Strlen30(p->u.zToken)+1;
71445  }
71446  return ROUND8(nByte);
71447}
71448
71449/*
71450** Return the number of bytes required to create a duplicate of the
71451** expression passed as the first argument. The second argument is a
71452** mask containing EXPRDUP_XXX flags.
71453**
71454** The value returned includes space to create a copy of the Expr struct
71455** itself and the buffer referred to by Expr.u.zToken, if any.
71456**
71457** If the EXPRDUP_REDUCE flag is set, then the return value includes
71458** space to duplicate all Expr nodes in the tree formed by Expr.pLeft
71459** and Expr.pRight variables (but not for any structures pointed to or
71460** descended from the Expr.x.pList or Expr.x.pSelect variables).
71461*/
71462static int dupedExprSize(Expr *p, int flags){
71463  int nByte = 0;
71464  if( p ){
71465    nByte = dupedExprNodeSize(p, flags);
71466    if( flags&EXPRDUP_REDUCE ){
71467      nByte += dupedExprSize(p->pLeft, flags) + dupedExprSize(p->pRight, flags);
71468    }
71469  }
71470  return nByte;
71471}
71472
71473/*
71474** This function is similar to sqlite3ExprDup(), except that if pzBuffer
71475** is not NULL then *pzBuffer is assumed to point to a buffer large enough
71476** to store the copy of expression p, the copies of p->u.zToken
71477** (if applicable), and the copies of the p->pLeft and p->pRight expressions,
71478** if any. Before returning, *pzBuffer is set to the first byte passed the
71479** portion of the buffer copied into by this function.
71480*/
71481static Expr *exprDup(sqlite3 *db, Expr *p, int flags, u8 **pzBuffer){
71482  Expr *pNew = 0;                      /* Value to return */
71483  if( p ){
71484    const int isReduced = (flags&EXPRDUP_REDUCE);
71485    u8 *zAlloc;
71486    u32 staticFlag = 0;
71487
71488    assert( pzBuffer==0 || isReduced );
71489
71490    /* Figure out where to write the new Expr structure. */
71491    if( pzBuffer ){
71492      zAlloc = *pzBuffer;
71493      staticFlag = EP_Static;
71494    }else{
71495      zAlloc = sqlite3DbMallocRaw(db, dupedExprSize(p, flags));
71496    }
71497    pNew = (Expr *)zAlloc;
71498
71499    if( pNew ){
71500      /* Set nNewSize to the size allocated for the structure pointed to
71501      ** by pNew. This is either EXPR_FULLSIZE, EXPR_REDUCEDSIZE or
71502      ** EXPR_TOKENONLYSIZE. nToken is set to the number of bytes consumed
71503      ** by the copy of the p->u.zToken string (if any).
71504      */
71505      const unsigned nStructSize = dupedExprStructSize(p, flags);
71506      const int nNewSize = nStructSize & 0xfff;
71507      int nToken;
71508      if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
71509        nToken = sqlite3Strlen30(p->u.zToken) + 1;
71510      }else{
71511        nToken = 0;
71512      }
71513      if( isReduced ){
71514        assert( ExprHasProperty(p, EP_Reduced)==0 );
71515        memcpy(zAlloc, p, nNewSize);
71516      }else{
71517        int nSize = exprStructSize(p);
71518        memcpy(zAlloc, p, nSize);
71519        if( EXPR_FULLSIZE>nSize ){
71520          memset(&zAlloc[nSize], 0, EXPR_FULLSIZE-nSize);
71521        }
71522      }
71523
71524      /* Set the EP_Reduced, EP_TokenOnly, and EP_Static flags appropriately. */
71525      pNew->flags &= ~(EP_Reduced|EP_TokenOnly|EP_Static);
71526      pNew->flags |= nStructSize & (EP_Reduced|EP_TokenOnly);
71527      pNew->flags |= staticFlag;
71528
71529      /* Copy the p->u.zToken string, if any. */
71530      if( nToken ){
71531        char *zToken = pNew->u.zToken = (char*)&zAlloc[nNewSize];
71532        memcpy(zToken, p->u.zToken, nToken);
71533      }
71534
71535      if( 0==((p->flags|pNew->flags) & EP_TokenOnly) ){
71536        /* Fill in the pNew->x.pSelect or pNew->x.pList member. */
71537        if( ExprHasProperty(p, EP_xIsSelect) ){
71538          pNew->x.pSelect = sqlite3SelectDup(db, p->x.pSelect, isReduced);
71539        }else{
71540          pNew->x.pList = sqlite3ExprListDup(db, p->x.pList, isReduced);
71541        }
71542      }
71543
71544      /* Fill in pNew->pLeft and pNew->pRight. */
71545      if( ExprHasAnyProperty(pNew, EP_Reduced|EP_TokenOnly) ){
71546        zAlloc += dupedExprNodeSize(p, flags);
71547        if( ExprHasProperty(pNew, EP_Reduced) ){
71548          pNew->pLeft = exprDup(db, p->pLeft, EXPRDUP_REDUCE, &zAlloc);
71549          pNew->pRight = exprDup(db, p->pRight, EXPRDUP_REDUCE, &zAlloc);
71550        }
71551        if( pzBuffer ){
71552          *pzBuffer = zAlloc;
71553        }
71554      }else{
71555        pNew->flags2 = 0;
71556        if( !ExprHasAnyProperty(p, EP_TokenOnly) ){
71557          pNew->pLeft = sqlite3ExprDup(db, p->pLeft, 0);
71558          pNew->pRight = sqlite3ExprDup(db, p->pRight, 0);
71559        }
71560      }
71561
71562    }
71563  }
71564  return pNew;
71565}
71566
71567/*
71568** The following group of routines make deep copies of expressions,
71569** expression lists, ID lists, and select statements.  The copies can
71570** be deleted (by being passed to their respective ...Delete() routines)
71571** without effecting the originals.
71572**
71573** The expression list, ID, and source lists return by sqlite3ExprListDup(),
71574** sqlite3IdListDup(), and sqlite3SrcListDup() can not be further expanded
71575** by subsequent calls to sqlite*ListAppend() routines.
71576**
71577** Any tables that the SrcList might point to are not duplicated.
71578**
71579** The flags parameter contains a combination of the EXPRDUP_XXX flags.
71580** If the EXPRDUP_REDUCE flag is set, then the structure returned is a
71581** truncated version of the usual Expr structure that will be stored as
71582** part of the in-memory representation of the database schema.
71583*/
71584SQLITE_PRIVATE Expr *sqlite3ExprDup(sqlite3 *db, Expr *p, int flags){
71585  return exprDup(db, p, flags, 0);
71586}
71587SQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3 *db, ExprList *p, int flags){
71588  ExprList *pNew;
71589  struct ExprList_item *pItem, *pOldItem;
71590  int i;
71591  if( p==0 ) return 0;
71592  pNew = sqlite3DbMallocRaw(db, sizeof(*pNew) );
71593  if( pNew==0 ) return 0;
71594  pNew->iECursor = 0;
71595  pNew->nExpr = pNew->nAlloc = p->nExpr;
71596  pNew->a = pItem = sqlite3DbMallocRaw(db,  p->nExpr*sizeof(p->a[0]) );
71597  if( pItem==0 ){
71598    sqlite3DbFree(db, pNew);
71599    return 0;
71600  }
71601  pOldItem = p->a;
71602  for(i=0; i<p->nExpr; i++, pItem++, pOldItem++){
71603    Expr *pOldExpr = pOldItem->pExpr;
71604    pItem->pExpr = sqlite3ExprDup(db, pOldExpr, flags);
71605    pItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
71606    pItem->zSpan = sqlite3DbStrDup(db, pOldItem->zSpan);
71607    pItem->sortOrder = pOldItem->sortOrder;
71608    pItem->done = 0;
71609    pItem->iCol = pOldItem->iCol;
71610    pItem->iAlias = pOldItem->iAlias;
71611  }
71612  return pNew;
71613}
71614
71615/*
71616** If cursors, triggers, views and subqueries are all omitted from
71617** the build, then none of the following routines, except for
71618** sqlite3SelectDup(), can be called. sqlite3SelectDup() is sometimes
71619** called with a NULL argument.
71620*/
71621#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER) \
71622 || !defined(SQLITE_OMIT_SUBQUERY)
71623SQLITE_PRIVATE SrcList *sqlite3SrcListDup(sqlite3 *db, SrcList *p, int flags){
71624  SrcList *pNew;
71625  int i;
71626  int nByte;
71627  if( p==0 ) return 0;
71628  nByte = sizeof(*p) + (p->nSrc>0 ? sizeof(p->a[0]) * (p->nSrc-1) : 0);
71629  pNew = sqlite3DbMallocRaw(db, nByte );
71630  if( pNew==0 ) return 0;
71631  pNew->nSrc = pNew->nAlloc = p->nSrc;
71632  for(i=0; i<p->nSrc; i++){
71633    struct SrcList_item *pNewItem = &pNew->a[i];
71634    struct SrcList_item *pOldItem = &p->a[i];
71635    Table *pTab;
71636    pNewItem->zDatabase = sqlite3DbStrDup(db, pOldItem->zDatabase);
71637    pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
71638    pNewItem->zAlias = sqlite3DbStrDup(db, pOldItem->zAlias);
71639    pNewItem->jointype = pOldItem->jointype;
71640    pNewItem->iCursor = pOldItem->iCursor;
71641    pNewItem->isPopulated = pOldItem->isPopulated;
71642    pNewItem->zIndex = sqlite3DbStrDup(db, pOldItem->zIndex);
71643    pNewItem->notIndexed = pOldItem->notIndexed;
71644    pNewItem->pIndex = pOldItem->pIndex;
71645    pTab = pNewItem->pTab = pOldItem->pTab;
71646    if( pTab ){
71647      pTab->nRef++;
71648    }
71649    pNewItem->pSelect = sqlite3SelectDup(db, pOldItem->pSelect, flags);
71650    pNewItem->pOn = sqlite3ExprDup(db, pOldItem->pOn, flags);
71651    pNewItem->pUsing = sqlite3IdListDup(db, pOldItem->pUsing);
71652    pNewItem->colUsed = pOldItem->colUsed;
71653  }
71654  return pNew;
71655}
71656SQLITE_PRIVATE IdList *sqlite3IdListDup(sqlite3 *db, IdList *p){
71657  IdList *pNew;
71658  int i;
71659  if( p==0 ) return 0;
71660  pNew = sqlite3DbMallocRaw(db, sizeof(*pNew) );
71661  if( pNew==0 ) return 0;
71662  pNew->nId = pNew->nAlloc = p->nId;
71663  pNew->a = sqlite3DbMallocRaw(db, p->nId*sizeof(p->a[0]) );
71664  if( pNew->a==0 ){
71665    sqlite3DbFree(db, pNew);
71666    return 0;
71667  }
71668  for(i=0; i<p->nId; i++){
71669    struct IdList_item *pNewItem = &pNew->a[i];
71670    struct IdList_item *pOldItem = &p->a[i];
71671    pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
71672    pNewItem->idx = pOldItem->idx;
71673  }
71674  return pNew;
71675}
71676SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3 *db, Select *p, int flags){
71677  Select *pNew;
71678  if( p==0 ) return 0;
71679  pNew = sqlite3DbMallocRaw(db, sizeof(*p) );
71680  if( pNew==0 ) return 0;
71681  pNew->pEList = sqlite3ExprListDup(db, p->pEList, flags);
71682  pNew->pSrc = sqlite3SrcListDup(db, p->pSrc, flags);
71683  pNew->pWhere = sqlite3ExprDup(db, p->pWhere, flags);
71684  pNew->pGroupBy = sqlite3ExprListDup(db, p->pGroupBy, flags);
71685  pNew->pHaving = sqlite3ExprDup(db, p->pHaving, flags);
71686  pNew->pOrderBy = sqlite3ExprListDup(db, p->pOrderBy, flags);
71687  pNew->op = p->op;
71688  pNew->pPrior = sqlite3SelectDup(db, p->pPrior, flags);
71689  pNew->pLimit = sqlite3ExprDup(db, p->pLimit, flags);
71690  pNew->pOffset = sqlite3ExprDup(db, p->pOffset, flags);
71691  pNew->iLimit = 0;
71692  pNew->iOffset = 0;
71693  pNew->selFlags = p->selFlags & ~SF_UsesEphemeral;
71694  pNew->pRightmost = 0;
71695  pNew->addrOpenEphm[0] = -1;
71696  pNew->addrOpenEphm[1] = -1;
71697  pNew->addrOpenEphm[2] = -1;
71698  return pNew;
71699}
71700#else
71701SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3 *db, Select *p, int flags){
71702  assert( p==0 );
71703  return 0;
71704}
71705#endif
71706
71707
71708/*
71709** Add a new element to the end of an expression list.  If pList is
71710** initially NULL, then create a new expression list.
71711**
71712** If a memory allocation error occurs, the entire list is freed and
71713** NULL is returned.  If non-NULL is returned, then it is guaranteed
71714** that the new entry was successfully appended.
71715*/
71716SQLITE_PRIVATE ExprList *sqlite3ExprListAppend(
71717  Parse *pParse,          /* Parsing context */
71718  ExprList *pList,        /* List to which to append. Might be NULL */
71719  Expr *pExpr             /* Expression to be appended. Might be NULL */
71720){
71721  sqlite3 *db = pParse->db;
71722  if( pList==0 ){
71723    pList = sqlite3DbMallocZero(db, sizeof(ExprList) );
71724    if( pList==0 ){
71725      goto no_mem;
71726    }
71727    assert( pList->nAlloc==0 );
71728  }
71729  if( pList->nAlloc<=pList->nExpr ){
71730    struct ExprList_item *a;
71731    int n = pList->nAlloc*2 + 4;
71732    a = sqlite3DbRealloc(db, pList->a, n*sizeof(pList->a[0]));
71733    if( a==0 ){
71734      goto no_mem;
71735    }
71736    pList->a = a;
71737    pList->nAlloc = sqlite3DbMallocSize(db, a)/sizeof(a[0]);
71738  }
71739  assert( pList->a!=0 );
71740  if( 1 ){
71741    struct ExprList_item *pItem = &pList->a[pList->nExpr++];
71742    memset(pItem, 0, sizeof(*pItem));
71743    pItem->pExpr = pExpr;
71744  }
71745  return pList;
71746
71747no_mem:
71748  /* Avoid leaking memory if malloc has failed. */
71749  sqlite3ExprDelete(db, pExpr);
71750  sqlite3ExprListDelete(db, pList);
71751  return 0;
71752}
71753
71754/*
71755** Set the ExprList.a[].zName element of the most recently added item
71756** on the expression list.
71757**
71758** pList might be NULL following an OOM error.  But pName should never be
71759** NULL.  If a memory allocation fails, the pParse->db->mallocFailed flag
71760** is set.
71761*/
71762SQLITE_PRIVATE void sqlite3ExprListSetName(
71763  Parse *pParse,          /* Parsing context */
71764  ExprList *pList,        /* List to which to add the span. */
71765  Token *pName,           /* Name to be added */
71766  int dequote             /* True to cause the name to be dequoted */
71767){
71768  assert( pList!=0 || pParse->db->mallocFailed!=0 );
71769  if( pList ){
71770    struct ExprList_item *pItem;
71771    assert( pList->nExpr>0 );
71772    pItem = &pList->a[pList->nExpr-1];
71773    assert( pItem->zName==0 );
71774    pItem->zName = sqlite3DbStrNDup(pParse->db, pName->z, pName->n);
71775    if( dequote && pItem->zName ) sqlite3Dequote(pItem->zName);
71776  }
71777}
71778
71779/*
71780** Set the ExprList.a[].zSpan element of the most recently added item
71781** on the expression list.
71782**
71783** pList might be NULL following an OOM error.  But pSpan should never be
71784** NULL.  If a memory allocation fails, the pParse->db->mallocFailed flag
71785** is set.
71786*/
71787SQLITE_PRIVATE void sqlite3ExprListSetSpan(
71788  Parse *pParse,          /* Parsing context */
71789  ExprList *pList,        /* List to which to add the span. */
71790  ExprSpan *pSpan         /* The span to be added */
71791){
71792  sqlite3 *db = pParse->db;
71793  assert( pList!=0 || db->mallocFailed!=0 );
71794  if( pList ){
71795    struct ExprList_item *pItem = &pList->a[pList->nExpr-1];
71796    assert( pList->nExpr>0 );
71797    assert( db->mallocFailed || pItem->pExpr==pSpan->pExpr );
71798    sqlite3DbFree(db, pItem->zSpan);
71799    pItem->zSpan = sqlite3DbStrNDup(db, (char*)pSpan->zStart,
71800                                    (int)(pSpan->zEnd - pSpan->zStart));
71801  }
71802}
71803
71804/*
71805** If the expression list pEList contains more than iLimit elements,
71806** leave an error message in pParse.
71807*/
71808SQLITE_PRIVATE void sqlite3ExprListCheckLength(
71809  Parse *pParse,
71810  ExprList *pEList,
71811  const char *zObject
71812){
71813  int mx = pParse->db->aLimit[SQLITE_LIMIT_COLUMN];
71814  testcase( pEList && pEList->nExpr==mx );
71815  testcase( pEList && pEList->nExpr==mx+1 );
71816  if( pEList && pEList->nExpr>mx ){
71817    sqlite3ErrorMsg(pParse, "too many columns in %s", zObject);
71818  }
71819}
71820
71821/*
71822** Delete an entire expression list.
71823*/
71824SQLITE_PRIVATE void sqlite3ExprListDelete(sqlite3 *db, ExprList *pList){
71825  int i;
71826  struct ExprList_item *pItem;
71827  if( pList==0 ) return;
71828  assert( pList->a!=0 || (pList->nExpr==0 && pList->nAlloc==0) );
71829  assert( pList->nExpr<=pList->nAlloc );
71830  for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
71831    sqlite3ExprDelete(db, pItem->pExpr);
71832    sqlite3DbFree(db, pItem->zName);
71833    sqlite3DbFree(db, pItem->zSpan);
71834  }
71835  sqlite3DbFree(db, pList->a);
71836  sqlite3DbFree(db, pList);
71837}
71838
71839/*
71840** These routines are Walker callbacks.  Walker.u.pi is a pointer
71841** to an integer.  These routines are checking an expression to see
71842** if it is a constant.  Set *Walker.u.pi to 0 if the expression is
71843** not constant.
71844**
71845** These callback routines are used to implement the following:
71846**
71847**     sqlite3ExprIsConstant()
71848**     sqlite3ExprIsConstantNotJoin()
71849**     sqlite3ExprIsConstantOrFunction()
71850**
71851*/
71852static int exprNodeIsConstant(Walker *pWalker, Expr *pExpr){
71853
71854  /* If pWalker->u.i is 3 then any term of the expression that comes from
71855  ** the ON or USING clauses of a join disqualifies the expression
71856  ** from being considered constant. */
71857  if( pWalker->u.i==3 && ExprHasAnyProperty(pExpr, EP_FromJoin) ){
71858    pWalker->u.i = 0;
71859    return WRC_Abort;
71860  }
71861
71862  switch( pExpr->op ){
71863    /* Consider functions to be constant if all their arguments are constant
71864    ** and pWalker->u.i==2 */
71865    case TK_FUNCTION:
71866      if( pWalker->u.i==2 ) return 0;
71867      /* Fall through */
71868    case TK_ID:
71869    case TK_COLUMN:
71870    case TK_AGG_FUNCTION:
71871    case TK_AGG_COLUMN:
71872      testcase( pExpr->op==TK_ID );
71873      testcase( pExpr->op==TK_COLUMN );
71874      testcase( pExpr->op==TK_AGG_FUNCTION );
71875      testcase( pExpr->op==TK_AGG_COLUMN );
71876      pWalker->u.i = 0;
71877      return WRC_Abort;
71878    default:
71879      testcase( pExpr->op==TK_SELECT ); /* selectNodeIsConstant will disallow */
71880      testcase( pExpr->op==TK_EXISTS ); /* selectNodeIsConstant will disallow */
71881      return WRC_Continue;
71882  }
71883}
71884static int selectNodeIsConstant(Walker *pWalker, Select *NotUsed){
71885  UNUSED_PARAMETER(NotUsed);
71886  pWalker->u.i = 0;
71887  return WRC_Abort;
71888}
71889static int exprIsConst(Expr *p, int initFlag){
71890  Walker w;
71891  w.u.i = initFlag;
71892  w.xExprCallback = exprNodeIsConstant;
71893  w.xSelectCallback = selectNodeIsConstant;
71894  sqlite3WalkExpr(&w, p);
71895  return w.u.i;
71896}
71897
71898/*
71899** Walk an expression tree.  Return 1 if the expression is constant
71900** and 0 if it involves variables or function calls.
71901**
71902** For the purposes of this function, a double-quoted string (ex: "abc")
71903** is considered a variable but a single-quoted string (ex: 'abc') is
71904** a constant.
71905*/
71906SQLITE_PRIVATE int sqlite3ExprIsConstant(Expr *p){
71907  return exprIsConst(p, 1);
71908}
71909
71910/*
71911** Walk an expression tree.  Return 1 if the expression is constant
71912** that does no originate from the ON or USING clauses of a join.
71913** Return 0 if it involves variables or function calls or terms from
71914** an ON or USING clause.
71915*/
71916SQLITE_PRIVATE int sqlite3ExprIsConstantNotJoin(Expr *p){
71917  return exprIsConst(p, 3);
71918}
71919
71920/*
71921** Walk an expression tree.  Return 1 if the expression is constant
71922** or a function call with constant arguments.  Return and 0 if there
71923** are any variables.
71924**
71925** For the purposes of this function, a double-quoted string (ex: "abc")
71926** is considered a variable but a single-quoted string (ex: 'abc') is
71927** a constant.
71928*/
71929SQLITE_PRIVATE int sqlite3ExprIsConstantOrFunction(Expr *p){
71930  return exprIsConst(p, 2);
71931}
71932
71933/*
71934** If the expression p codes a constant integer that is small enough
71935** to fit in a 32-bit integer, return 1 and put the value of the integer
71936** in *pValue.  If the expression is not an integer or if it is too big
71937** to fit in a signed 32-bit integer, return 0 and leave *pValue unchanged.
71938*/
71939SQLITE_PRIVATE int sqlite3ExprIsInteger(Expr *p, int *pValue){
71940  int rc = 0;
71941
71942  /* If an expression is an integer literal that fits in a signed 32-bit
71943  ** integer, then the EP_IntValue flag will have already been set */
71944  assert( p->op!=TK_INTEGER || (p->flags & EP_IntValue)!=0
71945           || sqlite3GetInt32(p->u.zToken, &rc)==0 );
71946
71947  if( p->flags & EP_IntValue ){
71948    *pValue = p->u.iValue;
71949    return 1;
71950  }
71951  switch( p->op ){
71952    case TK_UPLUS: {
71953      rc = sqlite3ExprIsInteger(p->pLeft, pValue);
71954      break;
71955    }
71956    case TK_UMINUS: {
71957      int v;
71958      if( sqlite3ExprIsInteger(p->pLeft, &v) ){
71959        *pValue = -v;
71960        rc = 1;
71961      }
71962      break;
71963    }
71964    default: break;
71965  }
71966  return rc;
71967}
71968
71969/*
71970** Return FALSE if there is no chance that the expression can be NULL.
71971**
71972** If the expression might be NULL or if the expression is too complex
71973** to tell return TRUE.
71974**
71975** This routine is used as an optimization, to skip OP_IsNull opcodes
71976** when we know that a value cannot be NULL.  Hence, a false positive
71977** (returning TRUE when in fact the expression can never be NULL) might
71978** be a small performance hit but is otherwise harmless.  On the other
71979** hand, a false negative (returning FALSE when the result could be NULL)
71980** will likely result in an incorrect answer.  So when in doubt, return
71981** TRUE.
71982*/
71983SQLITE_PRIVATE int sqlite3ExprCanBeNull(const Expr *p){
71984  u8 op;
71985  while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ p = p->pLeft; }
71986  op = p->op;
71987  if( op==TK_REGISTER ) op = p->op2;
71988  switch( op ){
71989    case TK_INTEGER:
71990    case TK_STRING:
71991    case TK_FLOAT:
71992    case TK_BLOB:
71993      return 0;
71994    default:
71995      return 1;
71996  }
71997}
71998
71999/*
72000** Generate an OP_IsNull instruction that tests register iReg and jumps
72001** to location iDest if the value in iReg is NULL.  The value in iReg
72002** was computed by pExpr.  If we can look at pExpr at compile-time and
72003** determine that it can never generate a NULL, then the OP_IsNull operation
72004** can be omitted.
72005*/
72006SQLITE_PRIVATE void sqlite3ExprCodeIsNullJump(
72007  Vdbe *v,            /* The VDBE under construction */
72008  const Expr *pExpr,  /* Only generate OP_IsNull if this expr can be NULL */
72009  int iReg,           /* Test the value in this register for NULL */
72010  int iDest           /* Jump here if the value is null */
72011){
72012  if( sqlite3ExprCanBeNull(pExpr) ){
72013    sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iDest);
72014  }
72015}
72016
72017/*
72018** Return TRUE if the given expression is a constant which would be
72019** unchanged by OP_Affinity with the affinity given in the second
72020** argument.
72021**
72022** This routine is used to determine if the OP_Affinity operation
72023** can be omitted.  When in doubt return FALSE.  A false negative
72024** is harmless.  A false positive, however, can result in the wrong
72025** answer.
72026*/
72027SQLITE_PRIVATE int sqlite3ExprNeedsNoAffinityChange(const Expr *p, char aff){
72028  u8 op;
72029  if( aff==SQLITE_AFF_NONE ) return 1;
72030  while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ p = p->pLeft; }
72031  op = p->op;
72032  if( op==TK_REGISTER ) op = p->op2;
72033  switch( op ){
72034    case TK_INTEGER: {
72035      return aff==SQLITE_AFF_INTEGER || aff==SQLITE_AFF_NUMERIC;
72036    }
72037    case TK_FLOAT: {
72038      return aff==SQLITE_AFF_REAL || aff==SQLITE_AFF_NUMERIC;
72039    }
72040    case TK_STRING: {
72041      return aff==SQLITE_AFF_TEXT;
72042    }
72043    case TK_BLOB: {
72044      return 1;
72045    }
72046    case TK_COLUMN: {
72047      assert( p->iTable>=0 );  /* p cannot be part of a CHECK constraint */
72048      return p->iColumn<0
72049          && (aff==SQLITE_AFF_INTEGER || aff==SQLITE_AFF_NUMERIC);
72050    }
72051    default: {
72052      return 0;
72053    }
72054  }
72055}
72056
72057/*
72058** Return TRUE if the given string is a row-id column name.
72059*/
72060SQLITE_PRIVATE int sqlite3IsRowid(const char *z){
72061  if( sqlite3StrICmp(z, "_ROWID_")==0 ) return 1;
72062  if( sqlite3StrICmp(z, "ROWID")==0 ) return 1;
72063  if( sqlite3StrICmp(z, "OID")==0 ) return 1;
72064  return 0;
72065}
72066
72067/*
72068** Return true if we are able to the IN operator optimization on a
72069** query of the form
72070**
72071**       x IN (SELECT ...)
72072**
72073** Where the SELECT... clause is as specified by the parameter to this
72074** routine.
72075**
72076** The Select object passed in has already been preprocessed and no
72077** errors have been found.
72078*/
72079#ifndef SQLITE_OMIT_SUBQUERY
72080static int isCandidateForInOpt(Select *p){
72081  SrcList *pSrc;
72082  ExprList *pEList;
72083  Table *pTab;
72084  if( p==0 ) return 0;                   /* right-hand side of IN is SELECT */
72085  if( p->pPrior ) return 0;              /* Not a compound SELECT */
72086  if( p->selFlags & (SF_Distinct|SF_Aggregate) ){
72087    testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
72088    testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
72089    return 0; /* No DISTINCT keyword and no aggregate functions */
72090  }
72091  assert( p->pGroupBy==0 );              /* Has no GROUP BY clause */
72092  if( p->pLimit ) return 0;              /* Has no LIMIT clause */
72093  assert( p->pOffset==0 );               /* No LIMIT means no OFFSET */
72094  if( p->pWhere ) return 0;              /* Has no WHERE clause */
72095  pSrc = p->pSrc;
72096  assert( pSrc!=0 );
72097  if( pSrc->nSrc!=1 ) return 0;          /* Single term in FROM clause */
72098  if( pSrc->a[0].pSelect ) return 0;     /* FROM is not a subquery or view */
72099  pTab = pSrc->a[0].pTab;
72100  if( NEVER(pTab==0) ) return 0;
72101  assert( pTab->pSelect==0 );            /* FROM clause is not a view */
72102  if( IsVirtual(pTab) ) return 0;        /* FROM clause not a virtual table */
72103  pEList = p->pEList;
72104  if( pEList->nExpr!=1 ) return 0;       /* One column in the result set */
72105  if( pEList->a[0].pExpr->op!=TK_COLUMN ) return 0; /* Result is a column */
72106  return 1;
72107}
72108#endif /* SQLITE_OMIT_SUBQUERY */
72109
72110/*
72111** This function is used by the implementation of the IN (...) operator.
72112** It's job is to find or create a b-tree structure that may be used
72113** either to test for membership of the (...) set or to iterate through
72114** its members, skipping duplicates.
72115**
72116** The index of the cursor opened on the b-tree (database table, database index
72117** or ephermal table) is stored in pX->iTable before this function returns.
72118** The returned value of this function indicates the b-tree type, as follows:
72119**
72120**   IN_INDEX_ROWID - The cursor was opened on a database table.
72121**   IN_INDEX_INDEX - The cursor was opened on a database index.
72122**   IN_INDEX_EPH -   The cursor was opened on a specially created and
72123**                    populated epheremal table.
72124**
72125** An existing b-tree may only be used if the SELECT is of the simple
72126** form:
72127**
72128**     SELECT <column> FROM <table>
72129**
72130** If the prNotFound parameter is 0, then the b-tree will be used to iterate
72131** through the set members, skipping any duplicates. In this case an
72132** epheremal table must be used unless the selected <column> is guaranteed
72133** to be unique - either because it is an INTEGER PRIMARY KEY or it
72134** has a UNIQUE constraint or UNIQUE index.
72135**
72136** If the prNotFound parameter is not 0, then the b-tree will be used
72137** for fast set membership tests. In this case an epheremal table must
72138** be used unless <column> is an INTEGER PRIMARY KEY or an index can
72139** be found with <column> as its left-most column.
72140**
72141** When the b-tree is being used for membership tests, the calling function
72142** needs to know whether or not the structure contains an SQL NULL
72143** value in order to correctly evaluate expressions like "X IN (Y, Z)".
72144** If there is any chance that the (...) might contain a NULL value at
72145** runtime, then a register is allocated and the register number written
72146** to *prNotFound. If there is no chance that the (...) contains a
72147** NULL value, then *prNotFound is left unchanged.
72148**
72149** If a register is allocated and its location stored in *prNotFound, then
72150** its initial value is NULL.  If the (...) does not remain constant
72151** for the duration of the query (i.e. the SELECT within the (...)
72152** is a correlated subquery) then the value of the allocated register is
72153** reset to NULL each time the subquery is rerun. This allows the
72154** caller to use vdbe code equivalent to the following:
72155**
72156**   if( register==NULL ){
72157**     has_null = <test if data structure contains null>
72158**     register = 1
72159**   }
72160**
72161** in order to avoid running the <test if data structure contains null>
72162** test more often than is necessary.
72163*/
72164#ifndef SQLITE_OMIT_SUBQUERY
72165SQLITE_PRIVATE int sqlite3FindInIndex(Parse *pParse, Expr *pX, int *prNotFound){
72166  Select *p;                            /* SELECT to the right of IN operator */
72167  int eType = 0;                        /* Type of RHS table. IN_INDEX_* */
72168  int iTab = pParse->nTab++;            /* Cursor of the RHS table */
72169  int mustBeUnique = (prNotFound==0);   /* True if RHS must be unique */
72170
72171  assert( pX->op==TK_IN );
72172
72173  /* Check to see if an existing table or index can be used to
72174  ** satisfy the query.  This is preferable to generating a new
72175  ** ephemeral table.
72176  */
72177  p = (ExprHasProperty(pX, EP_xIsSelect) ? pX->x.pSelect : 0);
72178  if( ALWAYS(pParse->nErr==0) && isCandidateForInOpt(p) ){
72179    sqlite3 *db = pParse->db;              /* Database connection */
72180    Expr *pExpr = p->pEList->a[0].pExpr;   /* Expression <column> */
72181    int iCol = pExpr->iColumn;             /* Index of column <column> */
72182    Vdbe *v = sqlite3GetVdbe(pParse);      /* Virtual machine being coded */
72183    Table *pTab = p->pSrc->a[0].pTab;      /* Table <table>. */
72184    int iDb;                               /* Database idx for pTab */
72185
72186    /* Code an OP_VerifyCookie and OP_TableLock for <table>. */
72187    iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
72188    sqlite3CodeVerifySchema(pParse, iDb);
72189    sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
72190
72191    /* This function is only called from two places. In both cases the vdbe
72192    ** has already been allocated. So assume sqlite3GetVdbe() is always
72193    ** successful here.
72194    */
72195    assert(v);
72196    if( iCol<0 ){
72197      int iMem = ++pParse->nMem;
72198      int iAddr;
72199
72200      iAddr = sqlite3VdbeAddOp1(v, OP_If, iMem);
72201      sqlite3VdbeAddOp2(v, OP_Integer, 1, iMem);
72202
72203      sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
72204      eType = IN_INDEX_ROWID;
72205
72206      sqlite3VdbeJumpHere(v, iAddr);
72207    }else{
72208      Index *pIdx;                         /* Iterator variable */
72209
72210      /* The collation sequence used by the comparison. If an index is to
72211      ** be used in place of a temp-table, it must be ordered according
72212      ** to this collation sequence.  */
72213      CollSeq *pReq = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pExpr);
72214
72215      /* Check that the affinity that will be used to perform the
72216      ** comparison is the same as the affinity of the column. If
72217      ** it is not, it is not possible to use any index.
72218      */
72219      char aff = comparisonAffinity(pX);
72220      int affinity_ok = (pTab->aCol[iCol].affinity==aff||aff==SQLITE_AFF_NONE);
72221
72222      for(pIdx=pTab->pIndex; pIdx && eType==0 && affinity_ok; pIdx=pIdx->pNext){
72223        if( (pIdx->aiColumn[0]==iCol)
72224         && sqlite3FindCollSeq(db, ENC(db), pIdx->azColl[0], 0)==pReq
72225         && (!mustBeUnique || (pIdx->nColumn==1 && pIdx->onError!=OE_None))
72226        ){
72227          int iMem = ++pParse->nMem;
72228          int iAddr;
72229          char *pKey;
72230
72231          pKey = (char *)sqlite3IndexKeyinfo(pParse, pIdx);
72232          iAddr = sqlite3VdbeAddOp1(v, OP_If, iMem);
72233          sqlite3VdbeAddOp2(v, OP_Integer, 1, iMem);
72234
72235          sqlite3VdbeAddOp4(v, OP_OpenRead, iTab, pIdx->tnum, iDb,
72236                               pKey,P4_KEYINFO_HANDOFF);
72237          VdbeComment((v, "%s", pIdx->zName));
72238          eType = IN_INDEX_INDEX;
72239
72240          sqlite3VdbeJumpHere(v, iAddr);
72241          if( prNotFound && !pTab->aCol[iCol].notNull ){
72242            *prNotFound = ++pParse->nMem;
72243          }
72244        }
72245      }
72246    }
72247  }
72248
72249  if( eType==0 ){
72250    /* Could not found an existing table or index to use as the RHS b-tree.
72251    ** We will have to generate an ephemeral table to do the job.
72252    */
72253    double savedNQueryLoop = pParse->nQueryLoop;
72254    int rMayHaveNull = 0;
72255    eType = IN_INDEX_EPH;
72256    if( prNotFound ){
72257      *prNotFound = rMayHaveNull = ++pParse->nMem;
72258    }else{
72259      testcase( pParse->nQueryLoop>(double)1 );
72260      pParse->nQueryLoop = (double)1;
72261      if( pX->pLeft->iColumn<0 && !ExprHasAnyProperty(pX, EP_xIsSelect) ){
72262        eType = IN_INDEX_ROWID;
72263      }
72264    }
72265    sqlite3CodeSubselect(pParse, pX, rMayHaveNull, eType==IN_INDEX_ROWID);
72266    pParse->nQueryLoop = savedNQueryLoop;
72267  }else{
72268    pX->iTable = iTab;
72269  }
72270  return eType;
72271}
72272#endif
72273
72274/*
72275** Generate code for scalar subqueries used as a subquery expression, EXISTS,
72276** or IN operators.  Examples:
72277**
72278**     (SELECT a FROM b)          -- subquery
72279**     EXISTS (SELECT a FROM b)   -- EXISTS subquery
72280**     x IN (4,5,11)              -- IN operator with list on right-hand side
72281**     x IN (SELECT a FROM b)     -- IN operator with subquery on the right
72282**
72283** The pExpr parameter describes the expression that contains the IN
72284** operator or subquery.
72285**
72286** If parameter isRowid is non-zero, then expression pExpr is guaranteed
72287** to be of the form "<rowid> IN (?, ?, ?)", where <rowid> is a reference
72288** to some integer key column of a table B-Tree. In this case, use an
72289** intkey B-Tree to store the set of IN(...) values instead of the usual
72290** (slower) variable length keys B-Tree.
72291**
72292** If rMayHaveNull is non-zero, that means that the operation is an IN
72293** (not a SELECT or EXISTS) and that the RHS might contains NULLs.
72294** Furthermore, the IN is in a WHERE clause and that we really want
72295** to iterate over the RHS of the IN operator in order to quickly locate
72296** all corresponding LHS elements.  All this routine does is initialize
72297** the register given by rMayHaveNull to NULL.  Calling routines will take
72298** care of changing this register value to non-NULL if the RHS is NULL-free.
72299**
72300** If rMayHaveNull is zero, that means that the subquery is being used
72301** for membership testing only.  There is no need to initialize any
72302** registers to indicate the presense or absence of NULLs on the RHS.
72303**
72304** For a SELECT or EXISTS operator, return the register that holds the
72305** result.  For IN operators or if an error occurs, the return value is 0.
72306*/
72307#ifndef SQLITE_OMIT_SUBQUERY
72308SQLITE_PRIVATE int sqlite3CodeSubselect(
72309  Parse *pParse,          /* Parsing context */
72310  Expr *pExpr,            /* The IN, SELECT, or EXISTS operator */
72311  int rMayHaveNull,       /* Register that records whether NULLs exist in RHS */
72312  int isRowid             /* If true, LHS of IN operator is a rowid */
72313){
72314  int testAddr = 0;                       /* One-time test address */
72315  int rReg = 0;                           /* Register storing resulting */
72316  Vdbe *v = sqlite3GetVdbe(pParse);
72317  if( NEVER(v==0) ) return 0;
72318  sqlite3ExprCachePush(pParse);
72319
72320  /* This code must be run in its entirety every time it is encountered
72321  ** if any of the following is true:
72322  **
72323  **    *  The right-hand side is a correlated subquery
72324  **    *  The right-hand side is an expression list containing variables
72325  **    *  We are inside a trigger
72326  **
72327  ** If all of the above are false, then we can run this code just once
72328  ** save the results, and reuse the same result on subsequent invocations.
72329  */
72330  if( !ExprHasAnyProperty(pExpr, EP_VarSelect) && !pParse->pTriggerTab ){
72331    int mem = ++pParse->nMem;
72332    sqlite3VdbeAddOp1(v, OP_If, mem);
72333    testAddr = sqlite3VdbeAddOp2(v, OP_Integer, 1, mem);
72334    assert( testAddr>0 || pParse->db->mallocFailed );
72335  }
72336
72337#ifndef SQLITE_OMIT_EXPLAIN
72338  if( pParse->explain==2 ){
72339    char *zMsg = sqlite3MPrintf(
72340        pParse->db, "EXECUTE %s%s SUBQUERY %d", testAddr?"":"CORRELATED ",
72341        pExpr->op==TK_IN?"LIST":"SCALAR", pParse->iNextSelectId
72342    );
72343    sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
72344  }
72345#endif
72346
72347  switch( pExpr->op ){
72348    case TK_IN: {
72349      char affinity;              /* Affinity of the LHS of the IN */
72350      KeyInfo keyInfo;            /* Keyinfo for the generated table */
72351      int addr;                   /* Address of OP_OpenEphemeral instruction */
72352      Expr *pLeft = pExpr->pLeft; /* the LHS of the IN operator */
72353
72354      if( rMayHaveNull ){
72355        sqlite3VdbeAddOp2(v, OP_Null, 0, rMayHaveNull);
72356      }
72357
72358      affinity = sqlite3ExprAffinity(pLeft);
72359
72360      /* Whether this is an 'x IN(SELECT...)' or an 'x IN(<exprlist>)'
72361      ** expression it is handled the same way.  An ephemeral table is
72362      ** filled with single-field index keys representing the results
72363      ** from the SELECT or the <exprlist>.
72364      **
72365      ** If the 'x' expression is a column value, or the SELECT...
72366      ** statement returns a column value, then the affinity of that
72367      ** column is used to build the index keys. If both 'x' and the
72368      ** SELECT... statement are columns, then numeric affinity is used
72369      ** if either column has NUMERIC or INTEGER affinity. If neither
72370      ** 'x' nor the SELECT... statement are columns, then numeric affinity
72371      ** is used.
72372      */
72373      pExpr->iTable = pParse->nTab++;
72374      addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pExpr->iTable, !isRowid);
72375      if( rMayHaveNull==0 ) sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
72376      memset(&keyInfo, 0, sizeof(keyInfo));
72377      keyInfo.nField = 1;
72378
72379      if( ExprHasProperty(pExpr, EP_xIsSelect) ){
72380        /* Case 1:     expr IN (SELECT ...)
72381        **
72382        ** Generate code to write the results of the select into the temporary
72383        ** table allocated and opened above.
72384        */
72385        SelectDest dest;
72386        ExprList *pEList;
72387
72388        assert( !isRowid );
72389        sqlite3SelectDestInit(&dest, SRT_Set, pExpr->iTable);
72390        dest.affinity = (u8)affinity;
72391        assert( (pExpr->iTable&0x0000FFFF)==pExpr->iTable );
72392        pExpr->x.pSelect->iLimit = 0;
72393        if( sqlite3Select(pParse, pExpr->x.pSelect, &dest) ){
72394          return 0;
72395        }
72396        pEList = pExpr->x.pSelect->pEList;
72397        if( ALWAYS(pEList!=0 && pEList->nExpr>0) ){
72398          keyInfo.aColl[0] = sqlite3BinaryCompareCollSeq(pParse, pExpr->pLeft,
72399              pEList->a[0].pExpr);
72400        }
72401      }else if( ALWAYS(pExpr->x.pList!=0) ){
72402        /* Case 2:     expr IN (exprlist)
72403        **
72404        ** For each expression, build an index key from the evaluation and
72405        ** store it in the temporary table. If <expr> is a column, then use
72406        ** that columns affinity when building index keys. If <expr> is not
72407        ** a column, use numeric affinity.
72408        */
72409        int i;
72410        ExprList *pList = pExpr->x.pList;
72411        struct ExprList_item *pItem;
72412        int r1, r2, r3;
72413
72414        if( !affinity ){
72415          affinity = SQLITE_AFF_NONE;
72416        }
72417        keyInfo.aColl[0] = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
72418
72419        /* Loop through each expression in <exprlist>. */
72420        r1 = sqlite3GetTempReg(pParse);
72421        r2 = sqlite3GetTempReg(pParse);
72422        sqlite3VdbeAddOp2(v, OP_Null, 0, r2);
72423        for(i=pList->nExpr, pItem=pList->a; i>0; i--, pItem++){
72424          Expr *pE2 = pItem->pExpr;
72425          int iValToIns;
72426
72427          /* If the expression is not constant then we will need to
72428          ** disable the test that was generated above that makes sure
72429          ** this code only executes once.  Because for a non-constant
72430          ** expression we need to rerun this code each time.
72431          */
72432          if( testAddr && !sqlite3ExprIsConstant(pE2) ){
72433            sqlite3VdbeChangeToNoop(v, testAddr-1, 2);
72434            testAddr = 0;
72435          }
72436
72437          /* Evaluate the expression and insert it into the temp table */
72438          if( isRowid && sqlite3ExprIsInteger(pE2, &iValToIns) ){
72439            sqlite3VdbeAddOp3(v, OP_InsertInt, pExpr->iTable, r2, iValToIns);
72440          }else{
72441            r3 = sqlite3ExprCodeTarget(pParse, pE2, r1);
72442            if( isRowid ){
72443              sqlite3VdbeAddOp2(v, OP_MustBeInt, r3,
72444                                sqlite3VdbeCurrentAddr(v)+2);
72445              sqlite3VdbeAddOp3(v, OP_Insert, pExpr->iTable, r2, r3);
72446            }else{
72447              sqlite3VdbeAddOp4(v, OP_MakeRecord, r3, 1, r2, &affinity, 1);
72448              sqlite3ExprCacheAffinityChange(pParse, r3, 1);
72449              sqlite3VdbeAddOp2(v, OP_IdxInsert, pExpr->iTable, r2);
72450            }
72451          }
72452        }
72453        sqlite3ReleaseTempReg(pParse, r1);
72454        sqlite3ReleaseTempReg(pParse, r2);
72455      }
72456      if( !isRowid ){
72457        sqlite3VdbeChangeP4(v, addr, (void *)&keyInfo, P4_KEYINFO);
72458      }
72459      break;
72460    }
72461
72462    case TK_EXISTS:
72463    case TK_SELECT:
72464    default: {
72465      /* If this has to be a scalar SELECT.  Generate code to put the
72466      ** value of this select in a memory cell and record the number
72467      ** of the memory cell in iColumn.  If this is an EXISTS, write
72468      ** an integer 0 (not exists) or 1 (exists) into a memory cell
72469      ** and record that memory cell in iColumn.
72470      */
72471      Select *pSel;                         /* SELECT statement to encode */
72472      SelectDest dest;                      /* How to deal with SELECt result */
72473
72474      testcase( pExpr->op==TK_EXISTS );
72475      testcase( pExpr->op==TK_SELECT );
72476      assert( pExpr->op==TK_EXISTS || pExpr->op==TK_SELECT );
72477
72478      assert( ExprHasProperty(pExpr, EP_xIsSelect) );
72479      pSel = pExpr->x.pSelect;
72480      sqlite3SelectDestInit(&dest, 0, ++pParse->nMem);
72481      if( pExpr->op==TK_SELECT ){
72482        dest.eDest = SRT_Mem;
72483        sqlite3VdbeAddOp2(v, OP_Null, 0, dest.iParm);
72484        VdbeComment((v, "Init subquery result"));
72485      }else{
72486        dest.eDest = SRT_Exists;
72487        sqlite3VdbeAddOp2(v, OP_Integer, 0, dest.iParm);
72488        VdbeComment((v, "Init EXISTS result"));
72489      }
72490      sqlite3ExprDelete(pParse->db, pSel->pLimit);
72491      pSel->pLimit = sqlite3PExpr(pParse, TK_INTEGER, 0, 0,
72492                                  &sqlite3IntTokens[1]);
72493      pSel->iLimit = 0;
72494      if( sqlite3Select(pParse, pSel, &dest) ){
72495        return 0;
72496      }
72497      rReg = dest.iParm;
72498      ExprSetIrreducible(pExpr);
72499      break;
72500    }
72501  }
72502
72503  if( testAddr ){
72504    sqlite3VdbeJumpHere(v, testAddr-1);
72505  }
72506  sqlite3ExprCachePop(pParse, 1);
72507
72508  return rReg;
72509}
72510#endif /* SQLITE_OMIT_SUBQUERY */
72511
72512#ifndef SQLITE_OMIT_SUBQUERY
72513/*
72514** Generate code for an IN expression.
72515**
72516**      x IN (SELECT ...)
72517**      x IN (value, value, ...)
72518**
72519** The left-hand side (LHS) is a scalar expression.  The right-hand side (RHS)
72520** is an array of zero or more values.  The expression is true if the LHS is
72521** contained within the RHS.  The value of the expression is unknown (NULL)
72522** if the LHS is NULL or if the LHS is not contained within the RHS and the
72523** RHS contains one or more NULL values.
72524**
72525** This routine generates code will jump to destIfFalse if the LHS is not
72526** contained within the RHS.  If due to NULLs we cannot determine if the LHS
72527** is contained in the RHS then jump to destIfNull.  If the LHS is contained
72528** within the RHS then fall through.
72529*/
72530static void sqlite3ExprCodeIN(
72531  Parse *pParse,        /* Parsing and code generating context */
72532  Expr *pExpr,          /* The IN expression */
72533  int destIfFalse,      /* Jump here if LHS is not contained in the RHS */
72534  int destIfNull        /* Jump here if the results are unknown due to NULLs */
72535){
72536  int rRhsHasNull = 0;  /* Register that is true if RHS contains NULL values */
72537  char affinity;        /* Comparison affinity to use */
72538  int eType;            /* Type of the RHS */
72539  int r1;               /* Temporary use register */
72540  Vdbe *v;              /* Statement under construction */
72541
72542  /* Compute the RHS.   After this step, the table with cursor
72543  ** pExpr->iTable will contains the values that make up the RHS.
72544  */
72545  v = pParse->pVdbe;
72546  assert( v!=0 );       /* OOM detected prior to this routine */
72547  VdbeNoopComment((v, "begin IN expr"));
72548  eType = sqlite3FindInIndex(pParse, pExpr, &rRhsHasNull);
72549
72550  /* Figure out the affinity to use to create a key from the results
72551  ** of the expression. affinityStr stores a static string suitable for
72552  ** P4 of OP_MakeRecord.
72553  */
72554  affinity = comparisonAffinity(pExpr);
72555
72556  /* Code the LHS, the <expr> from "<expr> IN (...)".
72557  */
72558  sqlite3ExprCachePush(pParse);
72559  r1 = sqlite3GetTempReg(pParse);
72560  sqlite3ExprCode(pParse, pExpr->pLeft, r1);
72561
72562  /* If the LHS is NULL, then the result is either false or NULL depending
72563  ** on whether the RHS is empty or not, respectively.
72564  */
72565  if( destIfNull==destIfFalse ){
72566    /* Shortcut for the common case where the false and NULL outcomes are
72567    ** the same. */
72568    sqlite3VdbeAddOp2(v, OP_IsNull, r1, destIfNull);
72569  }else{
72570    int addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, r1);
72571    sqlite3VdbeAddOp2(v, OP_Rewind, pExpr->iTable, destIfFalse);
72572    sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfNull);
72573    sqlite3VdbeJumpHere(v, addr1);
72574  }
72575
72576  if( eType==IN_INDEX_ROWID ){
72577    /* In this case, the RHS is the ROWID of table b-tree
72578    */
72579    sqlite3VdbeAddOp2(v, OP_MustBeInt, r1, destIfFalse);
72580    sqlite3VdbeAddOp3(v, OP_NotExists, pExpr->iTable, destIfFalse, r1);
72581  }else{
72582    /* In this case, the RHS is an index b-tree.
72583    */
72584    sqlite3VdbeAddOp4(v, OP_Affinity, r1, 1, 0, &affinity, 1);
72585
72586    /* If the set membership test fails, then the result of the
72587    ** "x IN (...)" expression must be either 0 or NULL. If the set
72588    ** contains no NULL values, then the result is 0. If the set
72589    ** contains one or more NULL values, then the result of the
72590    ** expression is also NULL.
72591    */
72592    if( rRhsHasNull==0 || destIfFalse==destIfNull ){
72593      /* This branch runs if it is known at compile time that the RHS
72594      ** cannot contain NULL values. This happens as the result
72595      ** of a "NOT NULL" constraint in the database schema.
72596      **
72597      ** Also run this branch if NULL is equivalent to FALSE
72598      ** for this particular IN operator.
72599      */
72600      sqlite3VdbeAddOp4Int(v, OP_NotFound, pExpr->iTable, destIfFalse, r1, 1);
72601
72602    }else{
72603      /* In this branch, the RHS of the IN might contain a NULL and
72604      ** the presence of a NULL on the RHS makes a difference in the
72605      ** outcome.
72606      */
72607      int j1, j2, j3;
72608
72609      /* First check to see if the LHS is contained in the RHS.  If so,
72610      ** then the presence of NULLs in the RHS does not matter, so jump
72611      ** over all of the code that follows.
72612      */
72613      j1 = sqlite3VdbeAddOp4Int(v, OP_Found, pExpr->iTable, 0, r1, 1);
72614
72615      /* Here we begin generating code that runs if the LHS is not
72616      ** contained within the RHS.  Generate additional code that
72617      ** tests the RHS for NULLs.  If the RHS contains a NULL then
72618      ** jump to destIfNull.  If there are no NULLs in the RHS then
72619      ** jump to destIfFalse.
72620      */
72621      j2 = sqlite3VdbeAddOp1(v, OP_NotNull, rRhsHasNull);
72622      j3 = sqlite3VdbeAddOp4Int(v, OP_Found, pExpr->iTable, 0, rRhsHasNull, 1);
72623      sqlite3VdbeAddOp2(v, OP_Integer, -1, rRhsHasNull);
72624      sqlite3VdbeJumpHere(v, j3);
72625      sqlite3VdbeAddOp2(v, OP_AddImm, rRhsHasNull, 1);
72626      sqlite3VdbeJumpHere(v, j2);
72627
72628      /* Jump to the appropriate target depending on whether or not
72629      ** the RHS contains a NULL
72630      */
72631      sqlite3VdbeAddOp2(v, OP_If, rRhsHasNull, destIfNull);
72632      sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfFalse);
72633
72634      /* The OP_Found at the top of this branch jumps here when true,
72635      ** causing the overall IN expression evaluation to fall through.
72636      */
72637      sqlite3VdbeJumpHere(v, j1);
72638    }
72639  }
72640  sqlite3ReleaseTempReg(pParse, r1);
72641  sqlite3ExprCachePop(pParse, 1);
72642  VdbeComment((v, "end IN expr"));
72643}
72644#endif /* SQLITE_OMIT_SUBQUERY */
72645
72646/*
72647** Duplicate an 8-byte value
72648*/
72649static char *dup8bytes(Vdbe *v, const char *in){
72650  char *out = sqlite3DbMallocRaw(sqlite3VdbeDb(v), 8);
72651  if( out ){
72652    memcpy(out, in, 8);
72653  }
72654  return out;
72655}
72656
72657#ifndef SQLITE_OMIT_FLOATING_POINT
72658/*
72659** Generate an instruction that will put the floating point
72660** value described by z[0..n-1] into register iMem.
72661**
72662** The z[] string will probably not be zero-terminated.  But the
72663** z[n] character is guaranteed to be something that does not look
72664** like the continuation of the number.
72665*/
72666static void codeReal(Vdbe *v, const char *z, int negateFlag, int iMem){
72667  if( ALWAYS(z!=0) ){
72668    double value;
72669    char *zV;
72670    sqlite3AtoF(z, &value, sqlite3Strlen30(z), SQLITE_UTF8);
72671    assert( !sqlite3IsNaN(value) ); /* The new AtoF never returns NaN */
72672    if( negateFlag ) value = -value;
72673    zV = dup8bytes(v, (char*)&value);
72674    sqlite3VdbeAddOp4(v, OP_Real, 0, iMem, 0, zV, P4_REAL);
72675  }
72676}
72677#endif
72678
72679
72680/*
72681** Generate an instruction that will put the integer describe by
72682** text z[0..n-1] into register iMem.
72683**
72684** Expr.u.zToken is always UTF8 and zero-terminated.
72685*/
72686static void codeInteger(Parse *pParse, Expr *pExpr, int negFlag, int iMem){
72687  Vdbe *v = pParse->pVdbe;
72688  if( pExpr->flags & EP_IntValue ){
72689    int i = pExpr->u.iValue;
72690    assert( i>=0 );
72691    if( negFlag ) i = -i;
72692    sqlite3VdbeAddOp2(v, OP_Integer, i, iMem);
72693  }else{
72694    int c;
72695    i64 value;
72696    const char *z = pExpr->u.zToken;
72697    assert( z!=0 );
72698    c = sqlite3Atoi64(z, &value, sqlite3Strlen30(z), SQLITE_UTF8);
72699    if( c==0 || (c==2 && negFlag) ){
72700      char *zV;
72701      if( negFlag ){ value = c==2 ? SMALLEST_INT64 : -value; }
72702      zV = dup8bytes(v, (char*)&value);
72703      sqlite3VdbeAddOp4(v, OP_Int64, 0, iMem, 0, zV, P4_INT64);
72704    }else{
72705#ifdef SQLITE_OMIT_FLOATING_POINT
72706      sqlite3ErrorMsg(pParse, "oversized integer: %s%s", negFlag ? "-" : "", z);
72707#else
72708      codeReal(v, z, negFlag, iMem);
72709#endif
72710    }
72711  }
72712}
72713
72714/*
72715** Clear a cache entry.
72716*/
72717static void cacheEntryClear(Parse *pParse, struct yColCache *p){
72718  if( p->tempReg ){
72719    if( pParse->nTempReg<ArraySize(pParse->aTempReg) ){
72720      pParse->aTempReg[pParse->nTempReg++] = p->iReg;
72721    }
72722    p->tempReg = 0;
72723  }
72724}
72725
72726
72727/*
72728** Record in the column cache that a particular column from a
72729** particular table is stored in a particular register.
72730*/
72731SQLITE_PRIVATE void sqlite3ExprCacheStore(Parse *pParse, int iTab, int iCol, int iReg){
72732  int i;
72733  int minLru;
72734  int idxLru;
72735  struct yColCache *p;
72736
72737  assert( iReg>0 );  /* Register numbers are always positive */
72738  assert( iCol>=-1 && iCol<32768 );  /* Finite column numbers */
72739
72740  /* The SQLITE_ColumnCache flag disables the column cache.  This is used
72741  ** for testing only - to verify that SQLite always gets the same answer
72742  ** with and without the column cache.
72743  */
72744  if( pParse->db->flags & SQLITE_ColumnCache ) return;
72745
72746  /* First replace any existing entry.
72747  **
72748  ** Actually, the way the column cache is currently used, we are guaranteed
72749  ** that the object will never already be in cache.  Verify this guarantee.
72750  */
72751#ifndef NDEBUG
72752  for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
72753#if 0 /* This code wold remove the entry from the cache if it existed */
72754    if( p->iReg && p->iTable==iTab && p->iColumn==iCol ){
72755      cacheEntryClear(pParse, p);
72756      p->iLevel = pParse->iCacheLevel;
72757      p->iReg = iReg;
72758      p->lru = pParse->iCacheCnt++;
72759      return;
72760    }
72761#endif
72762    assert( p->iReg==0 || p->iTable!=iTab || p->iColumn!=iCol );
72763  }
72764#endif
72765
72766  /* Find an empty slot and replace it */
72767  for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
72768    if( p->iReg==0 ){
72769      p->iLevel = pParse->iCacheLevel;
72770      p->iTable = iTab;
72771      p->iColumn = iCol;
72772      p->iReg = iReg;
72773      p->tempReg = 0;
72774      p->lru = pParse->iCacheCnt++;
72775      return;
72776    }
72777  }
72778
72779  /* Replace the last recently used */
72780  minLru = 0x7fffffff;
72781  idxLru = -1;
72782  for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
72783    if( p->lru<minLru ){
72784      idxLru = i;
72785      minLru = p->lru;
72786    }
72787  }
72788  if( ALWAYS(idxLru>=0) ){
72789    p = &pParse->aColCache[idxLru];
72790    p->iLevel = pParse->iCacheLevel;
72791    p->iTable = iTab;
72792    p->iColumn = iCol;
72793    p->iReg = iReg;
72794    p->tempReg = 0;
72795    p->lru = pParse->iCacheCnt++;
72796    return;
72797  }
72798}
72799
72800/*
72801** Indicate that registers between iReg..iReg+nReg-1 are being overwritten.
72802** Purge the range of registers from the column cache.
72803*/
72804SQLITE_PRIVATE void sqlite3ExprCacheRemove(Parse *pParse, int iReg, int nReg){
72805  int i;
72806  int iLast = iReg + nReg - 1;
72807  struct yColCache *p;
72808  for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
72809    int r = p->iReg;
72810    if( r>=iReg && r<=iLast ){
72811      cacheEntryClear(pParse, p);
72812      p->iReg = 0;
72813    }
72814  }
72815}
72816
72817/*
72818** Remember the current column cache context.  Any new entries added
72819** added to the column cache after this call are removed when the
72820** corresponding pop occurs.
72821*/
72822SQLITE_PRIVATE void sqlite3ExprCachePush(Parse *pParse){
72823  pParse->iCacheLevel++;
72824}
72825
72826/*
72827** Remove from the column cache any entries that were added since the
72828** the previous N Push operations.  In other words, restore the cache
72829** to the state it was in N Pushes ago.
72830*/
72831SQLITE_PRIVATE void sqlite3ExprCachePop(Parse *pParse, int N){
72832  int i;
72833  struct yColCache *p;
72834  assert( N>0 );
72835  assert( pParse->iCacheLevel>=N );
72836  pParse->iCacheLevel -= N;
72837  for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
72838    if( p->iReg && p->iLevel>pParse->iCacheLevel ){
72839      cacheEntryClear(pParse, p);
72840      p->iReg = 0;
72841    }
72842  }
72843}
72844
72845/*
72846** When a cached column is reused, make sure that its register is
72847** no longer available as a temp register.  ticket #3879:  that same
72848** register might be in the cache in multiple places, so be sure to
72849** get them all.
72850*/
72851static void sqlite3ExprCachePinRegister(Parse *pParse, int iReg){
72852  int i;
72853  struct yColCache *p;
72854  for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
72855    if( p->iReg==iReg ){
72856      p->tempReg = 0;
72857    }
72858  }
72859}
72860
72861/*
72862** Generate code to extract the value of the iCol-th column of a table.
72863*/
72864SQLITE_PRIVATE void sqlite3ExprCodeGetColumnOfTable(
72865  Vdbe *v,        /* The VDBE under construction */
72866  Table *pTab,    /* The table containing the value */
72867  int iTabCur,    /* The cursor for this table */
72868  int iCol,       /* Index of the column to extract */
72869  int regOut      /* Extract the valud into this register */
72870){
72871  if( iCol<0 || iCol==pTab->iPKey ){
72872    sqlite3VdbeAddOp2(v, OP_Rowid, iTabCur, regOut);
72873  }else{
72874    int op = IsVirtual(pTab) ? OP_VColumn : OP_Column;
72875    sqlite3VdbeAddOp3(v, op, iTabCur, iCol, regOut);
72876  }
72877  if( iCol>=0 ){
72878    sqlite3ColumnDefault(v, pTab, iCol, regOut);
72879  }
72880}
72881
72882/*
72883** Generate code that will extract the iColumn-th column from
72884** table pTab and store the column value in a register.  An effort
72885** is made to store the column value in register iReg, but this is
72886** not guaranteed.  The location of the column value is returned.
72887**
72888** There must be an open cursor to pTab in iTable when this routine
72889** is called.  If iColumn<0 then code is generated that extracts the rowid.
72890*/
72891SQLITE_PRIVATE int sqlite3ExprCodeGetColumn(
72892  Parse *pParse,   /* Parsing and code generating context */
72893  Table *pTab,     /* Description of the table we are reading from */
72894  int iColumn,     /* Index of the table column */
72895  int iTable,      /* The cursor pointing to the table */
72896  int iReg         /* Store results here */
72897){
72898  Vdbe *v = pParse->pVdbe;
72899  int i;
72900  struct yColCache *p;
72901
72902  for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
72903    if( p->iReg>0 && p->iTable==iTable && p->iColumn==iColumn ){
72904      p->lru = pParse->iCacheCnt++;
72905      sqlite3ExprCachePinRegister(pParse, p->iReg);
72906      return p->iReg;
72907    }
72908  }
72909  assert( v!=0 );
72910  sqlite3ExprCodeGetColumnOfTable(v, pTab, iTable, iColumn, iReg);
72911  sqlite3ExprCacheStore(pParse, iTable, iColumn, iReg);
72912  return iReg;
72913}
72914
72915/*
72916** Clear all column cache entries.
72917*/
72918SQLITE_PRIVATE void sqlite3ExprCacheClear(Parse *pParse){
72919  int i;
72920  struct yColCache *p;
72921
72922  for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
72923    if( p->iReg ){
72924      cacheEntryClear(pParse, p);
72925      p->iReg = 0;
72926    }
72927  }
72928}
72929
72930/*
72931** Record the fact that an affinity change has occurred on iCount
72932** registers starting with iStart.
72933*/
72934SQLITE_PRIVATE void sqlite3ExprCacheAffinityChange(Parse *pParse, int iStart, int iCount){
72935  sqlite3ExprCacheRemove(pParse, iStart, iCount);
72936}
72937
72938/*
72939** Generate code to move content from registers iFrom...iFrom+nReg-1
72940** over to iTo..iTo+nReg-1. Keep the column cache up-to-date.
72941*/
72942SQLITE_PRIVATE void sqlite3ExprCodeMove(Parse *pParse, int iFrom, int iTo, int nReg){
72943  int i;
72944  struct yColCache *p;
72945  if( NEVER(iFrom==iTo) ) return;
72946  sqlite3VdbeAddOp3(pParse->pVdbe, OP_Move, iFrom, iTo, nReg);
72947  for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
72948    int x = p->iReg;
72949    if( x>=iFrom && x<iFrom+nReg ){
72950      p->iReg += iTo-iFrom;
72951    }
72952  }
72953}
72954
72955/*
72956** Generate code to copy content from registers iFrom...iFrom+nReg-1
72957** over to iTo..iTo+nReg-1.
72958*/
72959SQLITE_PRIVATE void sqlite3ExprCodeCopy(Parse *pParse, int iFrom, int iTo, int nReg){
72960  int i;
72961  if( NEVER(iFrom==iTo) ) return;
72962  for(i=0; i<nReg; i++){
72963    sqlite3VdbeAddOp2(pParse->pVdbe, OP_Copy, iFrom+i, iTo+i);
72964  }
72965}
72966
72967#if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
72968/*
72969** Return true if any register in the range iFrom..iTo (inclusive)
72970** is used as part of the column cache.
72971**
72972** This routine is used within assert() and testcase() macros only
72973** and does not appear in a normal build.
72974*/
72975static int usedAsColumnCache(Parse *pParse, int iFrom, int iTo){
72976  int i;
72977  struct yColCache *p;
72978  for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
72979    int r = p->iReg;
72980    if( r>=iFrom && r<=iTo ) return 1;    /*NO_TEST*/
72981  }
72982  return 0;
72983}
72984#endif /* SQLITE_DEBUG || SQLITE_COVERAGE_TEST */
72985
72986/*
72987** Generate code into the current Vdbe to evaluate the given
72988** expression.  Attempt to store the results in register "target".
72989** Return the register where results are stored.
72990**
72991** With this routine, there is no guarantee that results will
72992** be stored in target.  The result might be stored in some other
72993** register if it is convenient to do so.  The calling function
72994** must check the return code and move the results to the desired
72995** register.
72996*/
72997SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse *pParse, Expr *pExpr, int target){
72998  Vdbe *v = pParse->pVdbe;  /* The VM under construction */
72999  int op;                   /* The opcode being coded */
73000  int inReg = target;       /* Results stored in register inReg */
73001  int regFree1 = 0;         /* If non-zero free this temporary register */
73002  int regFree2 = 0;         /* If non-zero free this temporary register */
73003  int r1, r2, r3, r4;       /* Various register numbers */
73004  sqlite3 *db = pParse->db; /* The database connection */
73005
73006  assert( target>0 && target<=pParse->nMem );
73007  if( v==0 ){
73008    assert( pParse->db->mallocFailed );
73009    return 0;
73010  }
73011
73012  if( pExpr==0 ){
73013    op = TK_NULL;
73014  }else{
73015    op = pExpr->op;
73016  }
73017  switch( op ){
73018    case TK_AGG_COLUMN: {
73019      AggInfo *pAggInfo = pExpr->pAggInfo;
73020      struct AggInfo_col *pCol = &pAggInfo->aCol[pExpr->iAgg];
73021      if( !pAggInfo->directMode ){
73022        assert( pCol->iMem>0 );
73023        inReg = pCol->iMem;
73024        break;
73025      }else if( pAggInfo->useSortingIdx ){
73026        sqlite3VdbeAddOp3(v, OP_Column, pAggInfo->sortingIdx,
73027                              pCol->iSorterColumn, target);
73028        break;
73029      }
73030      /* Otherwise, fall thru into the TK_COLUMN case */
73031    }
73032    case TK_COLUMN: {
73033      if( pExpr->iTable<0 ){
73034        /* This only happens when coding check constraints */
73035        assert( pParse->ckBase>0 );
73036        inReg = pExpr->iColumn + pParse->ckBase;
73037      }else{
73038        inReg = sqlite3ExprCodeGetColumn(pParse, pExpr->pTab,
73039                                 pExpr->iColumn, pExpr->iTable, target);
73040      }
73041      break;
73042    }
73043    case TK_INTEGER: {
73044      codeInteger(pParse, pExpr, 0, target);
73045      break;
73046    }
73047#ifndef SQLITE_OMIT_FLOATING_POINT
73048    case TK_FLOAT: {
73049      assert( !ExprHasProperty(pExpr, EP_IntValue) );
73050      codeReal(v, pExpr->u.zToken, 0, target);
73051      break;
73052    }
73053#endif
73054    case TK_STRING: {
73055      assert( !ExprHasProperty(pExpr, EP_IntValue) );
73056      sqlite3VdbeAddOp4(v, OP_String8, 0, target, 0, pExpr->u.zToken, 0);
73057      break;
73058    }
73059    case TK_NULL: {
73060      sqlite3VdbeAddOp2(v, OP_Null, 0, target);
73061      break;
73062    }
73063#ifndef SQLITE_OMIT_BLOB_LITERAL
73064    case TK_BLOB: {
73065      int n;
73066      const char *z;
73067      char *zBlob;
73068      assert( !ExprHasProperty(pExpr, EP_IntValue) );
73069      assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );
73070      assert( pExpr->u.zToken[1]=='\'' );
73071      z = &pExpr->u.zToken[2];
73072      n = sqlite3Strlen30(z) - 1;
73073      assert( z[n]=='\'' );
73074      zBlob = sqlite3HexToBlob(sqlite3VdbeDb(v), z, n);
73075      sqlite3VdbeAddOp4(v, OP_Blob, n/2, target, 0, zBlob, P4_DYNAMIC);
73076      break;
73077    }
73078#endif
73079    case TK_VARIABLE: {
73080      assert( !ExprHasProperty(pExpr, EP_IntValue) );
73081      assert( pExpr->u.zToken!=0 );
73082      assert( pExpr->u.zToken[0]!=0 );
73083      sqlite3VdbeAddOp2(v, OP_Variable, pExpr->iColumn, target);
73084      if( pExpr->u.zToken[1]!=0 ){
73085        sqlite3VdbeChangeP4(v, -1, pExpr->u.zToken, P4_TRANSIENT);
73086      }
73087      break;
73088    }
73089    case TK_REGISTER: {
73090      inReg = pExpr->iTable;
73091      break;
73092    }
73093    case TK_AS: {
73094      inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
73095      break;
73096    }
73097#ifndef SQLITE_OMIT_CAST
73098    case TK_CAST: {
73099      /* Expressions of the form:   CAST(pLeft AS token) */
73100      int aff, to_op;
73101      inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
73102      assert( !ExprHasProperty(pExpr, EP_IntValue) );
73103      aff = sqlite3AffinityType(pExpr->u.zToken);
73104      to_op = aff - SQLITE_AFF_TEXT + OP_ToText;
73105      assert( to_op==OP_ToText    || aff!=SQLITE_AFF_TEXT    );
73106      assert( to_op==OP_ToBlob    || aff!=SQLITE_AFF_NONE    );
73107      assert( to_op==OP_ToNumeric || aff!=SQLITE_AFF_NUMERIC );
73108      assert( to_op==OP_ToInt     || aff!=SQLITE_AFF_INTEGER );
73109      assert( to_op==OP_ToReal    || aff!=SQLITE_AFF_REAL    );
73110      testcase( to_op==OP_ToText );
73111      testcase( to_op==OP_ToBlob );
73112      testcase( to_op==OP_ToNumeric );
73113      testcase( to_op==OP_ToInt );
73114      testcase( to_op==OP_ToReal );
73115      if( inReg!=target ){
73116        sqlite3VdbeAddOp2(v, OP_SCopy, inReg, target);
73117        inReg = target;
73118      }
73119      sqlite3VdbeAddOp1(v, to_op, inReg);
73120      testcase( usedAsColumnCache(pParse, inReg, inReg) );
73121      sqlite3ExprCacheAffinityChange(pParse, inReg, 1);
73122      break;
73123    }
73124#endif /* SQLITE_OMIT_CAST */
73125    case TK_LT:
73126    case TK_LE:
73127    case TK_GT:
73128    case TK_GE:
73129    case TK_NE:
73130    case TK_EQ: {
73131      assert( TK_LT==OP_Lt );
73132      assert( TK_LE==OP_Le );
73133      assert( TK_GT==OP_Gt );
73134      assert( TK_GE==OP_Ge );
73135      assert( TK_EQ==OP_Eq );
73136      assert( TK_NE==OP_Ne );
73137      testcase( op==TK_LT );
73138      testcase( op==TK_LE );
73139      testcase( op==TK_GT );
73140      testcase( op==TK_GE );
73141      testcase( op==TK_EQ );
73142      testcase( op==TK_NE );
73143      r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
73144      r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
73145      codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
73146                  r1, r2, inReg, SQLITE_STOREP2);
73147      testcase( regFree1==0 );
73148      testcase( regFree2==0 );
73149      break;
73150    }
73151    case TK_IS:
73152    case TK_ISNOT: {
73153      testcase( op==TK_IS );
73154      testcase( op==TK_ISNOT );
73155      r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
73156      r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
73157      op = (op==TK_IS) ? TK_EQ : TK_NE;
73158      codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
73159                  r1, r2, inReg, SQLITE_STOREP2 | SQLITE_NULLEQ);
73160      testcase( regFree1==0 );
73161      testcase( regFree2==0 );
73162      break;
73163    }
73164    case TK_AND:
73165    case TK_OR:
73166    case TK_PLUS:
73167    case TK_STAR:
73168    case TK_MINUS:
73169    case TK_REM:
73170    case TK_BITAND:
73171    case TK_BITOR:
73172    case TK_SLASH:
73173    case TK_LSHIFT:
73174    case TK_RSHIFT:
73175    case TK_CONCAT: {
73176      assert( TK_AND==OP_And );
73177      assert( TK_OR==OP_Or );
73178      assert( TK_PLUS==OP_Add );
73179      assert( TK_MINUS==OP_Subtract );
73180      assert( TK_REM==OP_Remainder );
73181      assert( TK_BITAND==OP_BitAnd );
73182      assert( TK_BITOR==OP_BitOr );
73183      assert( TK_SLASH==OP_Divide );
73184      assert( TK_LSHIFT==OP_ShiftLeft );
73185      assert( TK_RSHIFT==OP_ShiftRight );
73186      assert( TK_CONCAT==OP_Concat );
73187      testcase( op==TK_AND );
73188      testcase( op==TK_OR );
73189      testcase( op==TK_PLUS );
73190      testcase( op==TK_MINUS );
73191      testcase( op==TK_REM );
73192      testcase( op==TK_BITAND );
73193      testcase( op==TK_BITOR );
73194      testcase( op==TK_SLASH );
73195      testcase( op==TK_LSHIFT );
73196      testcase( op==TK_RSHIFT );
73197      testcase( op==TK_CONCAT );
73198      r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
73199      r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
73200      sqlite3VdbeAddOp3(v, op, r2, r1, target);
73201      testcase( regFree1==0 );
73202      testcase( regFree2==0 );
73203      break;
73204    }
73205    case TK_UMINUS: {
73206      Expr *pLeft = pExpr->pLeft;
73207      assert( pLeft );
73208      if( pLeft->op==TK_INTEGER ){
73209        codeInteger(pParse, pLeft, 1, target);
73210#ifndef SQLITE_OMIT_FLOATING_POINT
73211      }else if( pLeft->op==TK_FLOAT ){
73212        assert( !ExprHasProperty(pExpr, EP_IntValue) );
73213        codeReal(v, pLeft->u.zToken, 1, target);
73214#endif
73215      }else{
73216        regFree1 = r1 = sqlite3GetTempReg(pParse);
73217        sqlite3VdbeAddOp2(v, OP_Integer, 0, r1);
73218        r2 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree2);
73219        sqlite3VdbeAddOp3(v, OP_Subtract, r2, r1, target);
73220        testcase( regFree2==0 );
73221      }
73222      inReg = target;
73223      break;
73224    }
73225    case TK_BITNOT:
73226    case TK_NOT: {
73227      assert( TK_BITNOT==OP_BitNot );
73228      assert( TK_NOT==OP_Not );
73229      testcase( op==TK_BITNOT );
73230      testcase( op==TK_NOT );
73231      r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
73232      testcase( regFree1==0 );
73233      inReg = target;
73234      sqlite3VdbeAddOp2(v, op, r1, inReg);
73235      break;
73236    }
73237    case TK_ISNULL:
73238    case TK_NOTNULL: {
73239      int addr;
73240      assert( TK_ISNULL==OP_IsNull );
73241      assert( TK_NOTNULL==OP_NotNull );
73242      testcase( op==TK_ISNULL );
73243      testcase( op==TK_NOTNULL );
73244      sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
73245      r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
73246      testcase( regFree1==0 );
73247      addr = sqlite3VdbeAddOp1(v, op, r1);
73248      sqlite3VdbeAddOp2(v, OP_AddImm, target, -1);
73249      sqlite3VdbeJumpHere(v, addr);
73250      break;
73251    }
73252    case TK_AGG_FUNCTION: {
73253      AggInfo *pInfo = pExpr->pAggInfo;
73254      if( pInfo==0 ){
73255        assert( !ExprHasProperty(pExpr, EP_IntValue) );
73256        sqlite3ErrorMsg(pParse, "misuse of aggregate: %s()", pExpr->u.zToken);
73257      }else{
73258        inReg = pInfo->aFunc[pExpr->iAgg].iMem;
73259      }
73260      break;
73261    }
73262    case TK_CONST_FUNC:
73263    case TK_FUNCTION: {
73264      ExprList *pFarg;       /* List of function arguments */
73265      int nFarg;             /* Number of function arguments */
73266      FuncDef *pDef;         /* The function definition object */
73267      int nId;               /* Length of the function name in bytes */
73268      const char *zId;       /* The function name */
73269      int constMask = 0;     /* Mask of function arguments that are constant */
73270      int i;                 /* Loop counter */
73271      u8 enc = ENC(db);      /* The text encoding used by this database */
73272      CollSeq *pColl = 0;    /* A collating sequence */
73273
73274      assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
73275      testcase( op==TK_CONST_FUNC );
73276      testcase( op==TK_FUNCTION );
73277      if( ExprHasAnyProperty(pExpr, EP_TokenOnly) ){
73278        pFarg = 0;
73279      }else{
73280        pFarg = pExpr->x.pList;
73281      }
73282      nFarg = pFarg ? pFarg->nExpr : 0;
73283      assert( !ExprHasProperty(pExpr, EP_IntValue) );
73284      zId = pExpr->u.zToken;
73285      nId = sqlite3Strlen30(zId);
73286      pDef = sqlite3FindFunction(db, zId, nId, nFarg, enc, 0);
73287      if( pDef==0 ){
73288        sqlite3ErrorMsg(pParse, "unknown function: %.*s()", nId, zId);
73289        break;
73290      }
73291
73292      /* Attempt a direct implementation of the built-in COALESCE() and
73293      ** IFNULL() functions.  This avoids unnecessary evalation of
73294      ** arguments past the first non-NULL argument.
73295      */
73296      if( pDef->flags & SQLITE_FUNC_COALESCE ){
73297        int endCoalesce = sqlite3VdbeMakeLabel(v);
73298        assert( nFarg>=2 );
73299        sqlite3ExprCode(pParse, pFarg->a[0].pExpr, target);
73300        for(i=1; i<nFarg; i++){
73301          sqlite3VdbeAddOp2(v, OP_NotNull, target, endCoalesce);
73302          sqlite3ExprCacheRemove(pParse, target, 1);
73303          sqlite3ExprCachePush(pParse);
73304          sqlite3ExprCode(pParse, pFarg->a[i].pExpr, target);
73305          sqlite3ExprCachePop(pParse, 1);
73306        }
73307        sqlite3VdbeResolveLabel(v, endCoalesce);
73308        break;
73309      }
73310
73311
73312      if( pFarg ){
73313        r1 = sqlite3GetTempRange(pParse, nFarg);
73314        sqlite3ExprCachePush(pParse);     /* Ticket 2ea2425d34be */
73315        sqlite3ExprCodeExprList(pParse, pFarg, r1, 1);
73316        sqlite3ExprCachePop(pParse, 1);   /* Ticket 2ea2425d34be */
73317      }else{
73318        r1 = 0;
73319      }
73320#ifndef SQLITE_OMIT_VIRTUALTABLE
73321      /* Possibly overload the function if the first argument is
73322      ** a virtual table column.
73323      **
73324      ** For infix functions (LIKE, GLOB, REGEXP, and MATCH) use the
73325      ** second argument, not the first, as the argument to test to
73326      ** see if it is a column in a virtual table.  This is done because
73327      ** the left operand of infix functions (the operand we want to
73328      ** control overloading) ends up as the second argument to the
73329      ** function.  The expression "A glob B" is equivalent to
73330      ** "glob(B,A).  We want to use the A in "A glob B" to test
73331      ** for function overloading.  But we use the B term in "glob(B,A)".
73332      */
73333      if( nFarg>=2 && (pExpr->flags & EP_InfixFunc) ){
73334        pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[1].pExpr);
73335      }else if( nFarg>0 ){
73336        pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[0].pExpr);
73337      }
73338#endif
73339      for(i=0; i<nFarg; i++){
73340        if( i<32 && sqlite3ExprIsConstant(pFarg->a[i].pExpr) ){
73341          constMask |= (1<<i);
73342        }
73343        if( (pDef->flags & SQLITE_FUNC_NEEDCOLL)!=0 && !pColl ){
73344          pColl = sqlite3ExprCollSeq(pParse, pFarg->a[i].pExpr);
73345        }
73346      }
73347      if( pDef->flags & SQLITE_FUNC_NEEDCOLL ){
73348        if( !pColl ) pColl = db->pDfltColl;
73349        sqlite3VdbeAddOp4(v, OP_CollSeq, 0, 0, 0, (char *)pColl, P4_COLLSEQ);
73350      }
73351      sqlite3VdbeAddOp4(v, OP_Function, constMask, r1, target,
73352                        (char*)pDef, P4_FUNCDEF);
73353      sqlite3VdbeChangeP5(v, (u8)nFarg);
73354      if( nFarg ){
73355        sqlite3ReleaseTempRange(pParse, r1, nFarg);
73356      }
73357      break;
73358    }
73359#ifndef SQLITE_OMIT_SUBQUERY
73360    case TK_EXISTS:
73361    case TK_SELECT: {
73362      testcase( op==TK_EXISTS );
73363      testcase( op==TK_SELECT );
73364      inReg = sqlite3CodeSubselect(pParse, pExpr, 0, 0);
73365      break;
73366    }
73367    case TK_IN: {
73368      int destIfFalse = sqlite3VdbeMakeLabel(v);
73369      int destIfNull = sqlite3VdbeMakeLabel(v);
73370      sqlite3VdbeAddOp2(v, OP_Null, 0, target);
73371      sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
73372      sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
73373      sqlite3VdbeResolveLabel(v, destIfFalse);
73374      sqlite3VdbeAddOp2(v, OP_AddImm, target, 0);
73375      sqlite3VdbeResolveLabel(v, destIfNull);
73376      break;
73377    }
73378#endif /* SQLITE_OMIT_SUBQUERY */
73379
73380
73381    /*
73382    **    x BETWEEN y AND z
73383    **
73384    ** This is equivalent to
73385    **
73386    **    x>=y AND x<=z
73387    **
73388    ** X is stored in pExpr->pLeft.
73389    ** Y is stored in pExpr->pList->a[0].pExpr.
73390    ** Z is stored in pExpr->pList->a[1].pExpr.
73391    */
73392    case TK_BETWEEN: {
73393      Expr *pLeft = pExpr->pLeft;
73394      struct ExprList_item *pLItem = pExpr->x.pList->a;
73395      Expr *pRight = pLItem->pExpr;
73396
73397      r1 = sqlite3ExprCodeTemp(pParse, pLeft, &regFree1);
73398      r2 = sqlite3ExprCodeTemp(pParse, pRight, &regFree2);
73399      testcase( regFree1==0 );
73400      testcase( regFree2==0 );
73401      r3 = sqlite3GetTempReg(pParse);
73402      r4 = sqlite3GetTempReg(pParse);
73403      codeCompare(pParse, pLeft, pRight, OP_Ge,
73404                  r1, r2, r3, SQLITE_STOREP2);
73405      pLItem++;
73406      pRight = pLItem->pExpr;
73407      sqlite3ReleaseTempReg(pParse, regFree2);
73408      r2 = sqlite3ExprCodeTemp(pParse, pRight, &regFree2);
73409      testcase( regFree2==0 );
73410      codeCompare(pParse, pLeft, pRight, OP_Le, r1, r2, r4, SQLITE_STOREP2);
73411      sqlite3VdbeAddOp3(v, OP_And, r3, r4, target);
73412      sqlite3ReleaseTempReg(pParse, r3);
73413      sqlite3ReleaseTempReg(pParse, r4);
73414      break;
73415    }
73416    case TK_UPLUS: {
73417      inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
73418      break;
73419    }
73420
73421    case TK_TRIGGER: {
73422      /* If the opcode is TK_TRIGGER, then the expression is a reference
73423      ** to a column in the new.* or old.* pseudo-tables available to
73424      ** trigger programs. In this case Expr.iTable is set to 1 for the
73425      ** new.* pseudo-table, or 0 for the old.* pseudo-table. Expr.iColumn
73426      ** is set to the column of the pseudo-table to read, or to -1 to
73427      ** read the rowid field.
73428      **
73429      ** The expression is implemented using an OP_Param opcode. The p1
73430      ** parameter is set to 0 for an old.rowid reference, or to (i+1)
73431      ** to reference another column of the old.* pseudo-table, where
73432      ** i is the index of the column. For a new.rowid reference, p1 is
73433      ** set to (n+1), where n is the number of columns in each pseudo-table.
73434      ** For a reference to any other column in the new.* pseudo-table, p1
73435      ** is set to (n+2+i), where n and i are as defined previously. For
73436      ** example, if the table on which triggers are being fired is
73437      ** declared as:
73438      **
73439      **   CREATE TABLE t1(a, b);
73440      **
73441      ** Then p1 is interpreted as follows:
73442      **
73443      **   p1==0   ->    old.rowid     p1==3   ->    new.rowid
73444      **   p1==1   ->    old.a         p1==4   ->    new.a
73445      **   p1==2   ->    old.b         p1==5   ->    new.b
73446      */
73447      Table *pTab = pExpr->pTab;
73448      int p1 = pExpr->iTable * (pTab->nCol+1) + 1 + pExpr->iColumn;
73449
73450      assert( pExpr->iTable==0 || pExpr->iTable==1 );
73451      assert( pExpr->iColumn>=-1 && pExpr->iColumn<pTab->nCol );
73452      assert( pTab->iPKey<0 || pExpr->iColumn!=pTab->iPKey );
73453      assert( p1>=0 && p1<(pTab->nCol*2+2) );
73454
73455      sqlite3VdbeAddOp2(v, OP_Param, p1, target);
73456      VdbeComment((v, "%s.%s -> $%d",
73457        (pExpr->iTable ? "new" : "old"),
73458        (pExpr->iColumn<0 ? "rowid" : pExpr->pTab->aCol[pExpr->iColumn].zName),
73459        target
73460      ));
73461
73462#ifndef SQLITE_OMIT_FLOATING_POINT
73463      /* If the column has REAL affinity, it may currently be stored as an
73464      ** integer. Use OP_RealAffinity to make sure it is really real.  */
73465      if( pExpr->iColumn>=0
73466       && pTab->aCol[pExpr->iColumn].affinity==SQLITE_AFF_REAL
73467      ){
73468        sqlite3VdbeAddOp1(v, OP_RealAffinity, target);
73469      }
73470#endif
73471      break;
73472    }
73473
73474
73475    /*
73476    ** Form A:
73477    **   CASE x WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
73478    **
73479    ** Form B:
73480    **   CASE WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
73481    **
73482    ** Form A is can be transformed into the equivalent form B as follows:
73483    **   CASE WHEN x=e1 THEN r1 WHEN x=e2 THEN r2 ...
73484    **        WHEN x=eN THEN rN ELSE y END
73485    **
73486    ** X (if it exists) is in pExpr->pLeft.
73487    ** Y is in pExpr->pRight.  The Y is also optional.  If there is no
73488    ** ELSE clause and no other term matches, then the result of the
73489    ** exprssion is NULL.
73490    ** Ei is in pExpr->pList->a[i*2] and Ri is pExpr->pList->a[i*2+1].
73491    **
73492    ** The result of the expression is the Ri for the first matching Ei,
73493    ** or if there is no matching Ei, the ELSE term Y, or if there is
73494    ** no ELSE term, NULL.
73495    */
73496    default: assert( op==TK_CASE ); {
73497      int endLabel;                     /* GOTO label for end of CASE stmt */
73498      int nextCase;                     /* GOTO label for next WHEN clause */
73499      int nExpr;                        /* 2x number of WHEN terms */
73500      int i;                            /* Loop counter */
73501      ExprList *pEList;                 /* List of WHEN terms */
73502      struct ExprList_item *aListelem;  /* Array of WHEN terms */
73503      Expr opCompare;                   /* The X==Ei expression */
73504      Expr cacheX;                      /* Cached expression X */
73505      Expr *pX;                         /* The X expression */
73506      Expr *pTest = 0;                  /* X==Ei (form A) or just Ei (form B) */
73507      VVA_ONLY( int iCacheLevel = pParse->iCacheLevel; )
73508
73509      assert( !ExprHasProperty(pExpr, EP_xIsSelect) && pExpr->x.pList );
73510      assert((pExpr->x.pList->nExpr % 2) == 0);
73511      assert(pExpr->x.pList->nExpr > 0);
73512      pEList = pExpr->x.pList;
73513      aListelem = pEList->a;
73514      nExpr = pEList->nExpr;
73515      endLabel = sqlite3VdbeMakeLabel(v);
73516      if( (pX = pExpr->pLeft)!=0 ){
73517        cacheX = *pX;
73518        testcase( pX->op==TK_COLUMN );
73519        testcase( pX->op==TK_REGISTER );
73520        cacheX.iTable = sqlite3ExprCodeTemp(pParse, pX, &regFree1);
73521        testcase( regFree1==0 );
73522        cacheX.op = TK_REGISTER;
73523        opCompare.op = TK_EQ;
73524        opCompare.pLeft = &cacheX;
73525        pTest = &opCompare;
73526        /* Ticket b351d95f9cd5ef17e9d9dbae18f5ca8611190001:
73527        ** The value in regFree1 might get SCopy-ed into the file result.
73528        ** So make sure that the regFree1 register is not reused for other
73529        ** purposes and possibly overwritten.  */
73530        regFree1 = 0;
73531      }
73532      for(i=0; i<nExpr; i=i+2){
73533        sqlite3ExprCachePush(pParse);
73534        if( pX ){
73535          assert( pTest!=0 );
73536          opCompare.pRight = aListelem[i].pExpr;
73537        }else{
73538          pTest = aListelem[i].pExpr;
73539        }
73540        nextCase = sqlite3VdbeMakeLabel(v);
73541        testcase( pTest->op==TK_COLUMN );
73542        sqlite3ExprIfFalse(pParse, pTest, nextCase, SQLITE_JUMPIFNULL);
73543        testcase( aListelem[i+1].pExpr->op==TK_COLUMN );
73544        testcase( aListelem[i+1].pExpr->op==TK_REGISTER );
73545        sqlite3ExprCode(pParse, aListelem[i+1].pExpr, target);
73546        sqlite3VdbeAddOp2(v, OP_Goto, 0, endLabel);
73547        sqlite3ExprCachePop(pParse, 1);
73548        sqlite3VdbeResolveLabel(v, nextCase);
73549      }
73550      if( pExpr->pRight ){
73551        sqlite3ExprCachePush(pParse);
73552        sqlite3ExprCode(pParse, pExpr->pRight, target);
73553        sqlite3ExprCachePop(pParse, 1);
73554      }else{
73555        sqlite3VdbeAddOp2(v, OP_Null, 0, target);
73556      }
73557      assert( db->mallocFailed || pParse->nErr>0
73558           || pParse->iCacheLevel==iCacheLevel );
73559      sqlite3VdbeResolveLabel(v, endLabel);
73560      break;
73561    }
73562#ifndef SQLITE_OMIT_TRIGGER
73563    case TK_RAISE: {
73564      assert( pExpr->affinity==OE_Rollback
73565           || pExpr->affinity==OE_Abort
73566           || pExpr->affinity==OE_Fail
73567           || pExpr->affinity==OE_Ignore
73568      );
73569      if( !pParse->pTriggerTab ){
73570        sqlite3ErrorMsg(pParse,
73571                       "RAISE() may only be used within a trigger-program");
73572        return 0;
73573      }
73574      if( pExpr->affinity==OE_Abort ){
73575        sqlite3MayAbort(pParse);
73576      }
73577      assert( !ExprHasProperty(pExpr, EP_IntValue) );
73578      if( pExpr->affinity==OE_Ignore ){
73579        sqlite3VdbeAddOp4(
73580            v, OP_Halt, SQLITE_OK, OE_Ignore, 0, pExpr->u.zToken,0);
73581      }else{
73582        sqlite3HaltConstraint(pParse, pExpr->affinity, pExpr->u.zToken, 0);
73583      }
73584
73585      break;
73586    }
73587#endif
73588  }
73589  sqlite3ReleaseTempReg(pParse, regFree1);
73590  sqlite3ReleaseTempReg(pParse, regFree2);
73591  return inReg;
73592}
73593
73594/*
73595** Generate code to evaluate an expression and store the results
73596** into a register.  Return the register number where the results
73597** are stored.
73598**
73599** If the register is a temporary register that can be deallocated,
73600** then write its number into *pReg.  If the result register is not
73601** a temporary, then set *pReg to zero.
73602*/
73603SQLITE_PRIVATE int sqlite3ExprCodeTemp(Parse *pParse, Expr *pExpr, int *pReg){
73604  int r1 = sqlite3GetTempReg(pParse);
73605  int r2 = sqlite3ExprCodeTarget(pParse, pExpr, r1);
73606  if( r2==r1 ){
73607    *pReg = r1;
73608  }else{
73609    sqlite3ReleaseTempReg(pParse, r1);
73610    *pReg = 0;
73611  }
73612  return r2;
73613}
73614
73615/*
73616** Generate code that will evaluate expression pExpr and store the
73617** results in register target.  The results are guaranteed to appear
73618** in register target.
73619*/
73620SQLITE_PRIVATE int sqlite3ExprCode(Parse *pParse, Expr *pExpr, int target){
73621  int inReg;
73622
73623  assert( target>0 && target<=pParse->nMem );
73624  if( pExpr && pExpr->op==TK_REGISTER ){
73625    sqlite3VdbeAddOp2(pParse->pVdbe, OP_Copy, pExpr->iTable, target);
73626  }else{
73627    inReg = sqlite3ExprCodeTarget(pParse, pExpr, target);
73628    assert( pParse->pVdbe || pParse->db->mallocFailed );
73629    if( inReg!=target && pParse->pVdbe ){
73630      sqlite3VdbeAddOp2(pParse->pVdbe, OP_SCopy, inReg, target);
73631    }
73632  }
73633  return target;
73634}
73635
73636/*
73637** Generate code that evalutes the given expression and puts the result
73638** in register target.
73639**
73640** Also make a copy of the expression results into another "cache" register
73641** and modify the expression so that the next time it is evaluated,
73642** the result is a copy of the cache register.
73643**
73644** This routine is used for expressions that are used multiple
73645** times.  They are evaluated once and the results of the expression
73646** are reused.
73647*/
73648SQLITE_PRIVATE int sqlite3ExprCodeAndCache(Parse *pParse, Expr *pExpr, int target){
73649  Vdbe *v = pParse->pVdbe;
73650  int inReg;
73651  inReg = sqlite3ExprCode(pParse, pExpr, target);
73652  assert( target>0 );
73653  /* This routine is called for terms to INSERT or UPDATE.  And the only
73654  ** other place where expressions can be converted into TK_REGISTER is
73655  ** in WHERE clause processing.  So as currently implemented, there is
73656  ** no way for a TK_REGISTER to exist here.  But it seems prudent to
73657  ** keep the ALWAYS() in case the conditions above change with future
73658  ** modifications or enhancements. */
73659  if( ALWAYS(pExpr->op!=TK_REGISTER) ){
73660    int iMem;
73661    iMem = ++pParse->nMem;
73662    sqlite3VdbeAddOp2(v, OP_Copy, inReg, iMem);
73663    pExpr->iTable = iMem;
73664    pExpr->op2 = pExpr->op;
73665    pExpr->op = TK_REGISTER;
73666  }
73667  return inReg;
73668}
73669
73670/*
73671** Return TRUE if pExpr is an constant expression that is appropriate
73672** for factoring out of a loop.  Appropriate expressions are:
73673**
73674**    *  Any expression that evaluates to two or more opcodes.
73675**
73676**    *  Any OP_Integer, OP_Real, OP_String, OP_Blob, OP_Null,
73677**       or OP_Variable that does not need to be placed in a
73678**       specific register.
73679**
73680** There is no point in factoring out single-instruction constant
73681** expressions that need to be placed in a particular register.
73682** We could factor them out, but then we would end up adding an
73683** OP_SCopy instruction to move the value into the correct register
73684** later.  We might as well just use the original instruction and
73685** avoid the OP_SCopy.
73686*/
73687static int isAppropriateForFactoring(Expr *p){
73688  if( !sqlite3ExprIsConstantNotJoin(p) ){
73689    return 0;  /* Only constant expressions are appropriate for factoring */
73690  }
73691  if( (p->flags & EP_FixedDest)==0 ){
73692    return 1;  /* Any constant without a fixed destination is appropriate */
73693  }
73694  while( p->op==TK_UPLUS ) p = p->pLeft;
73695  switch( p->op ){
73696#ifndef SQLITE_OMIT_BLOB_LITERAL
73697    case TK_BLOB:
73698#endif
73699    case TK_VARIABLE:
73700    case TK_INTEGER:
73701    case TK_FLOAT:
73702    case TK_NULL:
73703    case TK_STRING: {
73704      testcase( p->op==TK_BLOB );
73705      testcase( p->op==TK_VARIABLE );
73706      testcase( p->op==TK_INTEGER );
73707      testcase( p->op==TK_FLOAT );
73708      testcase( p->op==TK_NULL );
73709      testcase( p->op==TK_STRING );
73710      /* Single-instruction constants with a fixed destination are
73711      ** better done in-line.  If we factor them, they will just end
73712      ** up generating an OP_SCopy to move the value to the destination
73713      ** register. */
73714      return 0;
73715    }
73716    case TK_UMINUS: {
73717      if( p->pLeft->op==TK_FLOAT || p->pLeft->op==TK_INTEGER ){
73718        return 0;
73719      }
73720      break;
73721    }
73722    default: {
73723      break;
73724    }
73725  }
73726  return 1;
73727}
73728
73729/*
73730** If pExpr is a constant expression that is appropriate for
73731** factoring out of a loop, then evaluate the expression
73732** into a register and convert the expression into a TK_REGISTER
73733** expression.
73734*/
73735static int evalConstExpr(Walker *pWalker, Expr *pExpr){
73736  Parse *pParse = pWalker->pParse;
73737  switch( pExpr->op ){
73738    case TK_IN:
73739    case TK_REGISTER: {
73740      return WRC_Prune;
73741    }
73742    case TK_FUNCTION:
73743    case TK_AGG_FUNCTION:
73744    case TK_CONST_FUNC: {
73745      /* The arguments to a function have a fixed destination.
73746      ** Mark them this way to avoid generated unneeded OP_SCopy
73747      ** instructions.
73748      */
73749      ExprList *pList = pExpr->x.pList;
73750      assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
73751      if( pList ){
73752        int i = pList->nExpr;
73753        struct ExprList_item *pItem = pList->a;
73754        for(; i>0; i--, pItem++){
73755          if( ALWAYS(pItem->pExpr) ) pItem->pExpr->flags |= EP_FixedDest;
73756        }
73757      }
73758      break;
73759    }
73760  }
73761  if( isAppropriateForFactoring(pExpr) ){
73762    int r1 = ++pParse->nMem;
73763    int r2;
73764    r2 = sqlite3ExprCodeTarget(pParse, pExpr, r1);
73765    if( NEVER(r1!=r2) ) sqlite3ReleaseTempReg(pParse, r1);
73766    pExpr->op2 = pExpr->op;
73767    pExpr->op = TK_REGISTER;
73768    pExpr->iTable = r2;
73769    return WRC_Prune;
73770  }
73771  return WRC_Continue;
73772}
73773
73774/*
73775** Preevaluate constant subexpressions within pExpr and store the
73776** results in registers.  Modify pExpr so that the constant subexpresions
73777** are TK_REGISTER opcodes that refer to the precomputed values.
73778**
73779** This routine is a no-op if the jump to the cookie-check code has
73780** already occur.  Since the cookie-check jump is generated prior to
73781** any other serious processing, this check ensures that there is no
73782** way to accidently bypass the constant initializations.
73783**
73784** This routine is also a no-op if the SQLITE_FactorOutConst optimization
73785** is disabled via the sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS)
73786** interface.  This allows test logic to verify that the same answer is
73787** obtained for queries regardless of whether or not constants are
73788** precomputed into registers or if they are inserted in-line.
73789*/
73790SQLITE_PRIVATE void sqlite3ExprCodeConstants(Parse *pParse, Expr *pExpr){
73791  Walker w;
73792  if( pParse->cookieGoto ) return;
73793  if( (pParse->db->flags & SQLITE_FactorOutConst)!=0 ) return;
73794  w.xExprCallback = evalConstExpr;
73795  w.xSelectCallback = 0;
73796  w.pParse = pParse;
73797  sqlite3WalkExpr(&w, pExpr);
73798}
73799
73800
73801/*
73802** Generate code that pushes the value of every element of the given
73803** expression list into a sequence of registers beginning at target.
73804**
73805** Return the number of elements evaluated.
73806*/
73807SQLITE_PRIVATE int sqlite3ExprCodeExprList(
73808  Parse *pParse,     /* Parsing context */
73809  ExprList *pList,   /* The expression list to be coded */
73810  int target,        /* Where to write results */
73811  int doHardCopy     /* Make a hard copy of every element */
73812){
73813  struct ExprList_item *pItem;
73814  int i, n;
73815  assert( pList!=0 );
73816  assert( target>0 );
73817  assert( pParse->pVdbe!=0 );  /* Never gets this far otherwise */
73818  n = pList->nExpr;
73819  for(pItem=pList->a, i=0; i<n; i++, pItem++){
73820    Expr *pExpr = pItem->pExpr;
73821    int inReg = sqlite3ExprCodeTarget(pParse, pExpr, target+i);
73822    if( inReg!=target+i ){
73823      sqlite3VdbeAddOp2(pParse->pVdbe, doHardCopy ? OP_Copy : OP_SCopy,
73824                        inReg, target+i);
73825    }
73826  }
73827  return n;
73828}
73829
73830/*
73831** Generate code for a BETWEEN operator.
73832**
73833**    x BETWEEN y AND z
73834**
73835** The above is equivalent to
73836**
73837**    x>=y AND x<=z
73838**
73839** Code it as such, taking care to do the common subexpression
73840** elementation of x.
73841*/
73842static void exprCodeBetween(
73843  Parse *pParse,    /* Parsing and code generating context */
73844  Expr *pExpr,      /* The BETWEEN expression */
73845  int dest,         /* Jump here if the jump is taken */
73846  int jumpIfTrue,   /* Take the jump if the BETWEEN is true */
73847  int jumpIfNull    /* Take the jump if the BETWEEN is NULL */
73848){
73849  Expr exprAnd;     /* The AND operator in  x>=y AND x<=z  */
73850  Expr compLeft;    /* The  x>=y  term */
73851  Expr compRight;   /* The  x<=z  term */
73852  Expr exprX;       /* The  x  subexpression */
73853  int regFree1 = 0; /* Temporary use register */
73854
73855  assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
73856  exprX = *pExpr->pLeft;
73857  exprAnd.op = TK_AND;
73858  exprAnd.pLeft = &compLeft;
73859  exprAnd.pRight = &compRight;
73860  compLeft.op = TK_GE;
73861  compLeft.pLeft = &exprX;
73862  compLeft.pRight = pExpr->x.pList->a[0].pExpr;
73863  compRight.op = TK_LE;
73864  compRight.pLeft = &exprX;
73865  compRight.pRight = pExpr->x.pList->a[1].pExpr;
73866  exprX.iTable = sqlite3ExprCodeTemp(pParse, &exprX, &regFree1);
73867  exprX.op = TK_REGISTER;
73868  if( jumpIfTrue ){
73869    sqlite3ExprIfTrue(pParse, &exprAnd, dest, jumpIfNull);
73870  }else{
73871    sqlite3ExprIfFalse(pParse, &exprAnd, dest, jumpIfNull);
73872  }
73873  sqlite3ReleaseTempReg(pParse, regFree1);
73874
73875  /* Ensure adequate test coverage */
73876  testcase( jumpIfTrue==0 && jumpIfNull==0 && regFree1==0 );
73877  testcase( jumpIfTrue==0 && jumpIfNull==0 && regFree1!=0 );
73878  testcase( jumpIfTrue==0 && jumpIfNull!=0 && regFree1==0 );
73879  testcase( jumpIfTrue==0 && jumpIfNull!=0 && regFree1!=0 );
73880  testcase( jumpIfTrue!=0 && jumpIfNull==0 && regFree1==0 );
73881  testcase( jumpIfTrue!=0 && jumpIfNull==0 && regFree1!=0 );
73882  testcase( jumpIfTrue!=0 && jumpIfNull!=0 && regFree1==0 );
73883  testcase( jumpIfTrue!=0 && jumpIfNull!=0 && regFree1!=0 );
73884}
73885
73886/*
73887** Generate code for a boolean expression such that a jump is made
73888** to the label "dest" if the expression is true but execution
73889** continues straight thru if the expression is false.
73890**
73891** If the expression evaluates to NULL (neither true nor false), then
73892** take the jump if the jumpIfNull flag is SQLITE_JUMPIFNULL.
73893**
73894** This code depends on the fact that certain token values (ex: TK_EQ)
73895** are the same as opcode values (ex: OP_Eq) that implement the corresponding
73896** operation.  Special comments in vdbe.c and the mkopcodeh.awk script in
73897** the make process cause these values to align.  Assert()s in the code
73898** below verify that the numbers are aligned correctly.
73899*/
73900SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
73901  Vdbe *v = pParse->pVdbe;
73902  int op = 0;
73903  int regFree1 = 0;
73904  int regFree2 = 0;
73905  int r1, r2;
73906
73907  assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
73908  if( NEVER(v==0) )     return;  /* Existance of VDBE checked by caller */
73909  if( NEVER(pExpr==0) ) return;  /* No way this can happen */
73910  op = pExpr->op;
73911  switch( op ){
73912    case TK_AND: {
73913      int d2 = sqlite3VdbeMakeLabel(v);
73914      testcase( jumpIfNull==0 );
73915      sqlite3ExprCachePush(pParse);
73916      sqlite3ExprIfFalse(pParse, pExpr->pLeft, d2,jumpIfNull^SQLITE_JUMPIFNULL);
73917      sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
73918      sqlite3VdbeResolveLabel(v, d2);
73919      sqlite3ExprCachePop(pParse, 1);
73920      break;
73921    }
73922    case TK_OR: {
73923      testcase( jumpIfNull==0 );
73924      sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
73925      sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
73926      break;
73927    }
73928    case TK_NOT: {
73929      testcase( jumpIfNull==0 );
73930      sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
73931      break;
73932    }
73933    case TK_LT:
73934    case TK_LE:
73935    case TK_GT:
73936    case TK_GE:
73937    case TK_NE:
73938    case TK_EQ: {
73939      assert( TK_LT==OP_Lt );
73940      assert( TK_LE==OP_Le );
73941      assert( TK_GT==OP_Gt );
73942      assert( TK_GE==OP_Ge );
73943      assert( TK_EQ==OP_Eq );
73944      assert( TK_NE==OP_Ne );
73945      testcase( op==TK_LT );
73946      testcase( op==TK_LE );
73947      testcase( op==TK_GT );
73948      testcase( op==TK_GE );
73949      testcase( op==TK_EQ );
73950      testcase( op==TK_NE );
73951      testcase( jumpIfNull==0 );
73952      r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
73953      r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
73954      codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
73955                  r1, r2, dest, jumpIfNull);
73956      testcase( regFree1==0 );
73957      testcase( regFree2==0 );
73958      break;
73959    }
73960    case TK_IS:
73961    case TK_ISNOT: {
73962      testcase( op==TK_IS );
73963      testcase( op==TK_ISNOT );
73964      r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
73965      r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
73966      op = (op==TK_IS) ? TK_EQ : TK_NE;
73967      codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
73968                  r1, r2, dest, SQLITE_NULLEQ);
73969      testcase( regFree1==0 );
73970      testcase( regFree2==0 );
73971      break;
73972    }
73973    case TK_ISNULL:
73974    case TK_NOTNULL: {
73975      assert( TK_ISNULL==OP_IsNull );
73976      assert( TK_NOTNULL==OP_NotNull );
73977      testcase( op==TK_ISNULL );
73978      testcase( op==TK_NOTNULL );
73979      r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
73980      sqlite3VdbeAddOp2(v, op, r1, dest);
73981      testcase( regFree1==0 );
73982      break;
73983    }
73984    case TK_BETWEEN: {
73985      testcase( jumpIfNull==0 );
73986      exprCodeBetween(pParse, pExpr, dest, 1, jumpIfNull);
73987      break;
73988    }
73989#ifndef SQLITE_OMIT_SUBQUERY
73990    case TK_IN: {
73991      int destIfFalse = sqlite3VdbeMakeLabel(v);
73992      int destIfNull = jumpIfNull ? dest : destIfFalse;
73993      sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
73994      sqlite3VdbeAddOp2(v, OP_Goto, 0, dest);
73995      sqlite3VdbeResolveLabel(v, destIfFalse);
73996      break;
73997    }
73998#endif
73999    default: {
74000      r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
74001      sqlite3VdbeAddOp3(v, OP_If, r1, dest, jumpIfNull!=0);
74002      testcase( regFree1==0 );
74003      testcase( jumpIfNull==0 );
74004      break;
74005    }
74006  }
74007  sqlite3ReleaseTempReg(pParse, regFree1);
74008  sqlite3ReleaseTempReg(pParse, regFree2);
74009}
74010
74011/*
74012** Generate code for a boolean expression such that a jump is made
74013** to the label "dest" if the expression is false but execution
74014** continues straight thru if the expression is true.
74015**
74016** If the expression evaluates to NULL (neither true nor false) then
74017** jump if jumpIfNull is SQLITE_JUMPIFNULL or fall through if jumpIfNull
74018** is 0.
74019*/
74020SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
74021  Vdbe *v = pParse->pVdbe;
74022  int op = 0;
74023  int regFree1 = 0;
74024  int regFree2 = 0;
74025  int r1, r2;
74026
74027  assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
74028  if( NEVER(v==0) ) return; /* Existance of VDBE checked by caller */
74029  if( pExpr==0 )    return;
74030
74031  /* The value of pExpr->op and op are related as follows:
74032  **
74033  **       pExpr->op            op
74034  **       ---------          ----------
74035  **       TK_ISNULL          OP_NotNull
74036  **       TK_NOTNULL         OP_IsNull
74037  **       TK_NE              OP_Eq
74038  **       TK_EQ              OP_Ne
74039  **       TK_GT              OP_Le
74040  **       TK_LE              OP_Gt
74041  **       TK_GE              OP_Lt
74042  **       TK_LT              OP_Ge
74043  **
74044  ** For other values of pExpr->op, op is undefined and unused.
74045  ** The value of TK_ and OP_ constants are arranged such that we
74046  ** can compute the mapping above using the following expression.
74047  ** Assert()s verify that the computation is correct.
74048  */
74049  op = ((pExpr->op+(TK_ISNULL&1))^1)-(TK_ISNULL&1);
74050
74051  /* Verify correct alignment of TK_ and OP_ constants
74052  */
74053  assert( pExpr->op!=TK_ISNULL || op==OP_NotNull );
74054  assert( pExpr->op!=TK_NOTNULL || op==OP_IsNull );
74055  assert( pExpr->op!=TK_NE || op==OP_Eq );
74056  assert( pExpr->op!=TK_EQ || op==OP_Ne );
74057  assert( pExpr->op!=TK_LT || op==OP_Ge );
74058  assert( pExpr->op!=TK_LE || op==OP_Gt );
74059  assert( pExpr->op!=TK_GT || op==OP_Le );
74060  assert( pExpr->op!=TK_GE || op==OP_Lt );
74061
74062  switch( pExpr->op ){
74063    case TK_AND: {
74064      testcase( jumpIfNull==0 );
74065      sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
74066      sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
74067      break;
74068    }
74069    case TK_OR: {
74070      int d2 = sqlite3VdbeMakeLabel(v);
74071      testcase( jumpIfNull==0 );
74072      sqlite3ExprCachePush(pParse);
74073      sqlite3ExprIfTrue(pParse, pExpr->pLeft, d2, jumpIfNull^SQLITE_JUMPIFNULL);
74074      sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
74075      sqlite3VdbeResolveLabel(v, d2);
74076      sqlite3ExprCachePop(pParse, 1);
74077      break;
74078    }
74079    case TK_NOT: {
74080      testcase( jumpIfNull==0 );
74081      sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
74082      break;
74083    }
74084    case TK_LT:
74085    case TK_LE:
74086    case TK_GT:
74087    case TK_GE:
74088    case TK_NE:
74089    case TK_EQ: {
74090      testcase( op==TK_LT );
74091      testcase( op==TK_LE );
74092      testcase( op==TK_GT );
74093      testcase( op==TK_GE );
74094      testcase( op==TK_EQ );
74095      testcase( op==TK_NE );
74096      testcase( jumpIfNull==0 );
74097      r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
74098      r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
74099      codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
74100                  r1, r2, dest, jumpIfNull);
74101      testcase( regFree1==0 );
74102      testcase( regFree2==0 );
74103      break;
74104    }
74105    case TK_IS:
74106    case TK_ISNOT: {
74107      testcase( pExpr->op==TK_IS );
74108      testcase( pExpr->op==TK_ISNOT );
74109      r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
74110      r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
74111      op = (pExpr->op==TK_IS) ? TK_NE : TK_EQ;
74112      codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
74113                  r1, r2, dest, SQLITE_NULLEQ);
74114      testcase( regFree1==0 );
74115      testcase( regFree2==0 );
74116      break;
74117    }
74118    case TK_ISNULL:
74119    case TK_NOTNULL: {
74120      testcase( op==TK_ISNULL );
74121      testcase( op==TK_NOTNULL );
74122      r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
74123      sqlite3VdbeAddOp2(v, op, r1, dest);
74124      testcase( regFree1==0 );
74125      break;
74126    }
74127    case TK_BETWEEN: {
74128      testcase( jumpIfNull==0 );
74129      exprCodeBetween(pParse, pExpr, dest, 0, jumpIfNull);
74130      break;
74131    }
74132#ifndef SQLITE_OMIT_SUBQUERY
74133    case TK_IN: {
74134      if( jumpIfNull ){
74135        sqlite3ExprCodeIN(pParse, pExpr, dest, dest);
74136      }else{
74137        int destIfNull = sqlite3VdbeMakeLabel(v);
74138        sqlite3ExprCodeIN(pParse, pExpr, dest, destIfNull);
74139        sqlite3VdbeResolveLabel(v, destIfNull);
74140      }
74141      break;
74142    }
74143#endif
74144    default: {
74145      r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
74146      sqlite3VdbeAddOp3(v, OP_IfNot, r1, dest, jumpIfNull!=0);
74147      testcase( regFree1==0 );
74148      testcase( jumpIfNull==0 );
74149      break;
74150    }
74151  }
74152  sqlite3ReleaseTempReg(pParse, regFree1);
74153  sqlite3ReleaseTempReg(pParse, regFree2);
74154}
74155
74156/*
74157** Do a deep comparison of two expression trees.  Return 0 if the two
74158** expressions are completely identical.  Return 1 if they differ only
74159** by a COLLATE operator at the top level.  Return 2 if there are differences
74160** other than the top-level COLLATE operator.
74161**
74162** Sometimes this routine will return 2 even if the two expressions
74163** really are equivalent.  If we cannot prove that the expressions are
74164** identical, we return 2 just to be safe.  So if this routine
74165** returns 2, then you do not really know for certain if the two
74166** expressions are the same.  But if you get a 0 or 1 return, then you
74167** can be sure the expressions are the same.  In the places where
74168** this routine is used, it does not hurt to get an extra 2 - that
74169** just might result in some slightly slower code.  But returning
74170** an incorrect 0 or 1 could lead to a malfunction.
74171*/
74172SQLITE_PRIVATE int sqlite3ExprCompare(Expr *pA, Expr *pB){
74173  if( pA==0||pB==0 ){
74174    return pB==pA ? 0 : 2;
74175  }
74176  assert( !ExprHasAnyProperty(pA, EP_TokenOnly|EP_Reduced) );
74177  assert( !ExprHasAnyProperty(pB, EP_TokenOnly|EP_Reduced) );
74178  if( ExprHasProperty(pA, EP_xIsSelect) || ExprHasProperty(pB, EP_xIsSelect) ){
74179    return 2;
74180  }
74181  if( (pA->flags & EP_Distinct)!=(pB->flags & EP_Distinct) ) return 2;
74182  if( pA->op!=pB->op ) return 2;
74183  if( sqlite3ExprCompare(pA->pLeft, pB->pLeft) ) return 2;
74184  if( sqlite3ExprCompare(pA->pRight, pB->pRight) ) return 2;
74185  if( sqlite3ExprListCompare(pA->x.pList, pB->x.pList) ) return 2;
74186  if( pA->iTable!=pB->iTable || pA->iColumn!=pB->iColumn ) return 2;
74187  if( ExprHasProperty(pA, EP_IntValue) ){
74188    if( !ExprHasProperty(pB, EP_IntValue) || pA->u.iValue!=pB->u.iValue ){
74189      return 2;
74190    }
74191  }else if( pA->op!=TK_COLUMN && pA->u.zToken ){
74192    if( ExprHasProperty(pB, EP_IntValue) || NEVER(pB->u.zToken==0) ) return 2;
74193    if( sqlite3StrICmp(pA->u.zToken,pB->u.zToken)!=0 ){
74194      return 2;
74195    }
74196  }
74197  if( (pA->flags & EP_ExpCollate)!=(pB->flags & EP_ExpCollate) ) return 1;
74198  if( (pA->flags & EP_ExpCollate)!=0 && pA->pColl!=pB->pColl ) return 2;
74199  return 0;
74200}
74201
74202/*
74203** Compare two ExprList objects.  Return 0 if they are identical and
74204** non-zero if they differ in any way.
74205**
74206** This routine might return non-zero for equivalent ExprLists.  The
74207** only consequence will be disabled optimizations.  But this routine
74208** must never return 0 if the two ExprList objects are different, or
74209** a malfunction will result.
74210**
74211** Two NULL pointers are considered to be the same.  But a NULL pointer
74212** always differs from a non-NULL pointer.
74213*/
74214SQLITE_PRIVATE int sqlite3ExprListCompare(ExprList *pA, ExprList *pB){
74215  int i;
74216  if( pA==0 && pB==0 ) return 0;
74217  if( pA==0 || pB==0 ) return 1;
74218  if( pA->nExpr!=pB->nExpr ) return 1;
74219  for(i=0; i<pA->nExpr; i++){
74220    Expr *pExprA = pA->a[i].pExpr;
74221    Expr *pExprB = pB->a[i].pExpr;
74222    if( pA->a[i].sortOrder!=pB->a[i].sortOrder ) return 1;
74223    if( sqlite3ExprCompare(pExprA, pExprB) ) return 1;
74224  }
74225  return 0;
74226}
74227
74228/*
74229** Add a new element to the pAggInfo->aCol[] array.  Return the index of
74230** the new element.  Return a negative number if malloc fails.
74231*/
74232static int addAggInfoColumn(sqlite3 *db, AggInfo *pInfo){
74233  int i;
74234  pInfo->aCol = sqlite3ArrayAllocate(
74235       db,
74236       pInfo->aCol,
74237       sizeof(pInfo->aCol[0]),
74238       3,
74239       &pInfo->nColumn,
74240       &pInfo->nColumnAlloc,
74241       &i
74242  );
74243  return i;
74244}
74245
74246/*
74247** Add a new element to the pAggInfo->aFunc[] array.  Return the index of
74248** the new element.  Return a negative number if malloc fails.
74249*/
74250static int addAggInfoFunc(sqlite3 *db, AggInfo *pInfo){
74251  int i;
74252  pInfo->aFunc = sqlite3ArrayAllocate(
74253       db,
74254       pInfo->aFunc,
74255       sizeof(pInfo->aFunc[0]),
74256       3,
74257       &pInfo->nFunc,
74258       &pInfo->nFuncAlloc,
74259       &i
74260  );
74261  return i;
74262}
74263
74264/*
74265** This is the xExprCallback for a tree walker.  It is used to
74266** implement sqlite3ExprAnalyzeAggregates().  See sqlite3ExprAnalyzeAggregates
74267** for additional information.
74268*/
74269static int analyzeAggregate(Walker *pWalker, Expr *pExpr){
74270  int i;
74271  NameContext *pNC = pWalker->u.pNC;
74272  Parse *pParse = pNC->pParse;
74273  SrcList *pSrcList = pNC->pSrcList;
74274  AggInfo *pAggInfo = pNC->pAggInfo;
74275
74276  switch( pExpr->op ){
74277    case TK_AGG_COLUMN:
74278    case TK_COLUMN: {
74279      testcase( pExpr->op==TK_AGG_COLUMN );
74280      testcase( pExpr->op==TK_COLUMN );
74281      /* Check to see if the column is in one of the tables in the FROM
74282      ** clause of the aggregate query */
74283      if( ALWAYS(pSrcList!=0) ){
74284        struct SrcList_item *pItem = pSrcList->a;
74285        for(i=0; i<pSrcList->nSrc; i++, pItem++){
74286          struct AggInfo_col *pCol;
74287          assert( !ExprHasAnyProperty(pExpr, EP_TokenOnly|EP_Reduced) );
74288          if( pExpr->iTable==pItem->iCursor ){
74289            /* If we reach this point, it means that pExpr refers to a table
74290            ** that is in the FROM clause of the aggregate query.
74291            **
74292            ** Make an entry for the column in pAggInfo->aCol[] if there
74293            ** is not an entry there already.
74294            */
74295            int k;
74296            pCol = pAggInfo->aCol;
74297            for(k=0; k<pAggInfo->nColumn; k++, pCol++){
74298              if( pCol->iTable==pExpr->iTable &&
74299                  pCol->iColumn==pExpr->iColumn ){
74300                break;
74301              }
74302            }
74303            if( (k>=pAggInfo->nColumn)
74304             && (k = addAggInfoColumn(pParse->db, pAggInfo))>=0
74305            ){
74306              pCol = &pAggInfo->aCol[k];
74307              pCol->pTab = pExpr->pTab;
74308              pCol->iTable = pExpr->iTable;
74309              pCol->iColumn = pExpr->iColumn;
74310              pCol->iMem = ++pParse->nMem;
74311              pCol->iSorterColumn = -1;
74312              pCol->pExpr = pExpr;
74313              if( pAggInfo->pGroupBy ){
74314                int j, n;
74315                ExprList *pGB = pAggInfo->pGroupBy;
74316                struct ExprList_item *pTerm = pGB->a;
74317                n = pGB->nExpr;
74318                for(j=0; j<n; j++, pTerm++){
74319                  Expr *pE = pTerm->pExpr;
74320                  if( pE->op==TK_COLUMN && pE->iTable==pExpr->iTable &&
74321                      pE->iColumn==pExpr->iColumn ){
74322                    pCol->iSorterColumn = j;
74323                    break;
74324                  }
74325                }
74326              }
74327              if( pCol->iSorterColumn<0 ){
74328                pCol->iSorterColumn = pAggInfo->nSortingColumn++;
74329              }
74330            }
74331            /* There is now an entry for pExpr in pAggInfo->aCol[] (either
74332            ** because it was there before or because we just created it).
74333            ** Convert the pExpr to be a TK_AGG_COLUMN referring to that
74334            ** pAggInfo->aCol[] entry.
74335            */
74336            ExprSetIrreducible(pExpr);
74337            pExpr->pAggInfo = pAggInfo;
74338            pExpr->op = TK_AGG_COLUMN;
74339            pExpr->iAgg = (i16)k;
74340            break;
74341          } /* endif pExpr->iTable==pItem->iCursor */
74342        } /* end loop over pSrcList */
74343      }
74344      return WRC_Prune;
74345    }
74346    case TK_AGG_FUNCTION: {
74347      /* The pNC->nDepth==0 test causes aggregate functions in subqueries
74348      ** to be ignored */
74349      if( pNC->nDepth==0 ){
74350        /* Check to see if pExpr is a duplicate of another aggregate
74351        ** function that is already in the pAggInfo structure
74352        */
74353        struct AggInfo_func *pItem = pAggInfo->aFunc;
74354        for(i=0; i<pAggInfo->nFunc; i++, pItem++){
74355          if( sqlite3ExprCompare(pItem->pExpr, pExpr)==0 ){
74356            break;
74357          }
74358        }
74359        if( i>=pAggInfo->nFunc ){
74360          /* pExpr is original.  Make a new entry in pAggInfo->aFunc[]
74361          */
74362          u8 enc = ENC(pParse->db);
74363          i = addAggInfoFunc(pParse->db, pAggInfo);
74364          if( i>=0 ){
74365            assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
74366            pItem = &pAggInfo->aFunc[i];
74367            pItem->pExpr = pExpr;
74368            pItem->iMem = ++pParse->nMem;
74369            assert( !ExprHasProperty(pExpr, EP_IntValue) );
74370            pItem->pFunc = sqlite3FindFunction(pParse->db,
74371                   pExpr->u.zToken, sqlite3Strlen30(pExpr->u.zToken),
74372                   pExpr->x.pList ? pExpr->x.pList->nExpr : 0, enc, 0);
74373            if( pExpr->flags & EP_Distinct ){
74374              pItem->iDistinct = pParse->nTab++;
74375            }else{
74376              pItem->iDistinct = -1;
74377            }
74378          }
74379        }
74380        /* Make pExpr point to the appropriate pAggInfo->aFunc[] entry
74381        */
74382        assert( !ExprHasAnyProperty(pExpr, EP_TokenOnly|EP_Reduced) );
74383        ExprSetIrreducible(pExpr);
74384        pExpr->iAgg = (i16)i;
74385        pExpr->pAggInfo = pAggInfo;
74386        return WRC_Prune;
74387      }
74388    }
74389  }
74390  return WRC_Continue;
74391}
74392static int analyzeAggregatesInSelect(Walker *pWalker, Select *pSelect){
74393  NameContext *pNC = pWalker->u.pNC;
74394  if( pNC->nDepth==0 ){
74395    pNC->nDepth++;
74396    sqlite3WalkSelect(pWalker, pSelect);
74397    pNC->nDepth--;
74398    return WRC_Prune;
74399  }else{
74400    return WRC_Continue;
74401  }
74402}
74403
74404/*
74405** Analyze the given expression looking for aggregate functions and
74406** for variables that need to be added to the pParse->aAgg[] array.
74407** Make additional entries to the pParse->aAgg[] array as necessary.
74408**
74409** This routine should only be called after the expression has been
74410** analyzed by sqlite3ResolveExprNames().
74411*/
74412SQLITE_PRIVATE void sqlite3ExprAnalyzeAggregates(NameContext *pNC, Expr *pExpr){
74413  Walker w;
74414  w.xExprCallback = analyzeAggregate;
74415  w.xSelectCallback = analyzeAggregatesInSelect;
74416  w.u.pNC = pNC;
74417  assert( pNC->pSrcList!=0 );
74418  sqlite3WalkExpr(&w, pExpr);
74419}
74420
74421/*
74422** Call sqlite3ExprAnalyzeAggregates() for every expression in an
74423** expression list.  Return the number of errors.
74424**
74425** If an error is found, the analysis is cut short.
74426*/
74427SQLITE_PRIVATE void sqlite3ExprAnalyzeAggList(NameContext *pNC, ExprList *pList){
74428  struct ExprList_item *pItem;
74429  int i;
74430  if( pList ){
74431    for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
74432      sqlite3ExprAnalyzeAggregates(pNC, pItem->pExpr);
74433    }
74434  }
74435}
74436
74437/*
74438** Allocate a single new register for use to hold some intermediate result.
74439*/
74440SQLITE_PRIVATE int sqlite3GetTempReg(Parse *pParse){
74441  if( pParse->nTempReg==0 ){
74442    return ++pParse->nMem;
74443  }
74444  return pParse->aTempReg[--pParse->nTempReg];
74445}
74446
74447/*
74448** Deallocate a register, making available for reuse for some other
74449** purpose.
74450**
74451** If a register is currently being used by the column cache, then
74452** the dallocation is deferred until the column cache line that uses
74453** the register becomes stale.
74454*/
74455SQLITE_PRIVATE void sqlite3ReleaseTempReg(Parse *pParse, int iReg){
74456  if( iReg && pParse->nTempReg<ArraySize(pParse->aTempReg) ){
74457    int i;
74458    struct yColCache *p;
74459    for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
74460      if( p->iReg==iReg ){
74461        p->tempReg = 1;
74462        return;
74463      }
74464    }
74465    pParse->aTempReg[pParse->nTempReg++] = iReg;
74466  }
74467}
74468
74469/*
74470** Allocate or deallocate a block of nReg consecutive registers
74471*/
74472SQLITE_PRIVATE int sqlite3GetTempRange(Parse *pParse, int nReg){
74473  int i, n;
74474  i = pParse->iRangeReg;
74475  n = pParse->nRangeReg;
74476  if( nReg<=n ){
74477    assert( !usedAsColumnCache(pParse, i, i+n-1) );
74478    pParse->iRangeReg += nReg;
74479    pParse->nRangeReg -= nReg;
74480  }else{
74481    i = pParse->nMem+1;
74482    pParse->nMem += nReg;
74483  }
74484  return i;
74485}
74486SQLITE_PRIVATE void sqlite3ReleaseTempRange(Parse *pParse, int iReg, int nReg){
74487  sqlite3ExprCacheRemove(pParse, iReg, nReg);
74488  if( nReg>pParse->nRangeReg ){
74489    pParse->nRangeReg = nReg;
74490    pParse->iRangeReg = iReg;
74491  }
74492}
74493
74494/************** End of expr.c ************************************************/
74495/************** Begin file alter.c *******************************************/
74496/*
74497** 2005 February 15
74498**
74499** The author disclaims copyright to this source code.  In place of
74500** a legal notice, here is a blessing:
74501**
74502**    May you do good and not evil.
74503**    May you find forgiveness for yourself and forgive others.
74504**    May you share freely, never taking more than you give.
74505**
74506*************************************************************************
74507** This file contains C code routines that used to generate VDBE code
74508** that implements the ALTER TABLE command.
74509*/
74510
74511/*
74512** The code in this file only exists if we are not omitting the
74513** ALTER TABLE logic from the build.
74514*/
74515#ifndef SQLITE_OMIT_ALTERTABLE
74516
74517
74518/*
74519** This function is used by SQL generated to implement the
74520** ALTER TABLE command. The first argument is the text of a CREATE TABLE or
74521** CREATE INDEX command. The second is a table name. The table name in
74522** the CREATE TABLE or CREATE INDEX statement is replaced with the third
74523** argument and the result returned. Examples:
74524**
74525** sqlite_rename_table('CREATE TABLE abc(a, b, c)', 'def')
74526**     -> 'CREATE TABLE def(a, b, c)'
74527**
74528** sqlite_rename_table('CREATE INDEX i ON abc(a)', 'def')
74529**     -> 'CREATE INDEX i ON def(a, b, c)'
74530*/
74531static void renameTableFunc(
74532  sqlite3_context *context,
74533  int NotUsed,
74534  sqlite3_value **argv
74535){
74536  unsigned char const *zSql = sqlite3_value_text(argv[0]);
74537  unsigned char const *zTableName = sqlite3_value_text(argv[1]);
74538
74539  int token;
74540  Token tname;
74541  unsigned char const *zCsr = zSql;
74542  int len = 0;
74543  char *zRet;
74544
74545  sqlite3 *db = sqlite3_context_db_handle(context);
74546
74547  UNUSED_PARAMETER(NotUsed);
74548
74549  /* The principle used to locate the table name in the CREATE TABLE
74550  ** statement is that the table name is the first non-space token that
74551  ** is immediately followed by a TK_LP or TK_USING token.
74552  */
74553  if( zSql ){
74554    do {
74555      if( !*zCsr ){
74556        /* Ran out of input before finding an opening bracket. Return NULL. */
74557        return;
74558      }
74559
74560      /* Store the token that zCsr points to in tname. */
74561      tname.z = (char*)zCsr;
74562      tname.n = len;
74563
74564      /* Advance zCsr to the next token. Store that token type in 'token',
74565      ** and its length in 'len' (to be used next iteration of this loop).
74566      */
74567      do {
74568        zCsr += len;
74569        len = sqlite3GetToken(zCsr, &token);
74570      } while( token==TK_SPACE );
74571      assert( len>0 );
74572    } while( token!=TK_LP && token!=TK_USING );
74573
74574    zRet = sqlite3MPrintf(db, "%.*s\"%w\"%s", ((u8*)tname.z) - zSql, zSql,
74575       zTableName, tname.z+tname.n);
74576    sqlite3_result_text(context, zRet, -1, SQLITE_DYNAMIC);
74577  }
74578}
74579
74580/*
74581** This C function implements an SQL user function that is used by SQL code
74582** generated by the ALTER TABLE ... RENAME command to modify the definition
74583** of any foreign key constraints that use the table being renamed as the
74584** parent table. It is passed three arguments:
74585**
74586**   1) The complete text of the CREATE TABLE statement being modified,
74587**   2) The old name of the table being renamed, and
74588**   3) The new name of the table being renamed.
74589**
74590** It returns the new CREATE TABLE statement. For example:
74591**
74592**   sqlite_rename_parent('CREATE TABLE t1(a REFERENCES t2)', 't2', 't3')
74593**       -> 'CREATE TABLE t1(a REFERENCES t3)'
74594*/
74595#ifndef SQLITE_OMIT_FOREIGN_KEY
74596static void renameParentFunc(
74597  sqlite3_context *context,
74598  int NotUsed,
74599  sqlite3_value **argv
74600){
74601  sqlite3 *db = sqlite3_context_db_handle(context);
74602  char *zOutput = 0;
74603  char *zResult;
74604  unsigned char const *zInput = sqlite3_value_text(argv[0]);
74605  unsigned char const *zOld = sqlite3_value_text(argv[1]);
74606  unsigned char const *zNew = sqlite3_value_text(argv[2]);
74607
74608  unsigned const char *z;         /* Pointer to token */
74609  int n;                          /* Length of token z */
74610  int token;                      /* Type of token */
74611
74612  UNUSED_PARAMETER(NotUsed);
74613  for(z=zInput; *z; z=z+n){
74614    n = sqlite3GetToken(z, &token);
74615    if( token==TK_REFERENCES ){
74616      char *zParent;
74617      do {
74618        z += n;
74619        n = sqlite3GetToken(z, &token);
74620      }while( token==TK_SPACE );
74621
74622      zParent = sqlite3DbStrNDup(db, (const char *)z, n);
74623      if( zParent==0 ) break;
74624      sqlite3Dequote(zParent);
74625      if( 0==sqlite3StrICmp((const char *)zOld, zParent) ){
74626        char *zOut = sqlite3MPrintf(db, "%s%.*s\"%w\"",
74627            (zOutput?zOutput:""), z-zInput, zInput, (const char *)zNew
74628        );
74629        sqlite3DbFree(db, zOutput);
74630        zOutput = zOut;
74631        zInput = &z[n];
74632      }
74633      sqlite3DbFree(db, zParent);
74634    }
74635  }
74636
74637  zResult = sqlite3MPrintf(db, "%s%s", (zOutput?zOutput:""), zInput),
74638  sqlite3_result_text(context, zResult, -1, SQLITE_DYNAMIC);
74639  sqlite3DbFree(db, zOutput);
74640}
74641#endif
74642
74643#ifndef SQLITE_OMIT_TRIGGER
74644/* This function is used by SQL generated to implement the
74645** ALTER TABLE command. The first argument is the text of a CREATE TRIGGER
74646** statement. The second is a table name. The table name in the CREATE
74647** TRIGGER statement is replaced with the third argument and the result
74648** returned. This is analagous to renameTableFunc() above, except for CREATE
74649** TRIGGER, not CREATE INDEX and CREATE TABLE.
74650*/
74651static void renameTriggerFunc(
74652  sqlite3_context *context,
74653  int NotUsed,
74654  sqlite3_value **argv
74655){
74656  unsigned char const *zSql = sqlite3_value_text(argv[0]);
74657  unsigned char const *zTableName = sqlite3_value_text(argv[1]);
74658
74659  int token;
74660  Token tname;
74661  int dist = 3;
74662  unsigned char const *zCsr = zSql;
74663  int len = 0;
74664  char *zRet;
74665  sqlite3 *db = sqlite3_context_db_handle(context);
74666
74667  UNUSED_PARAMETER(NotUsed);
74668
74669  /* The principle used to locate the table name in the CREATE TRIGGER
74670  ** statement is that the table name is the first token that is immediatedly
74671  ** preceded by either TK_ON or TK_DOT and immediatedly followed by one
74672  ** of TK_WHEN, TK_BEGIN or TK_FOR.
74673  */
74674  if( zSql ){
74675    do {
74676
74677      if( !*zCsr ){
74678        /* Ran out of input before finding the table name. Return NULL. */
74679        return;
74680      }
74681
74682      /* Store the token that zCsr points to in tname. */
74683      tname.z = (char*)zCsr;
74684      tname.n = len;
74685
74686      /* Advance zCsr to the next token. Store that token type in 'token',
74687      ** and its length in 'len' (to be used next iteration of this loop).
74688      */
74689      do {
74690        zCsr += len;
74691        len = sqlite3GetToken(zCsr, &token);
74692      }while( token==TK_SPACE );
74693      assert( len>0 );
74694
74695      /* Variable 'dist' stores the number of tokens read since the most
74696      ** recent TK_DOT or TK_ON. This means that when a WHEN, FOR or BEGIN
74697      ** token is read and 'dist' equals 2, the condition stated above
74698      ** to be met.
74699      **
74700      ** Note that ON cannot be a database, table or column name, so
74701      ** there is no need to worry about syntax like
74702      ** "CREATE TRIGGER ... ON ON.ON BEGIN ..." etc.
74703      */
74704      dist++;
74705      if( token==TK_DOT || token==TK_ON ){
74706        dist = 0;
74707      }
74708    } while( dist!=2 || (token!=TK_WHEN && token!=TK_FOR && token!=TK_BEGIN) );
74709
74710    /* Variable tname now contains the token that is the old table-name
74711    ** in the CREATE TRIGGER statement.
74712    */
74713    zRet = sqlite3MPrintf(db, "%.*s\"%w\"%s", ((u8*)tname.z) - zSql, zSql,
74714       zTableName, tname.z+tname.n);
74715    sqlite3_result_text(context, zRet, -1, SQLITE_DYNAMIC);
74716  }
74717}
74718#endif   /* !SQLITE_OMIT_TRIGGER */
74719
74720/*
74721** Register built-in functions used to help implement ALTER TABLE
74722*/
74723SQLITE_PRIVATE void sqlite3AlterFunctions(void){
74724  static SQLITE_WSD FuncDef aAlterTableFuncs[] = {
74725    FUNCTION(sqlite_rename_table,   2, 0, 0, renameTableFunc),
74726#ifndef SQLITE_OMIT_TRIGGER
74727    FUNCTION(sqlite_rename_trigger, 2, 0, 0, renameTriggerFunc),
74728#endif
74729#ifndef SQLITE_OMIT_FOREIGN_KEY
74730    FUNCTION(sqlite_rename_parent,  3, 0, 0, renameParentFunc),
74731#endif
74732  };
74733  int i;
74734  FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
74735  FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aAlterTableFuncs);
74736
74737  for(i=0; i<ArraySize(aAlterTableFuncs); i++){
74738    sqlite3FuncDefInsert(pHash, &aFunc[i]);
74739  }
74740}
74741
74742/*
74743** This function is used to create the text of expressions of the form:
74744**
74745**   name=<constant1> OR name=<constant2> OR ...
74746**
74747** If argument zWhere is NULL, then a pointer string containing the text
74748** "name=<constant>" is returned, where <constant> is the quoted version
74749** of the string passed as argument zConstant. The returned buffer is
74750** allocated using sqlite3DbMalloc(). It is the responsibility of the
74751** caller to ensure that it is eventually freed.
74752**
74753** If argument zWhere is not NULL, then the string returned is
74754** "<where> OR name=<constant>", where <where> is the contents of zWhere.
74755** In this case zWhere is passed to sqlite3DbFree() before returning.
74756**
74757*/
74758static char *whereOrName(sqlite3 *db, char *zWhere, char *zConstant){
74759  char *zNew;
74760  if( !zWhere ){
74761    zNew = sqlite3MPrintf(db, "name=%Q", zConstant);
74762  }else{
74763    zNew = sqlite3MPrintf(db, "%s OR name=%Q", zWhere, zConstant);
74764    sqlite3DbFree(db, zWhere);
74765  }
74766  return zNew;
74767}
74768
74769#if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
74770/*
74771** Generate the text of a WHERE expression which can be used to select all
74772** tables that have foreign key constraints that refer to table pTab (i.e.
74773** constraints for which pTab is the parent table) from the sqlite_master
74774** table.
74775*/
74776static char *whereForeignKeys(Parse *pParse, Table *pTab){
74777  FKey *p;
74778  char *zWhere = 0;
74779  for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
74780    zWhere = whereOrName(pParse->db, zWhere, p->pFrom->zName);
74781  }
74782  return zWhere;
74783}
74784#endif
74785
74786/*
74787** Generate the text of a WHERE expression which can be used to select all
74788** temporary triggers on table pTab from the sqlite_temp_master table. If
74789** table pTab has no temporary triggers, or is itself stored in the
74790** temporary database, NULL is returned.
74791*/
74792static char *whereTempTriggers(Parse *pParse, Table *pTab){
74793  Trigger *pTrig;
74794  char *zWhere = 0;
74795  const Schema *pTempSchema = pParse->db->aDb[1].pSchema; /* Temp db schema */
74796
74797  /* If the table is not located in the temp-db (in which case NULL is
74798  ** returned, loop through the tables list of triggers. For each trigger
74799  ** that is not part of the temp-db schema, add a clause to the WHERE
74800  ** expression being built up in zWhere.
74801  */
74802  if( pTab->pSchema!=pTempSchema ){
74803    sqlite3 *db = pParse->db;
74804    for(pTrig=sqlite3TriggerList(pParse, pTab); pTrig; pTrig=pTrig->pNext){
74805      if( pTrig->pSchema==pTempSchema ){
74806        zWhere = whereOrName(db, zWhere, pTrig->zName);
74807      }
74808    }
74809  }
74810  if( zWhere ){
74811    char *zNew = sqlite3MPrintf(pParse->db, "type='trigger' AND (%s)", zWhere);
74812    sqlite3DbFree(pParse->db, zWhere);
74813    zWhere = zNew;
74814  }
74815  return zWhere;
74816}
74817
74818/*
74819** Generate code to drop and reload the internal representation of table
74820** pTab from the database, including triggers and temporary triggers.
74821** Argument zName is the name of the table in the database schema at
74822** the time the generated code is executed. This can be different from
74823** pTab->zName if this function is being called to code part of an
74824** "ALTER TABLE RENAME TO" statement.
74825*/
74826static void reloadTableSchema(Parse *pParse, Table *pTab, const char *zName){
74827  Vdbe *v;
74828  char *zWhere;
74829  int iDb;                   /* Index of database containing pTab */
74830#ifndef SQLITE_OMIT_TRIGGER
74831  Trigger *pTrig;
74832#endif
74833
74834  v = sqlite3GetVdbe(pParse);
74835  if( NEVER(v==0) ) return;
74836  assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
74837  iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
74838  assert( iDb>=0 );
74839
74840#ifndef SQLITE_OMIT_TRIGGER
74841  /* Drop any table triggers from the internal schema. */
74842  for(pTrig=sqlite3TriggerList(pParse, pTab); pTrig; pTrig=pTrig->pNext){
74843    int iTrigDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema);
74844    assert( iTrigDb==iDb || iTrigDb==1 );
74845    sqlite3VdbeAddOp4(v, OP_DropTrigger, iTrigDb, 0, 0, pTrig->zName, 0);
74846  }
74847#endif
74848
74849  /* Drop the table and index from the internal schema.  */
74850  sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
74851
74852  /* Reload the table, index and permanent trigger schemas. */
74853  zWhere = sqlite3MPrintf(pParse->db, "tbl_name=%Q", zName);
74854  if( !zWhere ) return;
74855  sqlite3VdbeAddOp4(v, OP_ParseSchema, iDb, 0, 0, zWhere, P4_DYNAMIC);
74856
74857#ifndef SQLITE_OMIT_TRIGGER
74858  /* Now, if the table is not stored in the temp database, reload any temp
74859  ** triggers. Don't use IN(...) in case SQLITE_OMIT_SUBQUERY is defined.
74860  */
74861  if( (zWhere=whereTempTriggers(pParse, pTab))!=0 ){
74862    sqlite3VdbeAddOp4(v, OP_ParseSchema, 1, 0, 0, zWhere, P4_DYNAMIC);
74863  }
74864#endif
74865}
74866
74867/*
74868** Parameter zName is the name of a table that is about to be altered
74869** (either with ALTER TABLE ... RENAME TO or ALTER TABLE ... ADD COLUMN).
74870** If the table is a system table, this function leaves an error message
74871** in pParse->zErr (system tables may not be altered) and returns non-zero.
74872**
74873** Or, if zName is not a system table, zero is returned.
74874*/
74875static int isSystemTable(Parse *pParse, const char *zName){
74876  if( sqlite3Strlen30(zName)>6 && 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){
74877    sqlite3ErrorMsg(pParse, "table %s may not be altered", zName);
74878    return 1;
74879  }
74880  return 0;
74881}
74882
74883/*
74884** Generate code to implement the "ALTER TABLE xxx RENAME TO yyy"
74885** command.
74886*/
74887SQLITE_PRIVATE void sqlite3AlterRenameTable(
74888  Parse *pParse,            /* Parser context. */
74889  SrcList *pSrc,            /* The table to rename. */
74890  Token *pName              /* The new table name. */
74891){
74892  int iDb;                  /* Database that contains the table */
74893  char *zDb;                /* Name of database iDb */
74894  Table *pTab;              /* Table being renamed */
74895  char *zName = 0;          /* NULL-terminated version of pName */
74896  sqlite3 *db = pParse->db; /* Database connection */
74897  int nTabName;             /* Number of UTF-8 characters in zTabName */
74898  const char *zTabName;     /* Original name of the table */
74899  Vdbe *v;
74900#ifndef SQLITE_OMIT_TRIGGER
74901  char *zWhere = 0;         /* Where clause to locate temp triggers */
74902#endif
74903  VTable *pVTab = 0;        /* Non-zero if this is a v-tab with an xRename() */
74904  int savedDbFlags;         /* Saved value of db->flags */
74905
74906  savedDbFlags = db->flags;
74907  if( NEVER(db->mallocFailed) ) goto exit_rename_table;
74908  assert( pSrc->nSrc==1 );
74909  assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
74910
74911  pTab = sqlite3LocateTable(pParse, 0, pSrc->a[0].zName, pSrc->a[0].zDatabase);
74912  if( !pTab ) goto exit_rename_table;
74913  iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
74914  zDb = db->aDb[iDb].zName;
74915  db->flags |= SQLITE_PreferBuiltin;
74916
74917  /* Get a NULL terminated version of the new table name. */
74918  zName = sqlite3NameFromToken(db, pName);
74919  if( !zName ) goto exit_rename_table;
74920
74921  /* Check that a table or index named 'zName' does not already exist
74922  ** in database iDb. If so, this is an error.
74923  */
74924  if( sqlite3FindTable(db, zName, zDb) || sqlite3FindIndex(db, zName, zDb) ){
74925    sqlite3ErrorMsg(pParse,
74926        "there is already another table or index with this name: %s", zName);
74927    goto exit_rename_table;
74928  }
74929
74930  /* Make sure it is not a system table being altered, or a reserved name
74931  ** that the table is being renamed to.
74932  */
74933  if( SQLITE_OK!=isSystemTable(pParse, pTab->zName) ){
74934    goto exit_rename_table;
74935  }
74936  if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){ goto
74937    exit_rename_table;
74938  }
74939
74940#ifndef SQLITE_OMIT_VIEW
74941  if( pTab->pSelect ){
74942    sqlite3ErrorMsg(pParse, "view %s may not be altered", pTab->zName);
74943    goto exit_rename_table;
74944  }
74945#endif
74946
74947#ifndef SQLITE_OMIT_AUTHORIZATION
74948  /* Invoke the authorization callback. */
74949  if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
74950    goto exit_rename_table;
74951  }
74952#endif
74953
74954#ifndef SQLITE_OMIT_VIRTUALTABLE
74955  if( sqlite3ViewGetColumnNames(pParse, pTab) ){
74956    goto exit_rename_table;
74957  }
74958  if( IsVirtual(pTab) ){
74959    pVTab = sqlite3GetVTable(db, pTab);
74960    if( pVTab->pVtab->pModule->xRename==0 ){
74961      pVTab = 0;
74962    }
74963  }
74964#endif
74965
74966  /* Begin a transaction and code the VerifyCookie for database iDb.
74967  ** Then modify the schema cookie (since the ALTER TABLE modifies the
74968  ** schema). Open a statement transaction if the table is a virtual
74969  ** table.
74970  */
74971  v = sqlite3GetVdbe(pParse);
74972  if( v==0 ){
74973    goto exit_rename_table;
74974  }
74975  sqlite3BeginWriteOperation(pParse, pVTab!=0, iDb);
74976  sqlite3ChangeCookie(pParse, iDb);
74977
74978  /* If this is a virtual table, invoke the xRename() function if
74979  ** one is defined. The xRename() callback will modify the names
74980  ** of any resources used by the v-table implementation (including other
74981  ** SQLite tables) that are identified by the name of the virtual table.
74982  */
74983#ifndef SQLITE_OMIT_VIRTUALTABLE
74984  if( pVTab ){
74985    int i = ++pParse->nMem;
74986    sqlite3VdbeAddOp4(v, OP_String8, 0, i, 0, zName, 0);
74987    sqlite3VdbeAddOp4(v, OP_VRename, i, 0, 0,(const char*)pVTab, P4_VTAB);
74988    sqlite3MayAbort(pParse);
74989  }
74990#endif
74991
74992  /* figure out how many UTF-8 characters are in zName */
74993  zTabName = pTab->zName;
74994  nTabName = sqlite3Utf8CharLen(zTabName, -1);
74995
74996#if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
74997  if( db->flags&SQLITE_ForeignKeys ){
74998    /* If foreign-key support is enabled, rewrite the CREATE TABLE
74999    ** statements corresponding to all child tables of foreign key constraints
75000    ** for which the renamed table is the parent table.  */
75001    if( (zWhere=whereForeignKeys(pParse, pTab))!=0 ){
75002      sqlite3NestedParse(pParse,
75003          "UPDATE \"%w\".%s SET "
75004              "sql = sqlite_rename_parent(sql, %Q, %Q) "
75005              "WHERE %s;", zDb, SCHEMA_TABLE(iDb), zTabName, zName, zWhere);
75006      sqlite3DbFree(db, zWhere);
75007    }
75008  }
75009#endif
75010
75011  /* Modify the sqlite_master table to use the new table name. */
75012  sqlite3NestedParse(pParse,
75013      "UPDATE %Q.%s SET "
75014#ifdef SQLITE_OMIT_TRIGGER
75015          "sql = sqlite_rename_table(sql, %Q), "
75016#else
75017          "sql = CASE "
75018            "WHEN type = 'trigger' THEN sqlite_rename_trigger(sql, %Q)"
75019            "ELSE sqlite_rename_table(sql, %Q) END, "
75020#endif
75021          "tbl_name = %Q, "
75022          "name = CASE "
75023            "WHEN type='table' THEN %Q "
75024            "WHEN name LIKE 'sqlite_autoindex%%' AND type='index' THEN "
75025             "'sqlite_autoindex_' || %Q || substr(name,%d+18) "
75026            "ELSE name END "
75027      "WHERE tbl_name=%Q AND "
75028          "(type='table' OR type='index' OR type='trigger');",
75029      zDb, SCHEMA_TABLE(iDb), zName, zName, zName,
75030#ifndef SQLITE_OMIT_TRIGGER
75031      zName,
75032#endif
75033      zName, nTabName, zTabName
75034  );
75035
75036#ifndef SQLITE_OMIT_AUTOINCREMENT
75037  /* If the sqlite_sequence table exists in this database, then update
75038  ** it with the new table name.
75039  */
75040  if( sqlite3FindTable(db, "sqlite_sequence", zDb) ){
75041    sqlite3NestedParse(pParse,
75042        "UPDATE \"%w\".sqlite_sequence set name = %Q WHERE name = %Q",
75043        zDb, zName, pTab->zName);
75044  }
75045#endif
75046
75047#ifndef SQLITE_OMIT_TRIGGER
75048  /* If there are TEMP triggers on this table, modify the sqlite_temp_master
75049  ** table. Don't do this if the table being ALTERed is itself located in
75050  ** the temp database.
75051  */
75052  if( (zWhere=whereTempTriggers(pParse, pTab))!=0 ){
75053    sqlite3NestedParse(pParse,
75054        "UPDATE sqlite_temp_master SET "
75055            "sql = sqlite_rename_trigger(sql, %Q), "
75056            "tbl_name = %Q "
75057            "WHERE %s;", zName, zName, zWhere);
75058    sqlite3DbFree(db, zWhere);
75059  }
75060#endif
75061
75062#if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
75063  if( db->flags&SQLITE_ForeignKeys ){
75064    FKey *p;
75065    for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
75066      Table *pFrom = p->pFrom;
75067      if( pFrom!=pTab ){
75068        reloadTableSchema(pParse, p->pFrom, pFrom->zName);
75069      }
75070    }
75071  }
75072#endif
75073
75074  /* Drop and reload the internal table schema. */
75075  reloadTableSchema(pParse, pTab, zName);
75076
75077exit_rename_table:
75078  sqlite3SrcListDelete(db, pSrc);
75079  sqlite3DbFree(db, zName);
75080  db->flags = savedDbFlags;
75081}
75082
75083
75084/*
75085** Generate code to make sure the file format number is at least minFormat.
75086** The generated code will increase the file format number if necessary.
75087*/
75088SQLITE_PRIVATE void sqlite3MinimumFileFormat(Parse *pParse, int iDb, int minFormat){
75089  Vdbe *v;
75090  v = sqlite3GetVdbe(pParse);
75091  /* The VDBE should have been allocated before this routine is called.
75092  ** If that allocation failed, we would have quit before reaching this
75093  ** point */
75094  if( ALWAYS(v) ){
75095    int r1 = sqlite3GetTempReg(pParse);
75096    int r2 = sqlite3GetTempReg(pParse);
75097    int j1;
75098    sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, r1, BTREE_FILE_FORMAT);
75099    sqlite3VdbeUsesBtree(v, iDb);
75100    sqlite3VdbeAddOp2(v, OP_Integer, minFormat, r2);
75101    j1 = sqlite3VdbeAddOp3(v, OP_Ge, r2, 0, r1);
75102    sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, r2);
75103    sqlite3VdbeJumpHere(v, j1);
75104    sqlite3ReleaseTempReg(pParse, r1);
75105    sqlite3ReleaseTempReg(pParse, r2);
75106  }
75107}
75108
75109/*
75110** This function is called after an "ALTER TABLE ... ADD" statement
75111** has been parsed. Argument pColDef contains the text of the new
75112** column definition.
75113**
75114** The Table structure pParse->pNewTable was extended to include
75115** the new column during parsing.
75116*/
75117SQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *pParse, Token *pColDef){
75118  Table *pNew;              /* Copy of pParse->pNewTable */
75119  Table *pTab;              /* Table being altered */
75120  int iDb;                  /* Database number */
75121  const char *zDb;          /* Database name */
75122  const char *zTab;         /* Table name */
75123  char *zCol;               /* Null-terminated column definition */
75124  Column *pCol;             /* The new column */
75125  Expr *pDflt;              /* Default value for the new column */
75126  sqlite3 *db;              /* The database connection; */
75127
75128  db = pParse->db;
75129  if( pParse->nErr || db->mallocFailed ) return;
75130  pNew = pParse->pNewTable;
75131  assert( pNew );
75132
75133  assert( sqlite3BtreeHoldsAllMutexes(db) );
75134  iDb = sqlite3SchemaToIndex(db, pNew->pSchema);
75135  zDb = db->aDb[iDb].zName;
75136  zTab = &pNew->zName[16];  /* Skip the "sqlite_altertab_" prefix on the name */
75137  pCol = &pNew->aCol[pNew->nCol-1];
75138  pDflt = pCol->pDflt;
75139  pTab = sqlite3FindTable(db, zTab, zDb);
75140  assert( pTab );
75141
75142#ifndef SQLITE_OMIT_AUTHORIZATION
75143  /* Invoke the authorization callback. */
75144  if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
75145    return;
75146  }
75147#endif
75148
75149  /* If the default value for the new column was specified with a
75150  ** literal NULL, then set pDflt to 0. This simplifies checking
75151  ** for an SQL NULL default below.
75152  */
75153  if( pDflt && pDflt->op==TK_NULL ){
75154    pDflt = 0;
75155  }
75156
75157  /* Check that the new column is not specified as PRIMARY KEY or UNIQUE.
75158  ** If there is a NOT NULL constraint, then the default value for the
75159  ** column must not be NULL.
75160  */
75161  if( pCol->isPrimKey ){
75162    sqlite3ErrorMsg(pParse, "Cannot add a PRIMARY KEY column");
75163    return;
75164  }
75165  if( pNew->pIndex ){
75166    sqlite3ErrorMsg(pParse, "Cannot add a UNIQUE column");
75167    return;
75168  }
75169  if( (db->flags&SQLITE_ForeignKeys) && pNew->pFKey && pDflt ){
75170    sqlite3ErrorMsg(pParse,
75171        "Cannot add a REFERENCES column with non-NULL default value");
75172    return;
75173  }
75174  if( pCol->notNull && !pDflt ){
75175    sqlite3ErrorMsg(pParse,
75176        "Cannot add a NOT NULL column with default value NULL");
75177    return;
75178  }
75179
75180  /* Ensure the default expression is something that sqlite3ValueFromExpr()
75181  ** can handle (i.e. not CURRENT_TIME etc.)
75182  */
75183  if( pDflt ){
75184    sqlite3_value *pVal;
75185    if( sqlite3ValueFromExpr(db, pDflt, SQLITE_UTF8, SQLITE_AFF_NONE, &pVal) ){
75186      db->mallocFailed = 1;
75187      return;
75188    }
75189    if( !pVal ){
75190      sqlite3ErrorMsg(pParse, "Cannot add a column with non-constant default");
75191      return;
75192    }
75193    sqlite3ValueFree(pVal);
75194  }
75195
75196  /* Modify the CREATE TABLE statement. */
75197  zCol = sqlite3DbStrNDup(db, (char*)pColDef->z, pColDef->n);
75198  if( zCol ){
75199    char *zEnd = &zCol[pColDef->n-1];
75200    int savedDbFlags = db->flags;
75201    while( zEnd>zCol && (*zEnd==';' || sqlite3Isspace(*zEnd)) ){
75202      *zEnd-- = '\0';
75203    }
75204    db->flags |= SQLITE_PreferBuiltin;
75205    sqlite3NestedParse(pParse,
75206        "UPDATE \"%w\".%s SET "
75207          "sql = substr(sql,1,%d) || ', ' || %Q || substr(sql,%d) "
75208        "WHERE type = 'table' AND name = %Q",
75209      zDb, SCHEMA_TABLE(iDb), pNew->addColOffset, zCol, pNew->addColOffset+1,
75210      zTab
75211    );
75212    sqlite3DbFree(db, zCol);
75213    db->flags = savedDbFlags;
75214  }
75215
75216  /* If the default value of the new column is NULL, then set the file
75217  ** format to 2. If the default value of the new column is not NULL,
75218  ** the file format becomes 3.
75219  */
75220  sqlite3MinimumFileFormat(pParse, iDb, pDflt ? 3 : 2);
75221
75222  /* Reload the schema of the modified table. */
75223  reloadTableSchema(pParse, pTab, pTab->zName);
75224}
75225
75226/*
75227** This function is called by the parser after the table-name in
75228** an "ALTER TABLE <table-name> ADD" statement is parsed. Argument
75229** pSrc is the full-name of the table being altered.
75230**
75231** This routine makes a (partial) copy of the Table structure
75232** for the table being altered and sets Parse.pNewTable to point
75233** to it. Routines called by the parser as the column definition
75234** is parsed (i.e. sqlite3AddColumn()) add the new Column data to
75235** the copy. The copy of the Table structure is deleted by tokenize.c
75236** after parsing is finished.
75237**
75238** Routine sqlite3AlterFinishAddColumn() will be called to complete
75239** coding the "ALTER TABLE ... ADD" statement.
75240*/
75241SQLITE_PRIVATE void sqlite3AlterBeginAddColumn(Parse *pParse, SrcList *pSrc){
75242  Table *pNew;
75243  Table *pTab;
75244  Vdbe *v;
75245  int iDb;
75246  int i;
75247  int nAlloc;
75248  sqlite3 *db = pParse->db;
75249
75250  /* Look up the table being altered. */
75251  assert( pParse->pNewTable==0 );
75252  assert( sqlite3BtreeHoldsAllMutexes(db) );
75253  if( db->mallocFailed ) goto exit_begin_add_column;
75254  pTab = sqlite3LocateTable(pParse, 0, pSrc->a[0].zName, pSrc->a[0].zDatabase);
75255  if( !pTab ) goto exit_begin_add_column;
75256
75257#ifndef SQLITE_OMIT_VIRTUALTABLE
75258  if( IsVirtual(pTab) ){
75259    sqlite3ErrorMsg(pParse, "virtual tables may not be altered");
75260    goto exit_begin_add_column;
75261  }
75262#endif
75263
75264  /* Make sure this is not an attempt to ALTER a view. */
75265  if( pTab->pSelect ){
75266    sqlite3ErrorMsg(pParse, "Cannot add a column to a view");
75267    goto exit_begin_add_column;
75268  }
75269  if( SQLITE_OK!=isSystemTable(pParse, pTab->zName) ){
75270    goto exit_begin_add_column;
75271  }
75272
75273  assert( pTab->addColOffset>0 );
75274  iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
75275
75276  /* Put a copy of the Table struct in Parse.pNewTable for the
75277  ** sqlite3AddColumn() function and friends to modify.  But modify
75278  ** the name by adding an "sqlite_altertab_" prefix.  By adding this
75279  ** prefix, we insure that the name will not collide with an existing
75280  ** table because user table are not allowed to have the "sqlite_"
75281  ** prefix on their name.
75282  */
75283  pNew = (Table*)sqlite3DbMallocZero(db, sizeof(Table));
75284  if( !pNew ) goto exit_begin_add_column;
75285  pParse->pNewTable = pNew;
75286  pNew->nRef = 1;
75287  pNew->nCol = pTab->nCol;
75288  assert( pNew->nCol>0 );
75289  nAlloc = (((pNew->nCol-1)/8)*8)+8;
75290  assert( nAlloc>=pNew->nCol && nAlloc%8==0 && nAlloc-pNew->nCol<8 );
75291  pNew->aCol = (Column*)sqlite3DbMallocZero(db, sizeof(Column)*nAlloc);
75292  pNew->zName = sqlite3MPrintf(db, "sqlite_altertab_%s", pTab->zName);
75293  if( !pNew->aCol || !pNew->zName ){
75294    db->mallocFailed = 1;
75295    goto exit_begin_add_column;
75296  }
75297  memcpy(pNew->aCol, pTab->aCol, sizeof(Column)*pNew->nCol);
75298  for(i=0; i<pNew->nCol; i++){
75299    Column *pCol = &pNew->aCol[i];
75300    pCol->zName = sqlite3DbStrDup(db, pCol->zName);
75301    pCol->zColl = 0;
75302    pCol->zType = 0;
75303    pCol->pDflt = 0;
75304    pCol->zDflt = 0;
75305  }
75306  pNew->pSchema = db->aDb[iDb].pSchema;
75307  pNew->addColOffset = pTab->addColOffset;
75308  pNew->nRef = 1;
75309
75310  /* Begin a transaction and increment the schema cookie.  */
75311  sqlite3BeginWriteOperation(pParse, 0, iDb);
75312  v = sqlite3GetVdbe(pParse);
75313  if( !v ) goto exit_begin_add_column;
75314  sqlite3ChangeCookie(pParse, iDb);
75315
75316exit_begin_add_column:
75317  sqlite3SrcListDelete(db, pSrc);
75318  return;
75319}
75320#endif  /* SQLITE_ALTER_TABLE */
75321
75322/************** End of alter.c ***********************************************/
75323/************** Begin file analyze.c *****************************************/
75324/*
75325** 2005 July 8
75326**
75327** The author disclaims copyright to this source code.  In place of
75328** a legal notice, here is a blessing:
75329**
75330**    May you do good and not evil.
75331**    May you find forgiveness for yourself and forgive others.
75332**    May you share freely, never taking more than you give.
75333**
75334*************************************************************************
75335** This file contains code associated with the ANALYZE command.
75336*/
75337#ifndef SQLITE_OMIT_ANALYZE
75338
75339/*
75340** This routine generates code that opens the sqlite_stat1 table for
75341** writing with cursor iStatCur. If the library was built with the
75342** SQLITE_ENABLE_STAT2 macro defined, then the sqlite_stat2 table is
75343** opened for writing using cursor (iStatCur+1)
75344**
75345** If the sqlite_stat1 tables does not previously exist, it is created.
75346** Similarly, if the sqlite_stat2 table does not exist and the library
75347** is compiled with SQLITE_ENABLE_STAT2 defined, it is created.
75348**
75349** Argument zWhere may be a pointer to a buffer containing a table name,
75350** or it may be a NULL pointer. If it is not NULL, then all entries in
75351** the sqlite_stat1 and (if applicable) sqlite_stat2 tables associated
75352** with the named table are deleted. If zWhere==0, then code is generated
75353** to delete all stat table entries.
75354*/
75355static void openStatTable(
75356  Parse *pParse,          /* Parsing context */
75357  int iDb,                /* The database we are looking in */
75358  int iStatCur,           /* Open the sqlite_stat1 table on this cursor */
75359  const char *zWhere,     /* Delete entries for this table or index */
75360  const char *zWhereType  /* Either "tbl" or "idx" */
75361){
75362  static const struct {
75363    const char *zName;
75364    const char *zCols;
75365  } aTable[] = {
75366    { "sqlite_stat1", "tbl,idx,stat" },
75367#ifdef SQLITE_ENABLE_STAT2
75368    { "sqlite_stat2", "tbl,idx,sampleno,sample" },
75369#endif
75370  };
75371
75372  int aRoot[] = {0, 0};
75373  u8 aCreateTbl[] = {0, 0};
75374
75375  int i;
75376  sqlite3 *db = pParse->db;
75377  Db *pDb;
75378  Vdbe *v = sqlite3GetVdbe(pParse);
75379  if( v==0 ) return;
75380  assert( sqlite3BtreeHoldsAllMutexes(db) );
75381  assert( sqlite3VdbeDb(v)==db );
75382  pDb = &db->aDb[iDb];
75383
75384  for(i=0; i<ArraySize(aTable); i++){
75385    const char *zTab = aTable[i].zName;
75386    Table *pStat;
75387    if( (pStat = sqlite3FindTable(db, zTab, pDb->zName))==0 ){
75388      /* The sqlite_stat[12] table does not exist. Create it. Note that a
75389      ** side-effect of the CREATE TABLE statement is to leave the rootpage
75390      ** of the new table in register pParse->regRoot. This is important
75391      ** because the OpenWrite opcode below will be needing it. */
75392      sqlite3NestedParse(pParse,
75393          "CREATE TABLE %Q.%s(%s)", pDb->zName, zTab, aTable[i].zCols
75394      );
75395      aRoot[i] = pParse->regRoot;
75396      aCreateTbl[i] = 1;
75397    }else{
75398      /* The table already exists. If zWhere is not NULL, delete all entries
75399      ** associated with the table zWhere. If zWhere is NULL, delete the
75400      ** entire contents of the table. */
75401      aRoot[i] = pStat->tnum;
75402      sqlite3TableLock(pParse, iDb, aRoot[i], 1, zTab);
75403      if( zWhere ){
75404        sqlite3NestedParse(pParse,
75405           "DELETE FROM %Q.%s WHERE %s=%Q", pDb->zName, zTab, zWhereType, zWhere
75406        );
75407      }else{
75408        /* The sqlite_stat[12] table already exists.  Delete all rows. */
75409        sqlite3VdbeAddOp2(v, OP_Clear, aRoot[i], iDb);
75410      }
75411    }
75412  }
75413
75414  /* Open the sqlite_stat[12] tables for writing. */
75415  for(i=0; i<ArraySize(aTable); i++){
75416    sqlite3VdbeAddOp3(v, OP_OpenWrite, iStatCur+i, aRoot[i], iDb);
75417    sqlite3VdbeChangeP4(v, -1, (char *)3, P4_INT32);
75418    sqlite3VdbeChangeP5(v, aCreateTbl[i]);
75419  }
75420}
75421
75422/*
75423** Generate code to do an analysis of all indices associated with
75424** a single table.
75425*/
75426static void analyzeOneTable(
75427  Parse *pParse,   /* Parser context */
75428  Table *pTab,     /* Table whose indices are to be analyzed */
75429  Index *pOnlyIdx, /* If not NULL, only analyze this one index */
75430  int iStatCur,    /* Index of VdbeCursor that writes the sqlite_stat1 table */
75431  int iMem         /* Available memory locations begin here */
75432){
75433  sqlite3 *db = pParse->db;    /* Database handle */
75434  Index *pIdx;                 /* An index to being analyzed */
75435  int iIdxCur;                 /* Cursor open on index being analyzed */
75436  Vdbe *v;                     /* The virtual machine being built up */
75437  int i;                       /* Loop counter */
75438  int topOfLoop;               /* The top of the loop */
75439  int endOfLoop;               /* The end of the loop */
75440  int jZeroRows = -1;          /* Jump from here if number of rows is zero */
75441  int iDb;                     /* Index of database containing pTab */
75442  int regTabname = iMem++;     /* Register containing table name */
75443  int regIdxname = iMem++;     /* Register containing index name */
75444  int regSampleno = iMem++;    /* Register containing next sample number */
75445  int regCol = iMem++;         /* Content of a column analyzed table */
75446  int regRec = iMem++;         /* Register holding completed record */
75447  int regTemp = iMem++;        /* Temporary use register */
75448  int regRowid = iMem++;       /* Rowid for the inserted record */
75449
75450#ifdef SQLITE_ENABLE_STAT2
75451  int addr = 0;                /* Instruction address */
75452  int regTemp2 = iMem++;       /* Temporary use register */
75453  int regSamplerecno = iMem++; /* Index of next sample to record */
75454  int regRecno = iMem++;       /* Current sample index */
75455  int regLast = iMem++;        /* Index of last sample to record */
75456  int regFirst = iMem++;       /* Index of first sample to record */
75457#endif
75458
75459  v = sqlite3GetVdbe(pParse);
75460  if( v==0 || NEVER(pTab==0) ){
75461    return;
75462  }
75463  if( pTab->tnum==0 ){
75464    /* Do not gather statistics on views or virtual tables */
75465    return;
75466  }
75467  if( sqlite3_strnicmp(pTab->zName, "sqlite_", 7)==0 ){
75468    /* Do not gather statistics on system tables */
75469    return;
75470  }
75471  assert( sqlite3BtreeHoldsAllMutexes(db) );
75472  iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
75473  assert( iDb>=0 );
75474  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
75475#ifndef SQLITE_OMIT_AUTHORIZATION
75476  if( sqlite3AuthCheck(pParse, SQLITE_ANALYZE, pTab->zName, 0,
75477      db->aDb[iDb].zName ) ){
75478    return;
75479  }
75480#endif
75481
75482  /* Establish a read-lock on the table at the shared-cache level. */
75483  sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
75484
75485  iIdxCur = pParse->nTab++;
75486  sqlite3VdbeAddOp4(v, OP_String8, 0, regTabname, 0, pTab->zName, 0);
75487  for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
75488    int nCol;
75489    KeyInfo *pKey;
75490
75491    if( pOnlyIdx && pOnlyIdx!=pIdx ) continue;
75492    nCol = pIdx->nColumn;
75493    pKey = sqlite3IndexKeyinfo(pParse, pIdx);
75494    if( iMem+1+(nCol*2)>pParse->nMem ){
75495      pParse->nMem = iMem+1+(nCol*2);
75496    }
75497
75498    /* Open a cursor to the index to be analyzed. */
75499    assert( iDb==sqlite3SchemaToIndex(db, pIdx->pSchema) );
75500    sqlite3VdbeAddOp4(v, OP_OpenRead, iIdxCur, pIdx->tnum, iDb,
75501        (char *)pKey, P4_KEYINFO_HANDOFF);
75502    VdbeComment((v, "%s", pIdx->zName));
75503
75504    /* Populate the register containing the index name. */
75505    sqlite3VdbeAddOp4(v, OP_String8, 0, regIdxname, 0, pIdx->zName, 0);
75506
75507#ifdef SQLITE_ENABLE_STAT2
75508
75509    /* If this iteration of the loop is generating code to analyze the
75510    ** first index in the pTab->pIndex list, then register regLast has
75511    ** not been populated. In this case populate it now.  */
75512    if( pTab->pIndex==pIdx ){
75513      sqlite3VdbeAddOp2(v, OP_Integer, SQLITE_INDEX_SAMPLES, regSamplerecno);
75514      sqlite3VdbeAddOp2(v, OP_Integer, SQLITE_INDEX_SAMPLES*2-1, regTemp);
75515      sqlite3VdbeAddOp2(v, OP_Integer, SQLITE_INDEX_SAMPLES*2, regTemp2);
75516
75517      sqlite3VdbeAddOp2(v, OP_Count, iIdxCur, regLast);
75518      sqlite3VdbeAddOp2(v, OP_Null, 0, regFirst);
75519      addr = sqlite3VdbeAddOp3(v, OP_Lt, regSamplerecno, 0, regLast);
75520      sqlite3VdbeAddOp3(v, OP_Divide, regTemp2, regLast, regFirst);
75521      sqlite3VdbeAddOp3(v, OP_Multiply, regLast, regTemp, regLast);
75522      sqlite3VdbeAddOp2(v, OP_AddImm, regLast, SQLITE_INDEX_SAMPLES*2-2);
75523      sqlite3VdbeAddOp3(v, OP_Divide,  regTemp2, regLast, regLast);
75524      sqlite3VdbeJumpHere(v, addr);
75525    }
75526
75527    /* Zero the regSampleno and regRecno registers. */
75528    sqlite3VdbeAddOp2(v, OP_Integer, 0, regSampleno);
75529    sqlite3VdbeAddOp2(v, OP_Integer, 0, regRecno);
75530    sqlite3VdbeAddOp2(v, OP_Copy, regFirst, regSamplerecno);
75531#endif
75532
75533    /* The block of memory cells initialized here is used as follows.
75534    **
75535    **    iMem:
75536    **        The total number of rows in the table.
75537    **
75538    **    iMem+1 .. iMem+nCol:
75539    **        Number of distinct entries in index considering the
75540    **        left-most N columns only, where N is between 1 and nCol,
75541    **        inclusive.
75542    **
75543    **    iMem+nCol+1 .. Mem+2*nCol:
75544    **        Previous value of indexed columns, from left to right.
75545    **
75546    ** Cells iMem through iMem+nCol are initialized to 0. The others are
75547    ** initialized to contain an SQL NULL.
75548    */
75549    for(i=0; i<=nCol; i++){
75550      sqlite3VdbeAddOp2(v, OP_Integer, 0, iMem+i);
75551    }
75552    for(i=0; i<nCol; i++){
75553      sqlite3VdbeAddOp2(v, OP_Null, 0, iMem+nCol+i+1);
75554    }
75555
75556    /* Start the analysis loop. This loop runs through all the entries in
75557    ** the index b-tree.  */
75558    endOfLoop = sqlite3VdbeMakeLabel(v);
75559    sqlite3VdbeAddOp2(v, OP_Rewind, iIdxCur, endOfLoop);
75560    topOfLoop = sqlite3VdbeCurrentAddr(v);
75561    sqlite3VdbeAddOp2(v, OP_AddImm, iMem, 1);
75562
75563    for(i=0; i<nCol; i++){
75564      CollSeq *pColl;
75565      sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, regCol);
75566      if( i==0 ){
75567#ifdef SQLITE_ENABLE_STAT2
75568        /* Check if the record that cursor iIdxCur points to contains a
75569        ** value that should be stored in the sqlite_stat2 table. If so,
75570        ** store it.  */
75571        int ne = sqlite3VdbeAddOp3(v, OP_Ne, regRecno, 0, regSamplerecno);
75572        assert( regTabname+1==regIdxname
75573             && regTabname+2==regSampleno
75574             && regTabname+3==regCol
75575        );
75576        sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);
75577        sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 4, regRec, "aaab", 0);
75578        sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur+1, regRowid);
75579        sqlite3VdbeAddOp3(v, OP_Insert, iStatCur+1, regRec, regRowid);
75580
75581        /* Calculate new values for regSamplerecno and regSampleno.
75582        **
75583        **   sampleno = sampleno + 1
75584        **   samplerecno = samplerecno+(remaining records)/(remaining samples)
75585        */
75586        sqlite3VdbeAddOp2(v, OP_AddImm, regSampleno, 1);
75587        sqlite3VdbeAddOp3(v, OP_Subtract, regRecno, regLast, regTemp);
75588        sqlite3VdbeAddOp2(v, OP_AddImm, regTemp, -1);
75589        sqlite3VdbeAddOp2(v, OP_Integer, SQLITE_INDEX_SAMPLES, regTemp2);
75590        sqlite3VdbeAddOp3(v, OP_Subtract, regSampleno, regTemp2, regTemp2);
75591        sqlite3VdbeAddOp3(v, OP_Divide, regTemp2, regTemp, regTemp);
75592        sqlite3VdbeAddOp3(v, OP_Add, regSamplerecno, regTemp, regSamplerecno);
75593
75594        sqlite3VdbeJumpHere(v, ne);
75595        sqlite3VdbeAddOp2(v, OP_AddImm, regRecno, 1);
75596#endif
75597
75598        /* Always record the very first row */
75599        sqlite3VdbeAddOp1(v, OP_IfNot, iMem+1);
75600      }
75601      assert( pIdx->azColl!=0 );
75602      assert( pIdx->azColl[i]!=0 );
75603      pColl = sqlite3LocateCollSeq(pParse, pIdx->azColl[i]);
75604      sqlite3VdbeAddOp4(v, OP_Ne, regCol, 0, iMem+nCol+i+1,
75605                       (char*)pColl, P4_COLLSEQ);
75606      sqlite3VdbeChangeP5(v, SQLITE_NULLEQ);
75607    }
75608    if( db->mallocFailed ){
75609      /* If a malloc failure has occurred, then the result of the expression
75610      ** passed as the second argument to the call to sqlite3VdbeJumpHere()
75611      ** below may be negative. Which causes an assert() to fail (or an
75612      ** out-of-bounds write if SQLITE_DEBUG is not defined).  */
75613      return;
75614    }
75615    sqlite3VdbeAddOp2(v, OP_Goto, 0, endOfLoop);
75616    for(i=0; i<nCol; i++){
75617      int addr2 = sqlite3VdbeCurrentAddr(v) - (nCol*2);
75618      if( i==0 ){
75619        sqlite3VdbeJumpHere(v, addr2-1);  /* Set jump dest for the OP_IfNot */
75620      }
75621      sqlite3VdbeJumpHere(v, addr2);      /* Set jump dest for the OP_Ne */
75622      sqlite3VdbeAddOp2(v, OP_AddImm, iMem+i+1, 1);
75623      sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, iMem+nCol+i+1);
75624    }
75625
75626    /* End of the analysis loop. */
75627    sqlite3VdbeResolveLabel(v, endOfLoop);
75628    sqlite3VdbeAddOp2(v, OP_Next, iIdxCur, topOfLoop);
75629    sqlite3VdbeAddOp1(v, OP_Close, iIdxCur);
75630
75631    /* Store the results in sqlite_stat1.
75632    **
75633    ** The result is a single row of the sqlite_stat1 table.  The first
75634    ** two columns are the names of the table and index.  The third column
75635    ** is a string composed of a list of integer statistics about the
75636    ** index.  The first integer in the list is the total number of entries
75637    ** in the index.  There is one additional integer in the list for each
75638    ** column of the table.  This additional integer is a guess of how many
75639    ** rows of the table the index will select.  If D is the count of distinct
75640    ** values and K is the total number of rows, then the integer is computed
75641    ** as:
75642    **
75643    **        I = (K+D-1)/D
75644    **
75645    ** If K==0 then no entry is made into the sqlite_stat1 table.
75646    ** If K>0 then it is always the case the D>0 so division by zero
75647    ** is never possible.
75648    */
75649    sqlite3VdbeAddOp2(v, OP_SCopy, iMem, regSampleno);
75650    if( jZeroRows<0 ){
75651      jZeroRows = sqlite3VdbeAddOp1(v, OP_IfNot, iMem);
75652    }
75653    for(i=0; i<nCol; i++){
75654      sqlite3VdbeAddOp4(v, OP_String8, 0, regTemp, 0, " ", 0);
75655      sqlite3VdbeAddOp3(v, OP_Concat, regTemp, regSampleno, regSampleno);
75656      sqlite3VdbeAddOp3(v, OP_Add, iMem, iMem+i+1, regTemp);
75657      sqlite3VdbeAddOp2(v, OP_AddImm, regTemp, -1);
75658      sqlite3VdbeAddOp3(v, OP_Divide, iMem+i+1, regTemp, regTemp);
75659      sqlite3VdbeAddOp1(v, OP_ToInt, regTemp);
75660      sqlite3VdbeAddOp3(v, OP_Concat, regTemp, regSampleno, regSampleno);
75661    }
75662    sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 3, regRec, "aaa", 0);
75663    sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur, regRowid);
75664    sqlite3VdbeAddOp3(v, OP_Insert, iStatCur, regRec, regRowid);
75665    sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
75666  }
75667
75668  /* If the table has no indices, create a single sqlite_stat1 entry
75669  ** containing NULL as the index name and the row count as the content.
75670  */
75671  if( pTab->pIndex==0 ){
75672    sqlite3VdbeAddOp3(v, OP_OpenRead, iIdxCur, pTab->tnum, iDb);
75673    VdbeComment((v, "%s", pTab->zName));
75674    sqlite3VdbeAddOp2(v, OP_Count, iIdxCur, regSampleno);
75675    sqlite3VdbeAddOp1(v, OP_Close, iIdxCur);
75676    jZeroRows = sqlite3VdbeAddOp1(v, OP_IfNot, regSampleno);
75677  }else{
75678    sqlite3VdbeJumpHere(v, jZeroRows);
75679    jZeroRows = sqlite3VdbeAddOp0(v, OP_Goto);
75680  }
75681  sqlite3VdbeAddOp2(v, OP_Null, 0, regIdxname);
75682  sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 3, regRec, "aaa", 0);
75683  sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur, regRowid);
75684  sqlite3VdbeAddOp3(v, OP_Insert, iStatCur, regRec, regRowid);
75685  sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
75686  if( pParse->nMem<regRec ) pParse->nMem = regRec;
75687  sqlite3VdbeJumpHere(v, jZeroRows);
75688}
75689
75690/*
75691** Generate code that will cause the most recent index analysis to
75692** be loaded into internal hash tables where is can be used.
75693*/
75694static void loadAnalysis(Parse *pParse, int iDb){
75695  Vdbe *v = sqlite3GetVdbe(pParse);
75696  if( v ){
75697    sqlite3VdbeAddOp1(v, OP_LoadAnalysis, iDb);
75698  }
75699}
75700
75701/*
75702** Generate code that will do an analysis of an entire database
75703*/
75704static void analyzeDatabase(Parse *pParse, int iDb){
75705  sqlite3 *db = pParse->db;
75706  Schema *pSchema = db->aDb[iDb].pSchema;    /* Schema of database iDb */
75707  HashElem *k;
75708  int iStatCur;
75709  int iMem;
75710
75711  sqlite3BeginWriteOperation(pParse, 0, iDb);
75712  iStatCur = pParse->nTab;
75713  pParse->nTab += 2;
75714  openStatTable(pParse, iDb, iStatCur, 0, 0);
75715  iMem = pParse->nMem+1;
75716  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
75717  for(k=sqliteHashFirst(&pSchema->tblHash); k; k=sqliteHashNext(k)){
75718    Table *pTab = (Table*)sqliteHashData(k);
75719    analyzeOneTable(pParse, pTab, 0, iStatCur, iMem);
75720  }
75721  loadAnalysis(pParse, iDb);
75722}
75723
75724/*
75725** Generate code that will do an analysis of a single table in
75726** a database.  If pOnlyIdx is not NULL then it is a single index
75727** in pTab that should be analyzed.
75728*/
75729static void analyzeTable(Parse *pParse, Table *pTab, Index *pOnlyIdx){
75730  int iDb;
75731  int iStatCur;
75732
75733  assert( pTab!=0 );
75734  assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
75735  iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
75736  sqlite3BeginWriteOperation(pParse, 0, iDb);
75737  iStatCur = pParse->nTab;
75738  pParse->nTab += 2;
75739  if( pOnlyIdx ){
75740    openStatTable(pParse, iDb, iStatCur, pOnlyIdx->zName, "idx");
75741  }else{
75742    openStatTable(pParse, iDb, iStatCur, pTab->zName, "tbl");
75743  }
75744  analyzeOneTable(pParse, pTab, pOnlyIdx, iStatCur, pParse->nMem+1);
75745  loadAnalysis(pParse, iDb);
75746}
75747
75748/*
75749** Generate code for the ANALYZE command.  The parser calls this routine
75750** when it recognizes an ANALYZE command.
75751**
75752**        ANALYZE                            -- 1
75753**        ANALYZE  <database>                -- 2
75754**        ANALYZE  ?<database>.?<tablename>  -- 3
75755**
75756** Form 1 causes all indices in all attached databases to be analyzed.
75757** Form 2 analyzes all indices the single database named.
75758** Form 3 analyzes all indices associated with the named table.
75759*/
75760SQLITE_PRIVATE void sqlite3Analyze(Parse *pParse, Token *pName1, Token *pName2){
75761  sqlite3 *db = pParse->db;
75762  int iDb;
75763  int i;
75764  char *z, *zDb;
75765  Table *pTab;
75766  Index *pIdx;
75767  Token *pTableName;
75768
75769  /* Read the database schema. If an error occurs, leave an error message
75770  ** and code in pParse and return NULL. */
75771  assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
75772  if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
75773    return;
75774  }
75775
75776  assert( pName2!=0 || pName1==0 );
75777  if( pName1==0 ){
75778    /* Form 1:  Analyze everything */
75779    for(i=0; i<db->nDb; i++){
75780      if( i==1 ) continue;  /* Do not analyze the TEMP database */
75781      analyzeDatabase(pParse, i);
75782    }
75783  }else if( pName2->n==0 ){
75784    /* Form 2:  Analyze the database or table named */
75785    iDb = sqlite3FindDb(db, pName1);
75786    if( iDb>=0 ){
75787      analyzeDatabase(pParse, iDb);
75788    }else{
75789      z = sqlite3NameFromToken(db, pName1);
75790      if( z ){
75791        if( (pIdx = sqlite3FindIndex(db, z, 0))!=0 ){
75792          analyzeTable(pParse, pIdx->pTable, pIdx);
75793        }else if( (pTab = sqlite3LocateTable(pParse, 0, z, 0))!=0 ){
75794          analyzeTable(pParse, pTab, 0);
75795        }
75796        sqlite3DbFree(db, z);
75797      }
75798    }
75799  }else{
75800    /* Form 3: Analyze the fully qualified table name */
75801    iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pTableName);
75802    if( iDb>=0 ){
75803      zDb = db->aDb[iDb].zName;
75804      z = sqlite3NameFromToken(db, pTableName);
75805      if( z ){
75806        if( (pIdx = sqlite3FindIndex(db, z, zDb))!=0 ){
75807          analyzeTable(pParse, pIdx->pTable, pIdx);
75808        }else if( (pTab = sqlite3LocateTable(pParse, 0, z, zDb))!=0 ){
75809          analyzeTable(pParse, pTab, 0);
75810        }
75811        sqlite3DbFree(db, z);
75812      }
75813    }
75814  }
75815}
75816
75817/*
75818** Used to pass information from the analyzer reader through to the
75819** callback routine.
75820*/
75821typedef struct analysisInfo analysisInfo;
75822struct analysisInfo {
75823  sqlite3 *db;
75824  const char *zDatabase;
75825};
75826
75827/*
75828** This callback is invoked once for each index when reading the
75829** sqlite_stat1 table.
75830**
75831**     argv[0] = name of the table
75832**     argv[1] = name of the index (might be NULL)
75833**     argv[2] = results of analysis - on integer for each column
75834**
75835** Entries for which argv[1]==NULL simply record the number of rows in
75836** the table.
75837*/
75838static int analysisLoader(void *pData, int argc, char **argv, char **NotUsed){
75839  analysisInfo *pInfo = (analysisInfo*)pData;
75840  Index *pIndex;
75841  Table *pTable;
75842  int i, c, n;
75843  unsigned int v;
75844  const char *z;
75845
75846  assert( argc==3 );
75847  UNUSED_PARAMETER2(NotUsed, argc);
75848
75849  if( argv==0 || argv[0]==0 || argv[2]==0 ){
75850    return 0;
75851  }
75852  pTable = sqlite3FindTable(pInfo->db, argv[0], pInfo->zDatabase);
75853  if( pTable==0 ){
75854    return 0;
75855  }
75856  if( argv[1] ){
75857    pIndex = sqlite3FindIndex(pInfo->db, argv[1], pInfo->zDatabase);
75858  }else{
75859    pIndex = 0;
75860  }
75861  n = pIndex ? pIndex->nColumn : 0;
75862  z = argv[2];
75863  for(i=0; *z && i<=n; i++){
75864    v = 0;
75865    while( (c=z[0])>='0' && c<='9' ){
75866      v = v*10 + c - '0';
75867      z++;
75868    }
75869    if( i==0 ) pTable->nRowEst = v;
75870    if( pIndex==0 ) break;
75871    pIndex->aiRowEst[i] = v;
75872    if( *z==' ' ) z++;
75873    if( strcmp(z, "unordered")==0 ){
75874      pIndex->bUnordered = 1;
75875      break;
75876    }
75877  }
75878  return 0;
75879}
75880
75881/*
75882** If the Index.aSample variable is not NULL, delete the aSample[] array
75883** and its contents.
75884*/
75885SQLITE_PRIVATE void sqlite3DeleteIndexSamples(sqlite3 *db, Index *pIdx){
75886#ifdef SQLITE_ENABLE_STAT2
75887  if( pIdx->aSample ){
75888    int j;
75889    for(j=0; j<SQLITE_INDEX_SAMPLES; j++){
75890      IndexSample *p = &pIdx->aSample[j];
75891      if( p->eType==SQLITE_TEXT || p->eType==SQLITE_BLOB ){
75892        sqlite3DbFree(db, p->u.z);
75893      }
75894    }
75895    sqlite3DbFree(db, pIdx->aSample);
75896  }
75897#else
75898  UNUSED_PARAMETER(db);
75899  UNUSED_PARAMETER(pIdx);
75900#endif
75901}
75902
75903/*
75904** Load the content of the sqlite_stat1 and sqlite_stat2 tables. The
75905** contents of sqlite_stat1 are used to populate the Index.aiRowEst[]
75906** arrays. The contents of sqlite_stat2 are used to populate the
75907** Index.aSample[] arrays.
75908**
75909** If the sqlite_stat1 table is not present in the database, SQLITE_ERROR
75910** is returned. In this case, even if SQLITE_ENABLE_STAT2 was defined
75911** during compilation and the sqlite_stat2 table is present, no data is
75912** read from it.
75913**
75914** If SQLITE_ENABLE_STAT2 was defined during compilation and the
75915** sqlite_stat2 table is not present in the database, SQLITE_ERROR is
75916** returned. However, in this case, data is read from the sqlite_stat1
75917** table (if it is present) before returning.
75918**
75919** If an OOM error occurs, this function always sets db->mallocFailed.
75920** This means if the caller does not care about other errors, the return
75921** code may be ignored.
75922*/
75923SQLITE_PRIVATE int sqlite3AnalysisLoad(sqlite3 *db, int iDb){
75924  analysisInfo sInfo;
75925  HashElem *i;
75926  char *zSql;
75927  int rc;
75928
75929  assert( iDb>=0 && iDb<db->nDb );
75930  assert( db->aDb[iDb].pBt!=0 );
75931
75932  /* Clear any prior statistics */
75933  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
75934  for(i=sqliteHashFirst(&db->aDb[iDb].pSchema->idxHash);i;i=sqliteHashNext(i)){
75935    Index *pIdx = sqliteHashData(i);
75936    sqlite3DefaultRowEst(pIdx);
75937    sqlite3DeleteIndexSamples(db, pIdx);
75938    pIdx->aSample = 0;
75939  }
75940
75941  /* Check to make sure the sqlite_stat1 table exists */
75942  sInfo.db = db;
75943  sInfo.zDatabase = db->aDb[iDb].zName;
75944  if( sqlite3FindTable(db, "sqlite_stat1", sInfo.zDatabase)==0 ){
75945    return SQLITE_ERROR;
75946  }
75947
75948  /* Load new statistics out of the sqlite_stat1 table */
75949  zSql = sqlite3MPrintf(db,
75950      "SELECT tbl, idx, stat FROM %Q.sqlite_stat1", sInfo.zDatabase);
75951  if( zSql==0 ){
75952    rc = SQLITE_NOMEM;
75953  }else{
75954    rc = sqlite3_exec(db, zSql, analysisLoader, &sInfo, 0);
75955    sqlite3DbFree(db, zSql);
75956  }
75957
75958
75959  /* Load the statistics from the sqlite_stat2 table. */
75960#ifdef SQLITE_ENABLE_STAT2
75961  if( rc==SQLITE_OK && !sqlite3FindTable(db, "sqlite_stat2", sInfo.zDatabase) ){
75962    rc = SQLITE_ERROR;
75963  }
75964  if( rc==SQLITE_OK ){
75965    sqlite3_stmt *pStmt = 0;
75966
75967    zSql = sqlite3MPrintf(db,
75968        "SELECT idx,sampleno,sample FROM %Q.sqlite_stat2", sInfo.zDatabase);
75969    if( !zSql ){
75970      rc = SQLITE_NOMEM;
75971    }else{
75972      rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
75973      sqlite3DbFree(db, zSql);
75974    }
75975
75976    if( rc==SQLITE_OK ){
75977      while( sqlite3_step(pStmt)==SQLITE_ROW ){
75978        char *zIndex;   /* Index name */
75979        Index *pIdx;    /* Pointer to the index object */
75980
75981        zIndex = (char *)sqlite3_column_text(pStmt, 0);
75982        pIdx = zIndex ? sqlite3FindIndex(db, zIndex, sInfo.zDatabase) : 0;
75983        if( pIdx ){
75984          int iSample = sqlite3_column_int(pStmt, 1);
75985          if( iSample<SQLITE_INDEX_SAMPLES && iSample>=0 ){
75986            int eType = sqlite3_column_type(pStmt, 2);
75987
75988            if( pIdx->aSample==0 ){
75989              static const int sz = sizeof(IndexSample)*SQLITE_INDEX_SAMPLES;
75990              pIdx->aSample = (IndexSample *)sqlite3DbMallocRaw(0, sz);
75991              if( pIdx->aSample==0 ){
75992                db->mallocFailed = 1;
75993                break;
75994              }
75995	      memset(pIdx->aSample, 0, sz);
75996            }
75997
75998            assert( pIdx->aSample );
75999            {
76000              IndexSample *pSample = &pIdx->aSample[iSample];
76001              pSample->eType = (u8)eType;
76002              if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
76003                pSample->u.r = sqlite3_column_double(pStmt, 2);
76004              }else if( eType==SQLITE_TEXT || eType==SQLITE_BLOB ){
76005                const char *z = (const char *)(
76006                    (eType==SQLITE_BLOB) ?
76007                    sqlite3_column_blob(pStmt, 2):
76008                    sqlite3_column_text(pStmt, 2)
76009                );
76010                int n = sqlite3_column_bytes(pStmt, 2);
76011                if( n>24 ){
76012                  n = 24;
76013                }
76014                pSample->nByte = (u8)n;
76015                if( n < 1){
76016                  pSample->u.z = 0;
76017                }else{
76018                  pSample->u.z = sqlite3DbStrNDup(0, z, n);
76019                  if( pSample->u.z==0 ){
76020                    db->mallocFailed = 1;
76021                    break;
76022                  }
76023                }
76024              }
76025            }
76026          }
76027        }
76028      }
76029      rc = sqlite3_finalize(pStmt);
76030    }
76031  }
76032#endif
76033
76034  if( rc==SQLITE_NOMEM ){
76035    db->mallocFailed = 1;
76036  }
76037  return rc;
76038}
76039
76040
76041#endif /* SQLITE_OMIT_ANALYZE */
76042
76043/************** End of analyze.c *********************************************/
76044/************** Begin file attach.c ******************************************/
76045/*
76046** 2003 April 6
76047**
76048** The author disclaims copyright to this source code.  In place of
76049** a legal notice, here is a blessing:
76050**
76051**    May you do good and not evil.
76052**    May you find forgiveness for yourself and forgive others.
76053**    May you share freely, never taking more than you give.
76054**
76055*************************************************************************
76056** This file contains code used to implement the ATTACH and DETACH commands.
76057*/
76058
76059#ifndef SQLITE_OMIT_ATTACH
76060/*
76061** Resolve an expression that was part of an ATTACH or DETACH statement. This
76062** is slightly different from resolving a normal SQL expression, because simple
76063** identifiers are treated as strings, not possible column names or aliases.
76064**
76065** i.e. if the parser sees:
76066**
76067**     ATTACH DATABASE abc AS def
76068**
76069** it treats the two expressions as literal strings 'abc' and 'def' instead of
76070** looking for columns of the same name.
76071**
76072** This only applies to the root node of pExpr, so the statement:
76073**
76074**     ATTACH DATABASE abc||def AS 'db2'
76075**
76076** will fail because neither abc or def can be resolved.
76077*/
76078static int resolveAttachExpr(NameContext *pName, Expr *pExpr)
76079{
76080  int rc = SQLITE_OK;
76081  if( pExpr ){
76082    if( pExpr->op!=TK_ID ){
76083      rc = sqlite3ResolveExprNames(pName, pExpr);
76084      if( rc==SQLITE_OK && !sqlite3ExprIsConstant(pExpr) ){
76085        sqlite3ErrorMsg(pName->pParse, "invalid name: \"%s\"", pExpr->u.zToken);
76086        return SQLITE_ERROR;
76087      }
76088    }else{
76089      pExpr->op = TK_STRING;
76090    }
76091  }
76092  return rc;
76093}
76094
76095/*
76096** An SQL user-function registered to do the work of an ATTACH statement. The
76097** three arguments to the function come directly from an attach statement:
76098**
76099**     ATTACH DATABASE x AS y KEY z
76100**
76101**     SELECT sqlite_attach(x, y, z)
76102**
76103** If the optional "KEY z" syntax is omitted, an SQL NULL is passed as the
76104** third argument.
76105*/
76106static void attachFunc(
76107  sqlite3_context *context,
76108  int NotUsed,
76109  sqlite3_value **argv
76110){
76111  int i;
76112  int rc = 0;
76113  sqlite3 *db = sqlite3_context_db_handle(context);
76114  const char *zName;
76115  const char *zFile;
76116  Db *aNew;
76117  char *zErrDyn = 0;
76118
76119  UNUSED_PARAMETER(NotUsed);
76120
76121  zFile = (const char *)sqlite3_value_text(argv[0]);
76122  zName = (const char *)sqlite3_value_text(argv[1]);
76123  if( zFile==0 ) zFile = "";
76124  if( zName==0 ) zName = "";
76125
76126  /* Check for the following errors:
76127  **
76128  **     * Too many attached databases,
76129  **     * Transaction currently open
76130  **     * Specified database name already being used.
76131  */
76132  if( db->nDb>=db->aLimit[SQLITE_LIMIT_ATTACHED]+2 ){
76133    zErrDyn = sqlite3MPrintf(db, "too many attached databases - max %d",
76134      db->aLimit[SQLITE_LIMIT_ATTACHED]
76135    );
76136    goto attach_error;
76137  }
76138  if( !db->autoCommit ){
76139    zErrDyn = sqlite3MPrintf(db, "cannot ATTACH database within transaction");
76140    goto attach_error;
76141  }
76142  for(i=0; i<db->nDb; i++){
76143    char *z = db->aDb[i].zName;
76144    assert( z && zName );
76145    if( sqlite3StrICmp(z, zName)==0 ){
76146      zErrDyn = sqlite3MPrintf(db, "database %s is already in use", zName);
76147      goto attach_error;
76148    }
76149  }
76150
76151  /* Allocate the new entry in the db->aDb[] array and initialise the schema
76152  ** hash tables.
76153  */
76154  if( db->aDb==db->aDbStatic ){
76155    aNew = sqlite3DbMallocRaw(db, sizeof(db->aDb[0])*3 );
76156    if( aNew==0 ) return;
76157    memcpy(aNew, db->aDb, sizeof(db->aDb[0])*2);
76158  }else{
76159    aNew = sqlite3DbRealloc(db, db->aDb, sizeof(db->aDb[0])*(db->nDb+1) );
76160    if( aNew==0 ) return;
76161  }
76162  db->aDb = aNew;
76163  aNew = &db->aDb[db->nDb];
76164  memset(aNew, 0, sizeof(*aNew));
76165
76166  /* Open the database file. If the btree is successfully opened, use
76167  ** it to obtain the database schema. At this point the schema may
76168  ** or may not be initialised.
76169  */
76170  rc = sqlite3BtreeOpen(zFile, db, &aNew->pBt, 0,
76171                        db->openFlags | SQLITE_OPEN_MAIN_DB);
76172  db->nDb++;
76173  if( rc==SQLITE_CONSTRAINT ){
76174    rc = SQLITE_ERROR;
76175    zErrDyn = sqlite3MPrintf(db, "database is already attached");
76176  }else if( rc==SQLITE_OK ){
76177    Pager *pPager;
76178    aNew->pSchema = sqlite3SchemaGet(db, aNew->pBt);
76179    if( !aNew->pSchema ){
76180      rc = SQLITE_NOMEM;
76181    }else if( aNew->pSchema->file_format && aNew->pSchema->enc!=ENC(db) ){
76182      zErrDyn = sqlite3MPrintf(db,
76183        "attached databases must use the same text encoding as main database");
76184      rc = SQLITE_ERROR;
76185    }
76186    pPager = sqlite3BtreePager(aNew->pBt);
76187    sqlite3PagerLockingMode(pPager, db->dfltLockMode);
76188    sqlite3BtreeSecureDelete(aNew->pBt,
76189                             sqlite3BtreeSecureDelete(db->aDb[0].pBt,-1) );
76190  }
76191  aNew->safety_level = 3;
76192  aNew->zName = sqlite3DbStrDup(db, zName);
76193  if( rc==SQLITE_OK && aNew->zName==0 ){
76194    rc = SQLITE_NOMEM;
76195  }
76196
76197
76198#ifdef SQLITE_HAS_CODEC
76199  if( rc==SQLITE_OK ){
76200    extern int sqlite3CodecAttach(sqlite3*, int, const void*, int);
76201    extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*);
76202    int nKey;
76203    char *zKey;
76204    int t = sqlite3_value_type(argv[2]);
76205    switch( t ){
76206      case SQLITE_INTEGER:
76207      case SQLITE_FLOAT:
76208        zErrDyn = sqlite3DbStrDup(db, "Invalid key value");
76209        rc = SQLITE_ERROR;
76210        break;
76211
76212      case SQLITE_TEXT:
76213      case SQLITE_BLOB:
76214        nKey = sqlite3_value_bytes(argv[2]);
76215        zKey = (char *)sqlite3_value_blob(argv[2]);
76216        rc = sqlite3CodecAttach(db, db->nDb-1, zKey, nKey);
76217        break;
76218
76219      case SQLITE_NULL:
76220        /* No key specified.  Use the key from the main database */
76221        sqlite3CodecGetKey(db, 0, (void**)&zKey, &nKey);
76222        if( nKey>0 || sqlite3BtreeGetReserve(db->aDb[0].pBt)>0 ){
76223          rc = sqlite3CodecAttach(db, db->nDb-1, zKey, nKey);
76224        }
76225        break;
76226    }
76227  }
76228#endif
76229
76230  /* If the file was opened successfully, read the schema for the new database.
76231  ** If this fails, or if opening the file failed, then close the file and
76232  ** remove the entry from the db->aDb[] array. i.e. put everything back the way
76233  ** we found it.
76234  */
76235  if( rc==SQLITE_OK ){
76236    sqlite3BtreeEnterAll(db);
76237    rc = sqlite3Init(db, &zErrDyn);
76238    sqlite3BtreeLeaveAll(db);
76239  }
76240  if( rc ){
76241    int iDb = db->nDb - 1;
76242    assert( iDb>=2 );
76243    if( db->aDb[iDb].pBt ){
76244      sqlite3BtreeClose(db->aDb[iDb].pBt);
76245      db->aDb[iDb].pBt = 0;
76246      db->aDb[iDb].pSchema = 0;
76247    }
76248    sqlite3ResetInternalSchema(db, -1);
76249    db->nDb = iDb;
76250    if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
76251      db->mallocFailed = 1;
76252      sqlite3DbFree(db, zErrDyn);
76253      zErrDyn = sqlite3MPrintf(db, "out of memory");
76254    }else if( zErrDyn==0 ){
76255      zErrDyn = sqlite3MPrintf(db, "unable to open database: %s", zFile);
76256    }
76257    goto attach_error;
76258  }
76259
76260  return;
76261
76262attach_error:
76263  /* Return an error if we get here */
76264  if( zErrDyn ){
76265    sqlite3_result_error(context, zErrDyn, -1);
76266    sqlite3DbFree(db, zErrDyn);
76267  }
76268  if( rc ) sqlite3_result_error_code(context, rc);
76269}
76270
76271/*
76272** An SQL user-function registered to do the work of an DETACH statement. The
76273** three arguments to the function come directly from a detach statement:
76274**
76275**     DETACH DATABASE x
76276**
76277**     SELECT sqlite_detach(x)
76278*/
76279static void detachFunc(
76280  sqlite3_context *context,
76281  int NotUsed,
76282  sqlite3_value **argv
76283){
76284  const char *zName = (const char *)sqlite3_value_text(argv[0]);
76285  sqlite3 *db = sqlite3_context_db_handle(context);
76286  int i;
76287  Db *pDb = 0;
76288  char zErr[128];
76289
76290  UNUSED_PARAMETER(NotUsed);
76291
76292  if( zName==0 ) zName = "";
76293  for(i=0; i<db->nDb; i++){
76294    pDb = &db->aDb[i];
76295    if( pDb->pBt==0 ) continue;
76296    if( sqlite3StrICmp(pDb->zName, zName)==0 ) break;
76297  }
76298
76299  if( i>=db->nDb ){
76300    sqlite3_snprintf(sizeof(zErr),zErr, "no such database: %s", zName);
76301    goto detach_error;
76302  }
76303  if( i<2 ){
76304    sqlite3_snprintf(sizeof(zErr),zErr, "cannot detach database %s", zName);
76305    goto detach_error;
76306  }
76307  if( !db->autoCommit ){
76308    sqlite3_snprintf(sizeof(zErr), zErr,
76309                     "cannot DETACH database within transaction");
76310    goto detach_error;
76311  }
76312  if( sqlite3BtreeIsInReadTrans(pDb->pBt) || sqlite3BtreeIsInBackup(pDb->pBt) ){
76313    sqlite3_snprintf(sizeof(zErr),zErr, "database %s is locked", zName);
76314    goto detach_error;
76315  }
76316
76317  sqlite3BtreeClose(pDb->pBt);
76318  pDb->pBt = 0;
76319  pDb->pSchema = 0;
76320  sqlite3ResetInternalSchema(db, -1);
76321  return;
76322
76323detach_error:
76324  sqlite3_result_error(context, zErr, -1);
76325}
76326
76327/*
76328** This procedure generates VDBE code for a single invocation of either the
76329** sqlite_detach() or sqlite_attach() SQL user functions.
76330*/
76331static void codeAttach(
76332  Parse *pParse,       /* The parser context */
76333  int type,            /* Either SQLITE_ATTACH or SQLITE_DETACH */
76334  FuncDef const *pFunc,/* FuncDef wrapper for detachFunc() or attachFunc() */
76335  Expr *pAuthArg,      /* Expression to pass to authorization callback */
76336  Expr *pFilename,     /* Name of database file */
76337  Expr *pDbname,       /* Name of the database to use internally */
76338  Expr *pKey           /* Database key for encryption extension */
76339){
76340  int rc;
76341  NameContext sName;
76342  Vdbe *v;
76343  sqlite3* db = pParse->db;
76344  int regArgs;
76345
76346  memset(&sName, 0, sizeof(NameContext));
76347  sName.pParse = pParse;
76348
76349  if(
76350      SQLITE_OK!=(rc = resolveAttachExpr(&sName, pFilename)) ||
76351      SQLITE_OK!=(rc = resolveAttachExpr(&sName, pDbname)) ||
76352      SQLITE_OK!=(rc = resolveAttachExpr(&sName, pKey))
76353  ){
76354    pParse->nErr++;
76355    goto attach_end;
76356  }
76357
76358#ifndef SQLITE_OMIT_AUTHORIZATION
76359  if( pAuthArg ){
76360    char *zAuthArg;
76361    if( pAuthArg->op==TK_STRING ){
76362      zAuthArg = pAuthArg->u.zToken;
76363    }else{
76364      zAuthArg = 0;
76365    }
76366    rc = sqlite3AuthCheck(pParse, type, zAuthArg, 0, 0);
76367    if(rc!=SQLITE_OK ){
76368      goto attach_end;
76369    }
76370  }
76371#endif /* SQLITE_OMIT_AUTHORIZATION */
76372
76373
76374  v = sqlite3GetVdbe(pParse);
76375  regArgs = sqlite3GetTempRange(pParse, 4);
76376  sqlite3ExprCode(pParse, pFilename, regArgs);
76377  sqlite3ExprCode(pParse, pDbname, regArgs+1);
76378  sqlite3ExprCode(pParse, pKey, regArgs+2);
76379
76380  assert( v || db->mallocFailed );
76381  if( v ){
76382    sqlite3VdbeAddOp3(v, OP_Function, 0, regArgs+3-pFunc->nArg, regArgs+3);
76383    assert( pFunc->nArg==-1 || (pFunc->nArg&0xff)==pFunc->nArg );
76384    sqlite3VdbeChangeP5(v, (u8)(pFunc->nArg));
76385    sqlite3VdbeChangeP4(v, -1, (char *)pFunc, P4_FUNCDEF);
76386
76387    /* Code an OP_Expire. For an ATTACH statement, set P1 to true (expire this
76388    ** statement only). For DETACH, set it to false (expire all existing
76389    ** statements).
76390    */
76391    sqlite3VdbeAddOp1(v, OP_Expire, (type==SQLITE_ATTACH));
76392  }
76393
76394attach_end:
76395  sqlite3ExprDelete(db, pFilename);
76396  sqlite3ExprDelete(db, pDbname);
76397  sqlite3ExprDelete(db, pKey);
76398}
76399
76400/*
76401** Called by the parser to compile a DETACH statement.
76402**
76403**     DETACH pDbname
76404*/
76405SQLITE_PRIVATE void sqlite3Detach(Parse *pParse, Expr *pDbname){
76406  static const FuncDef detach_func = {
76407    1,                /* nArg */
76408    SQLITE_UTF8,      /* iPrefEnc */
76409    0,                /* flags */
76410    0,                /* pUserData */
76411    0,                /* pNext */
76412    detachFunc,       /* xFunc */
76413    0,                /* xStep */
76414    0,                /* xFinalize */
76415    "sqlite_detach",  /* zName */
76416    0,                /* pHash */
76417    0                 /* pDestructor */
76418  };
76419  codeAttach(pParse, SQLITE_DETACH, &detach_func, pDbname, 0, 0, pDbname);
76420}
76421
76422/*
76423** Called by the parser to compile an ATTACH statement.
76424**
76425**     ATTACH p AS pDbname KEY pKey
76426*/
76427SQLITE_PRIVATE void sqlite3Attach(Parse *pParse, Expr *p, Expr *pDbname, Expr *pKey){
76428  static const FuncDef attach_func = {
76429    3,                /* nArg */
76430    SQLITE_UTF8,      /* iPrefEnc */
76431    0,                /* flags */
76432    0,                /* pUserData */
76433    0,                /* pNext */
76434    attachFunc,       /* xFunc */
76435    0,                /* xStep */
76436    0,                /* xFinalize */
76437    "sqlite_attach",  /* zName */
76438    0,                /* pHash */
76439    0                 /* pDestructor */
76440  };
76441  codeAttach(pParse, SQLITE_ATTACH, &attach_func, p, p, pDbname, pKey);
76442}
76443#endif /* SQLITE_OMIT_ATTACH */
76444
76445/*
76446** Initialize a DbFixer structure.  This routine must be called prior
76447** to passing the structure to one of the sqliteFixAAAA() routines below.
76448**
76449** The return value indicates whether or not fixation is required.  TRUE
76450** means we do need to fix the database references, FALSE means we do not.
76451*/
76452SQLITE_PRIVATE int sqlite3FixInit(
76453  DbFixer *pFix,      /* The fixer to be initialized */
76454  Parse *pParse,      /* Error messages will be written here */
76455  int iDb,            /* This is the database that must be used */
76456  const char *zType,  /* "view", "trigger", or "index" */
76457  const Token *pName  /* Name of the view, trigger, or index */
76458){
76459  sqlite3 *db;
76460
76461  if( NEVER(iDb<0) || iDb==1 ) return 0;
76462  db = pParse->db;
76463  assert( db->nDb>iDb );
76464  pFix->pParse = pParse;
76465  pFix->zDb = db->aDb[iDb].zName;
76466  pFix->zType = zType;
76467  pFix->pName = pName;
76468  return 1;
76469}
76470
76471/*
76472** The following set of routines walk through the parse tree and assign
76473** a specific database to all table references where the database name
76474** was left unspecified in the original SQL statement.  The pFix structure
76475** must have been initialized by a prior call to sqlite3FixInit().
76476**
76477** These routines are used to make sure that an index, trigger, or
76478** view in one database does not refer to objects in a different database.
76479** (Exception: indices, triggers, and views in the TEMP database are
76480** allowed to refer to anything.)  If a reference is explicitly made
76481** to an object in a different database, an error message is added to
76482** pParse->zErrMsg and these routines return non-zero.  If everything
76483** checks out, these routines return 0.
76484*/
76485SQLITE_PRIVATE int sqlite3FixSrcList(
76486  DbFixer *pFix,       /* Context of the fixation */
76487  SrcList *pList       /* The Source list to check and modify */
76488){
76489  int i;
76490  const char *zDb;
76491  struct SrcList_item *pItem;
76492
76493  if( NEVER(pList==0) ) return 0;
76494  zDb = pFix->zDb;
76495  for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
76496    if( pItem->zDatabase==0 ){
76497      pItem->zDatabase = sqlite3DbStrDup(pFix->pParse->db, zDb);
76498    }else if( sqlite3StrICmp(pItem->zDatabase,zDb)!=0 ){
76499      sqlite3ErrorMsg(pFix->pParse,
76500         "%s %T cannot reference objects in database %s",
76501         pFix->zType, pFix->pName, pItem->zDatabase);
76502      return 1;
76503    }
76504#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)
76505    if( sqlite3FixSelect(pFix, pItem->pSelect) ) return 1;
76506    if( sqlite3FixExpr(pFix, pItem->pOn) ) return 1;
76507#endif
76508  }
76509  return 0;
76510}
76511#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)
76512SQLITE_PRIVATE int sqlite3FixSelect(
76513  DbFixer *pFix,       /* Context of the fixation */
76514  Select *pSelect      /* The SELECT statement to be fixed to one database */
76515){
76516  while( pSelect ){
76517    if( sqlite3FixExprList(pFix, pSelect->pEList) ){
76518      return 1;
76519    }
76520    if( sqlite3FixSrcList(pFix, pSelect->pSrc) ){
76521      return 1;
76522    }
76523    if( sqlite3FixExpr(pFix, pSelect->pWhere) ){
76524      return 1;
76525    }
76526    if( sqlite3FixExpr(pFix, pSelect->pHaving) ){
76527      return 1;
76528    }
76529    pSelect = pSelect->pPrior;
76530  }
76531  return 0;
76532}
76533SQLITE_PRIVATE int sqlite3FixExpr(
76534  DbFixer *pFix,     /* Context of the fixation */
76535  Expr *pExpr        /* The expression to be fixed to one database */
76536){
76537  while( pExpr ){
76538    if( ExprHasAnyProperty(pExpr, EP_TokenOnly) ) break;
76539    if( ExprHasProperty(pExpr, EP_xIsSelect) ){
76540      if( sqlite3FixSelect(pFix, pExpr->x.pSelect) ) return 1;
76541    }else{
76542      if( sqlite3FixExprList(pFix, pExpr->x.pList) ) return 1;
76543    }
76544    if( sqlite3FixExpr(pFix, pExpr->pRight) ){
76545      return 1;
76546    }
76547    pExpr = pExpr->pLeft;
76548  }
76549  return 0;
76550}
76551SQLITE_PRIVATE int sqlite3FixExprList(
76552  DbFixer *pFix,     /* Context of the fixation */
76553  ExprList *pList    /* The expression to be fixed to one database */
76554){
76555  int i;
76556  struct ExprList_item *pItem;
76557  if( pList==0 ) return 0;
76558  for(i=0, pItem=pList->a; i<pList->nExpr; i++, pItem++){
76559    if( sqlite3FixExpr(pFix, pItem->pExpr) ){
76560      return 1;
76561    }
76562  }
76563  return 0;
76564}
76565#endif
76566
76567#ifndef SQLITE_OMIT_TRIGGER
76568SQLITE_PRIVATE int sqlite3FixTriggerStep(
76569  DbFixer *pFix,     /* Context of the fixation */
76570  TriggerStep *pStep /* The trigger step be fixed to one database */
76571){
76572  while( pStep ){
76573    if( sqlite3FixSelect(pFix, pStep->pSelect) ){
76574      return 1;
76575    }
76576    if( sqlite3FixExpr(pFix, pStep->pWhere) ){
76577      return 1;
76578    }
76579    if( sqlite3FixExprList(pFix, pStep->pExprList) ){
76580      return 1;
76581    }
76582    pStep = pStep->pNext;
76583  }
76584  return 0;
76585}
76586#endif
76587
76588/************** End of attach.c **********************************************/
76589/************** Begin file auth.c ********************************************/
76590/*
76591** 2003 January 11
76592**
76593** The author disclaims copyright to this source code.  In place of
76594** a legal notice, here is a blessing:
76595**
76596**    May you do good and not evil.
76597**    May you find forgiveness for yourself and forgive others.
76598**    May you share freely, never taking more than you give.
76599**
76600*************************************************************************
76601** This file contains code used to implement the sqlite3_set_authorizer()
76602** API.  This facility is an optional feature of the library.  Embedded
76603** systems that do not need this facility may omit it by recompiling
76604** the library with -DSQLITE_OMIT_AUTHORIZATION=1
76605*/
76606
76607/*
76608** All of the code in this file may be omitted by defining a single
76609** macro.
76610*/
76611#ifndef SQLITE_OMIT_AUTHORIZATION
76612
76613/*
76614** Set or clear the access authorization function.
76615**
76616** The access authorization function is be called during the compilation
76617** phase to verify that the user has read and/or write access permission on
76618** various fields of the database.  The first argument to the auth function
76619** is a copy of the 3rd argument to this routine.  The second argument
76620** to the auth function is one of these constants:
76621**
76622**       SQLITE_CREATE_INDEX
76623**       SQLITE_CREATE_TABLE
76624**       SQLITE_CREATE_TEMP_INDEX
76625**       SQLITE_CREATE_TEMP_TABLE
76626**       SQLITE_CREATE_TEMP_TRIGGER
76627**       SQLITE_CREATE_TEMP_VIEW
76628**       SQLITE_CREATE_TRIGGER
76629**       SQLITE_CREATE_VIEW
76630**       SQLITE_DELETE
76631**       SQLITE_DROP_INDEX
76632**       SQLITE_DROP_TABLE
76633**       SQLITE_DROP_TEMP_INDEX
76634**       SQLITE_DROP_TEMP_TABLE
76635**       SQLITE_DROP_TEMP_TRIGGER
76636**       SQLITE_DROP_TEMP_VIEW
76637**       SQLITE_DROP_TRIGGER
76638**       SQLITE_DROP_VIEW
76639**       SQLITE_INSERT
76640**       SQLITE_PRAGMA
76641**       SQLITE_READ
76642**       SQLITE_SELECT
76643**       SQLITE_TRANSACTION
76644**       SQLITE_UPDATE
76645**
76646** The third and fourth arguments to the auth function are the name of
76647** the table and the column that are being accessed.  The auth function
76648** should return either SQLITE_OK, SQLITE_DENY, or SQLITE_IGNORE.  If
76649** SQLITE_OK is returned, it means that access is allowed.  SQLITE_DENY
76650** means that the SQL statement will never-run - the sqlite3_exec() call
76651** will return with an error.  SQLITE_IGNORE means that the SQL statement
76652** should run but attempts to read the specified column will return NULL
76653** and attempts to write the column will be ignored.
76654**
76655** Setting the auth function to NULL disables this hook.  The default
76656** setting of the auth function is NULL.
76657*/
76658SQLITE_API int sqlite3_set_authorizer(
76659  sqlite3 *db,
76660  int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
76661  void *pArg
76662){
76663  sqlite3_mutex_enter(db->mutex);
76664  db->xAuth = xAuth;
76665  db->pAuthArg = pArg;
76666  sqlite3ExpirePreparedStatements(db);
76667  sqlite3_mutex_leave(db->mutex);
76668  return SQLITE_OK;
76669}
76670
76671/*
76672** Write an error message into pParse->zErrMsg that explains that the
76673** user-supplied authorization function returned an illegal value.
76674*/
76675static void sqliteAuthBadReturnCode(Parse *pParse){
76676  sqlite3ErrorMsg(pParse, "authorizer malfunction");
76677  pParse->rc = SQLITE_ERROR;
76678}
76679
76680/*
76681** Invoke the authorization callback for permission to read column zCol from
76682** table zTab in database zDb. This function assumes that an authorization
76683** callback has been registered (i.e. that sqlite3.xAuth is not NULL).
76684**
76685** If SQLITE_IGNORE is returned and pExpr is not NULL, then pExpr is changed
76686** to an SQL NULL expression. Otherwise, if pExpr is NULL, then SQLITE_IGNORE
76687** is treated as SQLITE_DENY. In this case an error is left in pParse.
76688*/
76689SQLITE_PRIVATE int sqlite3AuthReadCol(
76690  Parse *pParse,                  /* The parser context */
76691  const char *zTab,               /* Table name */
76692  const char *zCol,               /* Column name */
76693  int iDb                         /* Index of containing database. */
76694){
76695  sqlite3 *db = pParse->db;       /* Database handle */
76696  char *zDb = db->aDb[iDb].zName; /* Name of attached database */
76697  int rc;                         /* Auth callback return code */
76698
76699  rc = db->xAuth(db->pAuthArg, SQLITE_READ, zTab,zCol,zDb,pParse->zAuthContext);
76700  if( rc==SQLITE_DENY ){
76701    if( db->nDb>2 || iDb!=0 ){
76702      sqlite3ErrorMsg(pParse, "access to %s.%s.%s is prohibited",zDb,zTab,zCol);
76703    }else{
76704      sqlite3ErrorMsg(pParse, "access to %s.%s is prohibited", zTab, zCol);
76705    }
76706    pParse->rc = SQLITE_AUTH;
76707  }else if( rc!=SQLITE_IGNORE && rc!=SQLITE_OK ){
76708    sqliteAuthBadReturnCode(pParse);
76709  }
76710  return rc;
76711}
76712
76713/*
76714** The pExpr should be a TK_COLUMN expression.  The table referred to
76715** is in pTabList or else it is the NEW or OLD table of a trigger.
76716** Check to see if it is OK to read this particular column.
76717**
76718** If the auth function returns SQLITE_IGNORE, change the TK_COLUMN
76719** instruction into a TK_NULL.  If the auth function returns SQLITE_DENY,
76720** then generate an error.
76721*/
76722SQLITE_PRIVATE void sqlite3AuthRead(
76723  Parse *pParse,        /* The parser context */
76724  Expr *pExpr,          /* The expression to check authorization on */
76725  Schema *pSchema,      /* The schema of the expression */
76726  SrcList *pTabList     /* All table that pExpr might refer to */
76727){
76728  sqlite3 *db = pParse->db;
76729  Table *pTab = 0;      /* The table being read */
76730  const char *zCol;     /* Name of the column of the table */
76731  int iSrc;             /* Index in pTabList->a[] of table being read */
76732  int iDb;              /* The index of the database the expression refers to */
76733  int iCol;             /* Index of column in table */
76734
76735  if( db->xAuth==0 ) return;
76736  iDb = sqlite3SchemaToIndex(pParse->db, pSchema);
76737  if( iDb<0 ){
76738    /* An attempt to read a column out of a subquery or other
76739    ** temporary table. */
76740    return;
76741  }
76742
76743  assert( pExpr->op==TK_COLUMN || pExpr->op==TK_TRIGGER );
76744  if( pExpr->op==TK_TRIGGER ){
76745    pTab = pParse->pTriggerTab;
76746  }else{
76747    assert( pTabList );
76748    for(iSrc=0; ALWAYS(iSrc<pTabList->nSrc); iSrc++){
76749      if( pExpr->iTable==pTabList->a[iSrc].iCursor ){
76750        pTab = pTabList->a[iSrc].pTab;
76751        break;
76752      }
76753    }
76754  }
76755  iCol = pExpr->iColumn;
76756  if( NEVER(pTab==0) ) return;
76757
76758  if( iCol>=0 ){
76759    assert( iCol<pTab->nCol );
76760    zCol = pTab->aCol[iCol].zName;
76761  }else if( pTab->iPKey>=0 ){
76762    assert( pTab->iPKey<pTab->nCol );
76763    zCol = pTab->aCol[pTab->iPKey].zName;
76764  }else{
76765    zCol = "ROWID";
76766  }
76767  assert( iDb>=0 && iDb<db->nDb );
76768  if( SQLITE_IGNORE==sqlite3AuthReadCol(pParse, pTab->zName, zCol, iDb) ){
76769    pExpr->op = TK_NULL;
76770  }
76771}
76772
76773/*
76774** Do an authorization check using the code and arguments given.  Return
76775** either SQLITE_OK (zero) or SQLITE_IGNORE or SQLITE_DENY.  If SQLITE_DENY
76776** is returned, then the error count and error message in pParse are
76777** modified appropriately.
76778*/
76779SQLITE_PRIVATE int sqlite3AuthCheck(
76780  Parse *pParse,
76781  int code,
76782  const char *zArg1,
76783  const char *zArg2,
76784  const char *zArg3
76785){
76786  sqlite3 *db = pParse->db;
76787  int rc;
76788
76789  /* Don't do any authorization checks if the database is initialising
76790  ** or if the parser is being invoked from within sqlite3_declare_vtab.
76791  */
76792  if( db->init.busy || IN_DECLARE_VTAB ){
76793    return SQLITE_OK;
76794  }
76795
76796  if( db->xAuth==0 ){
76797    return SQLITE_OK;
76798  }
76799  rc = db->xAuth(db->pAuthArg, code, zArg1, zArg2, zArg3, pParse->zAuthContext);
76800  if( rc==SQLITE_DENY ){
76801    sqlite3ErrorMsg(pParse, "not authorized");
76802    pParse->rc = SQLITE_AUTH;
76803  }else if( rc!=SQLITE_OK && rc!=SQLITE_IGNORE ){
76804    rc = SQLITE_DENY;
76805    sqliteAuthBadReturnCode(pParse);
76806  }
76807  return rc;
76808}
76809
76810/*
76811** Push an authorization context.  After this routine is called, the
76812** zArg3 argument to authorization callbacks will be zContext until
76813** popped.  Or if pParse==0, this routine is a no-op.
76814*/
76815SQLITE_PRIVATE void sqlite3AuthContextPush(
76816  Parse *pParse,
76817  AuthContext *pContext,
76818  const char *zContext
76819){
76820  assert( pParse );
76821  pContext->pParse = pParse;
76822  pContext->zAuthContext = pParse->zAuthContext;
76823  pParse->zAuthContext = zContext;
76824}
76825
76826/*
76827** Pop an authorization context that was previously pushed
76828** by sqlite3AuthContextPush
76829*/
76830SQLITE_PRIVATE void sqlite3AuthContextPop(AuthContext *pContext){
76831  if( pContext->pParse ){
76832    pContext->pParse->zAuthContext = pContext->zAuthContext;
76833    pContext->pParse = 0;
76834  }
76835}
76836
76837#endif /* SQLITE_OMIT_AUTHORIZATION */
76838
76839/************** End of auth.c ************************************************/
76840/************** Begin file build.c *******************************************/
76841/*
76842** 2001 September 15
76843**
76844** The author disclaims copyright to this source code.  In place of
76845** a legal notice, here is a blessing:
76846**
76847**    May you do good and not evil.
76848**    May you find forgiveness for yourself and forgive others.
76849**    May you share freely, never taking more than you give.
76850**
76851*************************************************************************
76852** This file contains C code routines that are called by the SQLite parser
76853** when syntax rules are reduced.  The routines in this file handle the
76854** following kinds of SQL syntax:
76855**
76856**     CREATE TABLE
76857**     DROP TABLE
76858**     CREATE INDEX
76859**     DROP INDEX
76860**     creating ID lists
76861**     BEGIN TRANSACTION
76862**     COMMIT
76863**     ROLLBACK
76864*/
76865
76866/*
76867** This routine is called when a new SQL statement is beginning to
76868** be parsed.  Initialize the pParse structure as needed.
76869*/
76870SQLITE_PRIVATE void sqlite3BeginParse(Parse *pParse, int explainFlag){
76871  pParse->explain = (u8)explainFlag;
76872  pParse->nVar = 0;
76873}
76874
76875#ifndef SQLITE_OMIT_SHARED_CACHE
76876/*
76877** The TableLock structure is only used by the sqlite3TableLock() and
76878** codeTableLocks() functions.
76879*/
76880struct TableLock {
76881  int iDb;             /* The database containing the table to be locked */
76882  int iTab;            /* The root page of the table to be locked */
76883  u8 isWriteLock;      /* True for write lock.  False for a read lock */
76884  const char *zName;   /* Name of the table */
76885};
76886
76887/*
76888** Record the fact that we want to lock a table at run-time.
76889**
76890** The table to be locked has root page iTab and is found in database iDb.
76891** A read or a write lock can be taken depending on isWritelock.
76892**
76893** This routine just records the fact that the lock is desired.  The
76894** code to make the lock occur is generated by a later call to
76895** codeTableLocks() which occurs during sqlite3FinishCoding().
76896*/
76897SQLITE_PRIVATE void sqlite3TableLock(
76898  Parse *pParse,     /* Parsing context */
76899  int iDb,           /* Index of the database containing the table to lock */
76900  int iTab,          /* Root page number of the table to be locked */
76901  u8 isWriteLock,    /* True for a write lock */
76902  const char *zName  /* Name of the table to be locked */
76903){
76904  Parse *pToplevel = sqlite3ParseToplevel(pParse);
76905  int i;
76906  int nBytes;
76907  TableLock *p;
76908  assert( iDb>=0 );
76909
76910  for(i=0; i<pToplevel->nTableLock; i++){
76911    p = &pToplevel->aTableLock[i];
76912    if( p->iDb==iDb && p->iTab==iTab ){
76913      p->isWriteLock = (p->isWriteLock || isWriteLock);
76914      return;
76915    }
76916  }
76917
76918  nBytes = sizeof(TableLock) * (pToplevel->nTableLock+1);
76919  pToplevel->aTableLock =
76920      sqlite3DbReallocOrFree(pToplevel->db, pToplevel->aTableLock, nBytes);
76921  if( pToplevel->aTableLock ){
76922    p = &pToplevel->aTableLock[pToplevel->nTableLock++];
76923    p->iDb = iDb;
76924    p->iTab = iTab;
76925    p->isWriteLock = isWriteLock;
76926    p->zName = zName;
76927  }else{
76928    pToplevel->nTableLock = 0;
76929    pToplevel->db->mallocFailed = 1;
76930  }
76931}
76932
76933/*
76934** Code an OP_TableLock instruction for each table locked by the
76935** statement (configured by calls to sqlite3TableLock()).
76936*/
76937static void codeTableLocks(Parse *pParse){
76938  int i;
76939  Vdbe *pVdbe;
76940
76941  pVdbe = sqlite3GetVdbe(pParse);
76942  assert( pVdbe!=0 ); /* sqlite3GetVdbe cannot fail: VDBE already allocated */
76943
76944  for(i=0; i<pParse->nTableLock; i++){
76945    TableLock *p = &pParse->aTableLock[i];
76946    int p1 = p->iDb;
76947    sqlite3VdbeAddOp4(pVdbe, OP_TableLock, p1, p->iTab, p->isWriteLock,
76948                      p->zName, P4_STATIC);
76949  }
76950}
76951#else
76952  #define codeTableLocks(x)
76953#endif
76954
76955/*
76956** This routine is called after a single SQL statement has been
76957** parsed and a VDBE program to execute that statement has been
76958** prepared.  This routine puts the finishing touches on the
76959** VDBE program and resets the pParse structure for the next
76960** parse.
76961**
76962** Note that if an error occurred, it might be the case that
76963** no VDBE code was generated.
76964*/
76965SQLITE_PRIVATE void sqlite3FinishCoding(Parse *pParse){
76966  sqlite3 *db;
76967  Vdbe *v;
76968
76969  db = pParse->db;
76970  if( db->mallocFailed ) return;
76971  if( pParse->nested ) return;
76972  if( pParse->nErr ) return;
76973
76974  /* Begin by generating some termination code at the end of the
76975  ** vdbe program
76976  */
76977  v = sqlite3GetVdbe(pParse);
76978  assert( !pParse->isMultiWrite
76979       || sqlite3VdbeAssertMayAbort(v, pParse->mayAbort));
76980  if( v ){
76981    sqlite3VdbeAddOp0(v, OP_Halt);
76982
76983    /* The cookie mask contains one bit for each database file open.
76984    ** (Bit 0 is for main, bit 1 is for temp, and so forth.)  Bits are
76985    ** set for each database that is used.  Generate code to start a
76986    ** transaction on each used database and to verify the schema cookie
76987    ** on each used database.
76988    */
76989    if( pParse->cookieGoto>0 ){
76990      yDbMask mask;
76991      int iDb;
76992      sqlite3VdbeJumpHere(v, pParse->cookieGoto-1);
76993      for(iDb=0, mask=1; iDb<db->nDb; mask<<=1, iDb++){
76994        if( (mask & pParse->cookieMask)==0 ) continue;
76995        sqlite3VdbeUsesBtree(v, iDb);
76996        sqlite3VdbeAddOp2(v,OP_Transaction, iDb, (mask & pParse->writeMask)!=0);
76997        if( db->init.busy==0 ){
76998          assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
76999          sqlite3VdbeAddOp3(v, OP_VerifyCookie,
77000                            iDb, pParse->cookieValue[iDb],
77001                            db->aDb[iDb].pSchema->iGeneration);
77002        }
77003      }
77004#ifndef SQLITE_OMIT_VIRTUALTABLE
77005      {
77006        int i;
77007        for(i=0; i<pParse->nVtabLock; i++){
77008          char *vtab = (char *)sqlite3GetVTable(db, pParse->apVtabLock[i]);
77009          sqlite3VdbeAddOp4(v, OP_VBegin, 0, 0, 0, vtab, P4_VTAB);
77010        }
77011        pParse->nVtabLock = 0;
77012      }
77013#endif
77014
77015      /* Once all the cookies have been verified and transactions opened,
77016      ** obtain the required table-locks. This is a no-op unless the
77017      ** shared-cache feature is enabled.
77018      */
77019      codeTableLocks(pParse);
77020
77021      /* Initialize any AUTOINCREMENT data structures required.
77022      */
77023      sqlite3AutoincrementBegin(pParse);
77024
77025      /* Finally, jump back to the beginning of the executable code. */
77026      sqlite3VdbeAddOp2(v, OP_Goto, 0, pParse->cookieGoto);
77027    }
77028  }
77029
77030
77031  /* Get the VDBE program ready for execution
77032  */
77033  if( v && ALWAYS(pParse->nErr==0) && !db->mallocFailed ){
77034#ifdef SQLITE_DEBUG
77035    FILE *trace = (db->flags & SQLITE_VdbeTrace)!=0 ? stdout : 0;
77036    sqlite3VdbeTrace(v, trace);
77037#endif
77038    assert( pParse->iCacheLevel==0 );  /* Disables and re-enables match */
77039    /* A minimum of one cursor is required if autoincrement is used
77040    *  See ticket [a696379c1f08866] */
77041    if( pParse->pAinc!=0 && pParse->nTab==0 ) pParse->nTab = 1;
77042    sqlite3VdbeMakeReady(v, pParse->nVar, pParse->nMem,
77043                         pParse->nTab, pParse->nMaxArg, pParse->explain,
77044                         pParse->isMultiWrite && pParse->mayAbort);
77045    pParse->rc = SQLITE_DONE;
77046    pParse->colNamesSet = 0;
77047  }else{
77048    pParse->rc = SQLITE_ERROR;
77049  }
77050  pParse->nTab = 0;
77051  pParse->nMem = 0;
77052  pParse->nSet = 0;
77053  pParse->nVar = 0;
77054  pParse->cookieMask = 0;
77055  pParse->cookieGoto = 0;
77056}
77057
77058/*
77059** Run the parser and code generator recursively in order to generate
77060** code for the SQL statement given onto the end of the pParse context
77061** currently under construction.  When the parser is run recursively
77062** this way, the final OP_Halt is not appended and other initialization
77063** and finalization steps are omitted because those are handling by the
77064** outermost parser.
77065**
77066** Not everything is nestable.  This facility is designed to permit
77067** INSERT, UPDATE, and DELETE operations against SQLITE_MASTER.  Use
77068** care if you decide to try to use this routine for some other purposes.
77069*/
77070SQLITE_PRIVATE void sqlite3NestedParse(Parse *pParse, const char *zFormat, ...){
77071  va_list ap;
77072  char *zSql;
77073  char *zErrMsg = 0;
77074  sqlite3 *db = pParse->db;
77075# define SAVE_SZ  (sizeof(Parse) - offsetof(Parse,nVar))
77076  char saveBuf[SAVE_SZ];
77077
77078  if( pParse->nErr ) return;
77079  assert( pParse->nested<10 );  /* Nesting should only be of limited depth */
77080  va_start(ap, zFormat);
77081  zSql = sqlite3VMPrintf(db, zFormat, ap);
77082  va_end(ap);
77083  if( zSql==0 ){
77084    return;   /* A malloc must have failed */
77085  }
77086  pParse->nested++;
77087  memcpy(saveBuf, &pParse->nVar, SAVE_SZ);
77088  memset(&pParse->nVar, 0, SAVE_SZ);
77089  sqlite3RunParser(pParse, zSql, &zErrMsg);
77090  sqlite3DbFree(db, zErrMsg);
77091  sqlite3DbFree(db, zSql);
77092  memcpy(&pParse->nVar, saveBuf, SAVE_SZ);
77093  pParse->nested--;
77094}
77095
77096/*
77097** Locate the in-memory structure that describes a particular database
77098** table given the name of that table and (optionally) the name of the
77099** database containing the table.  Return NULL if not found.
77100**
77101** If zDatabase is 0, all databases are searched for the table and the
77102** first matching table is returned.  (No checking for duplicate table
77103** names is done.)  The search order is TEMP first, then MAIN, then any
77104** auxiliary databases added using the ATTACH command.
77105**
77106** See also sqlite3LocateTable().
77107*/
77108SQLITE_PRIVATE Table *sqlite3FindTable(sqlite3 *db, const char *zName, const char *zDatabase){
77109  Table *p = 0;
77110  int i;
77111  int nName;
77112  assert( zName!=0 );
77113  nName = sqlite3Strlen30(zName);
77114  /* All mutexes are required for schema access.  Make sure we hold them. */
77115  assert( zDatabase!=0 || sqlite3BtreeHoldsAllMutexes(db) );
77116  for(i=OMIT_TEMPDB; i<db->nDb; i++){
77117    int j = (i<2) ? i^1 : i;   /* Search TEMP before MAIN */
77118    if( zDatabase!=0 && sqlite3StrICmp(zDatabase, db->aDb[j].zName) ) continue;
77119    assert( sqlite3SchemaMutexHeld(db, j, 0) );
77120    p = sqlite3HashFind(&db->aDb[j].pSchema->tblHash, zName, nName);
77121    if( p ) break;
77122  }
77123  return p;
77124}
77125
77126/*
77127** Locate the in-memory structure that describes a particular database
77128** table given the name of that table and (optionally) the name of the
77129** database containing the table.  Return NULL if not found.  Also leave an
77130** error message in pParse->zErrMsg.
77131**
77132** The difference between this routine and sqlite3FindTable() is that this
77133** routine leaves an error message in pParse->zErrMsg where
77134** sqlite3FindTable() does not.
77135*/
77136SQLITE_PRIVATE Table *sqlite3LocateTable(
77137  Parse *pParse,         /* context in which to report errors */
77138  int isView,            /* True if looking for a VIEW rather than a TABLE */
77139  const char *zName,     /* Name of the table we are looking for */
77140  const char *zDbase     /* Name of the database.  Might be NULL */
77141){
77142  Table *p;
77143
77144  /* Read the database schema. If an error occurs, leave an error message
77145  ** and code in pParse and return NULL. */
77146  if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
77147    return 0;
77148  }
77149
77150  p = sqlite3FindTable(pParse->db, zName, zDbase);
77151  if( p==0 ){
77152    const char *zMsg = isView ? "no such view" : "no such table";
77153    if( zDbase ){
77154      sqlite3ErrorMsg(pParse, "%s: %s.%s", zMsg, zDbase, zName);
77155    }else{
77156      sqlite3ErrorMsg(pParse, "%s: %s", zMsg, zName);
77157    }
77158    pParse->checkSchema = 1;
77159  }
77160  return p;
77161}
77162
77163/*
77164** Locate the in-memory structure that describes
77165** a particular index given the name of that index
77166** and the name of the database that contains the index.
77167** Return NULL if not found.
77168**
77169** If zDatabase is 0, all databases are searched for the
77170** table and the first matching index is returned.  (No checking
77171** for duplicate index names is done.)  The search order is
77172** TEMP first, then MAIN, then any auxiliary databases added
77173** using the ATTACH command.
77174*/
77175SQLITE_PRIVATE Index *sqlite3FindIndex(sqlite3 *db, const char *zName, const char *zDb){
77176  Index *p = 0;
77177  int i;
77178  int nName = sqlite3Strlen30(zName);
77179  /* All mutexes are required for schema access.  Make sure we hold them. */
77180  assert( zDb!=0 || sqlite3BtreeHoldsAllMutexes(db) );
77181  for(i=OMIT_TEMPDB; i<db->nDb; i++){
77182    int j = (i<2) ? i^1 : i;  /* Search TEMP before MAIN */
77183    Schema *pSchema = db->aDb[j].pSchema;
77184    assert( pSchema );
77185    if( zDb && sqlite3StrICmp(zDb, db->aDb[j].zName) ) continue;
77186    assert( sqlite3SchemaMutexHeld(db, j, 0) );
77187    p = sqlite3HashFind(&pSchema->idxHash, zName, nName);
77188    if( p ) break;
77189  }
77190  return p;
77191}
77192
77193/*
77194** Reclaim the memory used by an index
77195*/
77196static void freeIndex(sqlite3 *db, Index *p){
77197#ifndef SQLITE_OMIT_ANALYZE
77198  sqlite3DeleteIndexSamples(db, p);
77199#endif
77200  sqlite3DbFree(db, p->zColAff);
77201  sqlite3DbFree(db, p);
77202}
77203
77204/*
77205** For the index called zIdxName which is found in the database iDb,
77206** unlike that index from its Table then remove the index from
77207** the index hash table and free all memory structures associated
77208** with the index.
77209*/
77210SQLITE_PRIVATE void sqlite3UnlinkAndDeleteIndex(sqlite3 *db, int iDb, const char *zIdxName){
77211  Index *pIndex;
77212  int len;
77213  Hash *pHash;
77214
77215  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
77216  pHash = &db->aDb[iDb].pSchema->idxHash;
77217  len = sqlite3Strlen30(zIdxName);
77218  pIndex = sqlite3HashInsert(pHash, zIdxName, len, 0);
77219  if( ALWAYS(pIndex) ){
77220    if( pIndex->pTable->pIndex==pIndex ){
77221      pIndex->pTable->pIndex = pIndex->pNext;
77222    }else{
77223      Index *p;
77224      /* Justification of ALWAYS();  The index must be on the list of
77225      ** indices. */
77226      p = pIndex->pTable->pIndex;
77227      while( ALWAYS(p) && p->pNext!=pIndex ){ p = p->pNext; }
77228      if( ALWAYS(p && p->pNext==pIndex) ){
77229        p->pNext = pIndex->pNext;
77230      }
77231    }
77232    freeIndex(db, pIndex);
77233  }
77234  db->flags |= SQLITE_InternChanges;
77235}
77236
77237/*
77238** Erase all schema information from the in-memory hash tables of
77239** a single database.  This routine is called to reclaim memory
77240** before the database closes.  It is also called during a rollback
77241** if there were schema changes during the transaction or if a
77242** schema-cookie mismatch occurs.
77243**
77244** If iDb<0 then reset the internal schema tables for all database
77245** files.  If iDb>=0 then reset the internal schema for only the
77246** single file indicated.
77247*/
77248SQLITE_PRIVATE void sqlite3ResetInternalSchema(sqlite3 *db, int iDb){
77249  int i, j;
77250  assert( iDb<db->nDb );
77251
77252  if( iDb>=0 ){
77253    /* Case 1:  Reset the single schema identified by iDb */
77254    Db *pDb = &db->aDb[iDb];
77255    assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
77256    assert( pDb->pSchema!=0 );
77257    sqlite3SchemaClear(pDb->pSchema);
77258
77259    /* If any database other than TEMP is reset, then also reset TEMP
77260    ** since TEMP might be holding triggers that reference tables in the
77261    ** other database.
77262    */
77263    if( iDb!=1 ){
77264      pDb = &db->aDb[1];
77265      assert( pDb->pSchema!=0 );
77266      sqlite3SchemaClear(pDb->pSchema);
77267    }
77268    return;
77269  }
77270  /* Case 2 (from here to the end): Reset all schemas for all attached
77271  ** databases. */
77272  assert( iDb<0 );
77273  sqlite3BtreeEnterAll(db);
77274  for(i=0; i<db->nDb; i++){
77275    Db *pDb = &db->aDb[i];
77276    if( pDb->pSchema ){
77277      sqlite3SchemaClear(pDb->pSchema);
77278    }
77279  }
77280  db->flags &= ~SQLITE_InternChanges;
77281  sqlite3VtabUnlockList(db);
77282  sqlite3BtreeLeaveAll(db);
77283
77284  /* If one or more of the auxiliary database files has been closed,
77285  ** then remove them from the auxiliary database list.  We take the
77286  ** opportunity to do this here since we have just deleted all of the
77287  ** schema hash tables and therefore do not have to make any changes
77288  ** to any of those tables.
77289  */
77290  for(i=j=2; i<db->nDb; i++){
77291    struct Db *pDb = &db->aDb[i];
77292    if( pDb->pBt==0 ){
77293      sqlite3DbFree(db, pDb->zName);
77294      pDb->zName = 0;
77295      continue;
77296    }
77297    if( j<i ){
77298      db->aDb[j] = db->aDb[i];
77299    }
77300    j++;
77301  }
77302  memset(&db->aDb[j], 0, (db->nDb-j)*sizeof(db->aDb[j]));
77303  db->nDb = j;
77304  if( db->nDb<=2 && db->aDb!=db->aDbStatic ){
77305    memcpy(db->aDbStatic, db->aDb, 2*sizeof(db->aDb[0]));
77306    sqlite3DbFree(db, db->aDb);
77307    db->aDb = db->aDbStatic;
77308  }
77309}
77310
77311/*
77312** This routine is called when a commit occurs.
77313*/
77314SQLITE_PRIVATE void sqlite3CommitInternalChanges(sqlite3 *db){
77315  db->flags &= ~SQLITE_InternChanges;
77316}
77317
77318/*
77319** Delete memory allocated for the column names of a table or view (the
77320** Table.aCol[] array).
77321*/
77322static void sqliteDeleteColumnNames(sqlite3 *db, Table *pTable){
77323  int i;
77324  Column *pCol;
77325  assert( pTable!=0 );
77326  if( (pCol = pTable->aCol)!=0 ){
77327    for(i=0; i<pTable->nCol; i++, pCol++){
77328      sqlite3DbFree(db, pCol->zName);
77329      sqlite3ExprDelete(db, pCol->pDflt);
77330      sqlite3DbFree(db, pCol->zDflt);
77331      sqlite3DbFree(db, pCol->zType);
77332      sqlite3DbFree(db, pCol->zColl);
77333    }
77334    sqlite3DbFree(db, pTable->aCol);
77335  }
77336}
77337
77338/*
77339** Remove the memory data structures associated with the given
77340** Table.  No changes are made to disk by this routine.
77341**
77342** This routine just deletes the data structure.  It does not unlink
77343** the table data structure from the hash table.  But it does destroy
77344** memory structures of the indices and foreign keys associated with
77345** the table.
77346*/
77347SQLITE_PRIVATE void sqlite3DeleteTable(sqlite3 *db, Table *pTable){
77348  Index *pIndex, *pNext;
77349
77350  assert( !pTable || pTable->nRef>0 );
77351
77352  /* Do not delete the table until the reference count reaches zero. */
77353  if( !pTable ) return;
77354  if( ((!db || db->pnBytesFreed==0) && (--pTable->nRef)>0) ) return;
77355
77356  /* Delete all indices associated with this table. */
77357  for(pIndex = pTable->pIndex; pIndex; pIndex=pNext){
77358    pNext = pIndex->pNext;
77359    assert( pIndex->pSchema==pTable->pSchema );
77360    if( !db || db->pnBytesFreed==0 ){
77361      char *zName = pIndex->zName;
77362      TESTONLY ( Index *pOld = ) sqlite3HashInsert(
77363	  &pIndex->pSchema->idxHash, zName, sqlite3Strlen30(zName), 0
77364      );
77365      assert( db==0 || sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) );
77366      assert( pOld==pIndex || pOld==0 );
77367    }
77368    freeIndex(db, pIndex);
77369  }
77370
77371  /* Delete any foreign keys attached to this table. */
77372  sqlite3FkDelete(db, pTable);
77373
77374  /* Delete the Table structure itself.
77375  */
77376  sqliteDeleteColumnNames(db, pTable);
77377  sqlite3DbFree(db, pTable->zName);
77378  sqlite3DbFree(db, pTable->zColAff);
77379  sqlite3SelectDelete(db, pTable->pSelect);
77380#ifndef SQLITE_OMIT_CHECK
77381  sqlite3ExprDelete(db, pTable->pCheck);
77382#endif
77383#ifndef SQLITE_OMIT_VIRTUALTABLE
77384  sqlite3VtabClear(db, pTable);
77385#endif
77386  sqlite3DbFree(db, pTable);
77387}
77388
77389/*
77390** Unlink the given table from the hash tables and the delete the
77391** table structure with all its indices and foreign keys.
77392*/
77393SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTable(sqlite3 *db, int iDb, const char *zTabName){
77394  Table *p;
77395  Db *pDb;
77396
77397  assert( db!=0 );
77398  assert( iDb>=0 && iDb<db->nDb );
77399  assert( zTabName );
77400  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
77401  testcase( zTabName[0]==0 );  /* Zero-length table names are allowed */
77402  pDb = &db->aDb[iDb];
77403  p = sqlite3HashInsert(&pDb->pSchema->tblHash, zTabName,
77404                        sqlite3Strlen30(zTabName),0);
77405  sqlite3DeleteTable(db, p);
77406  db->flags |= SQLITE_InternChanges;
77407}
77408
77409/*
77410** Given a token, return a string that consists of the text of that
77411** token.  Space to hold the returned string
77412** is obtained from sqliteMalloc() and must be freed by the calling
77413** function.
77414**
77415** Any quotation marks (ex:  "name", 'name', [name], or `name`) that
77416** surround the body of the token are removed.
77417**
77418** Tokens are often just pointers into the original SQL text and so
77419** are not \000 terminated and are not persistent.  The returned string
77420** is \000 terminated and is persistent.
77421*/
77422SQLITE_PRIVATE char *sqlite3NameFromToken(sqlite3 *db, Token *pName){
77423  char *zName;
77424  if( pName ){
77425    zName = sqlite3DbStrNDup(db, (char*)pName->z, pName->n);
77426    sqlite3Dequote(zName);
77427  }else{
77428    zName = 0;
77429  }
77430  return zName;
77431}
77432
77433/*
77434** Open the sqlite_master table stored in database number iDb for
77435** writing. The table is opened using cursor 0.
77436*/
77437SQLITE_PRIVATE void sqlite3OpenMasterTable(Parse *p, int iDb){
77438  Vdbe *v = sqlite3GetVdbe(p);
77439  sqlite3TableLock(p, iDb, MASTER_ROOT, 1, SCHEMA_TABLE(iDb));
77440  sqlite3VdbeAddOp3(v, OP_OpenWrite, 0, MASTER_ROOT, iDb);
77441  sqlite3VdbeChangeP4(v, -1, (char *)5, P4_INT32);  /* 5 column table */
77442  if( p->nTab==0 ){
77443    p->nTab = 1;
77444  }
77445}
77446
77447/*
77448** Parameter zName points to a nul-terminated buffer containing the name
77449** of a database ("main", "temp" or the name of an attached db). This
77450** function returns the index of the named database in db->aDb[], or
77451** -1 if the named db cannot be found.
77452*/
77453SQLITE_PRIVATE int sqlite3FindDbName(sqlite3 *db, const char *zName){
77454  int i = -1;         /* Database number */
77455  if( zName ){
77456    Db *pDb;
77457    int n = sqlite3Strlen30(zName);
77458    for(i=(db->nDb-1), pDb=&db->aDb[i]; i>=0; i--, pDb--){
77459      if( (!OMIT_TEMPDB || i!=1 ) && n==sqlite3Strlen30(pDb->zName) &&
77460          0==sqlite3StrICmp(pDb->zName, zName) ){
77461        break;
77462      }
77463    }
77464  }
77465  return i;
77466}
77467
77468/*
77469** The token *pName contains the name of a database (either "main" or
77470** "temp" or the name of an attached db). This routine returns the
77471** index of the named database in db->aDb[], or -1 if the named db
77472** does not exist.
77473*/
77474SQLITE_PRIVATE int sqlite3FindDb(sqlite3 *db, Token *pName){
77475  int i;                               /* Database number */
77476  char *zName;                         /* Name we are searching for */
77477  zName = sqlite3NameFromToken(db, pName);
77478  i = sqlite3FindDbName(db, zName);
77479  sqlite3DbFree(db, zName);
77480  return i;
77481}
77482
77483/* The table or view or trigger name is passed to this routine via tokens
77484** pName1 and pName2. If the table name was fully qualified, for example:
77485**
77486** CREATE TABLE xxx.yyy (...);
77487**
77488** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
77489** the table name is not fully qualified, i.e.:
77490**
77491** CREATE TABLE yyy(...);
77492**
77493** Then pName1 is set to "yyy" and pName2 is "".
77494**
77495** This routine sets the *ppUnqual pointer to point at the token (pName1 or
77496** pName2) that stores the unqualified table name.  The index of the
77497** database "xxx" is returned.
77498*/
77499SQLITE_PRIVATE int sqlite3TwoPartName(
77500  Parse *pParse,      /* Parsing and code generating context */
77501  Token *pName1,      /* The "xxx" in the name "xxx.yyy" or "xxx" */
77502  Token *pName2,      /* The "yyy" in the name "xxx.yyy" */
77503  Token **pUnqual     /* Write the unqualified object name here */
77504){
77505  int iDb;                    /* Database holding the object */
77506  sqlite3 *db = pParse->db;
77507
77508  if( ALWAYS(pName2!=0) && pName2->n>0 ){
77509    if( db->init.busy ) {
77510      sqlite3ErrorMsg(pParse, "corrupt database");
77511      pParse->nErr++;
77512      return -1;
77513    }
77514    *pUnqual = pName2;
77515    iDb = sqlite3FindDb(db, pName1);
77516    if( iDb<0 ){
77517      sqlite3ErrorMsg(pParse, "unknown database %T", pName1);
77518      pParse->nErr++;
77519      return -1;
77520    }
77521  }else{
77522    assert( db->init.iDb==0 || db->init.busy );
77523    iDb = db->init.iDb;
77524    *pUnqual = pName1;
77525  }
77526  return iDb;
77527}
77528
77529/*
77530** This routine is used to check if the UTF-8 string zName is a legal
77531** unqualified name for a new schema object (table, index, view or
77532** trigger). All names are legal except those that begin with the string
77533** "sqlite_" (in upper, lower or mixed case). This portion of the namespace
77534** is reserved for internal use.
77535*/
77536SQLITE_PRIVATE int sqlite3CheckObjectName(Parse *pParse, const char *zName){
77537  if( !pParse->db->init.busy && pParse->nested==0
77538          && (pParse->db->flags & SQLITE_WriteSchema)==0
77539          && 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){
77540    sqlite3ErrorMsg(pParse, "object name reserved for internal use: %s", zName);
77541    return SQLITE_ERROR;
77542  }
77543  return SQLITE_OK;
77544}
77545
77546/*
77547** Begin constructing a new table representation in memory.  This is
77548** the first of several action routines that get called in response
77549** to a CREATE TABLE statement.  In particular, this routine is called
77550** after seeing tokens "CREATE" and "TABLE" and the table name. The isTemp
77551** flag is true if the table should be stored in the auxiliary database
77552** file instead of in the main database file.  This is normally the case
77553** when the "TEMP" or "TEMPORARY" keyword occurs in between
77554** CREATE and TABLE.
77555**
77556** The new table record is initialized and put in pParse->pNewTable.
77557** As more of the CREATE TABLE statement is parsed, additional action
77558** routines will be called to add more information to this record.
77559** At the end of the CREATE TABLE statement, the sqlite3EndTable() routine
77560** is called to complete the construction of the new table record.
77561*/
77562SQLITE_PRIVATE void sqlite3StartTable(
77563  Parse *pParse,   /* Parser context */
77564  Token *pName1,   /* First part of the name of the table or view */
77565  Token *pName2,   /* Second part of the name of the table or view */
77566  int isTemp,      /* True if this is a TEMP table */
77567  int isView,      /* True if this is a VIEW */
77568  int isVirtual,   /* True if this is a VIRTUAL table */
77569  int noErr        /* Do nothing if table already exists */
77570){
77571  Table *pTable;
77572  char *zName = 0; /* The name of the new table */
77573  sqlite3 *db = pParse->db;
77574  Vdbe *v;
77575  int iDb;         /* Database number to create the table in */
77576  Token *pName;    /* Unqualified name of the table to create */
77577
77578  /* The table or view name to create is passed to this routine via tokens
77579  ** pName1 and pName2. If the table name was fully qualified, for example:
77580  **
77581  ** CREATE TABLE xxx.yyy (...);
77582  **
77583  ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
77584  ** the table name is not fully qualified, i.e.:
77585  **
77586  ** CREATE TABLE yyy(...);
77587  **
77588  ** Then pName1 is set to "yyy" and pName2 is "".
77589  **
77590  ** The call below sets the pName pointer to point at the token (pName1 or
77591  ** pName2) that stores the unqualified table name. The variable iDb is
77592  ** set to the index of the database that the table or view is to be
77593  ** created in.
77594  */
77595  iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
77596  if( iDb<0 ) return;
77597  if( !OMIT_TEMPDB && isTemp && pName2->n>0 && iDb!=1 ){
77598    /* If creating a temp table, the name may not be qualified. Unless
77599    ** the database name is "temp" anyway.  */
77600    sqlite3ErrorMsg(pParse, "temporary table name must be unqualified");
77601    return;
77602  }
77603  if( !OMIT_TEMPDB && isTemp ) iDb = 1;
77604
77605  pParse->sNameToken = *pName;
77606  zName = sqlite3NameFromToken(db, pName);
77607  if( zName==0 ) return;
77608  if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
77609    goto begin_table_error;
77610  }
77611  if( db->init.iDb==1 ) isTemp = 1;
77612#ifndef SQLITE_OMIT_AUTHORIZATION
77613  assert( (isTemp & 1)==isTemp );
77614  {
77615    int code;
77616    char *zDb = db->aDb[iDb].zName;
77617    if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(isTemp), 0, zDb) ){
77618      goto begin_table_error;
77619    }
77620    if( isView ){
77621      if( !OMIT_TEMPDB && isTemp ){
77622        code = SQLITE_CREATE_TEMP_VIEW;
77623      }else{
77624        code = SQLITE_CREATE_VIEW;
77625      }
77626    }else{
77627      if( !OMIT_TEMPDB && isTemp ){
77628        code = SQLITE_CREATE_TEMP_TABLE;
77629      }else{
77630        code = SQLITE_CREATE_TABLE;
77631      }
77632    }
77633    if( !isVirtual && sqlite3AuthCheck(pParse, code, zName, 0, zDb) ){
77634      goto begin_table_error;
77635    }
77636  }
77637#endif
77638
77639  /* Make sure the new table name does not collide with an existing
77640  ** index or table name in the same database.  Issue an error message if
77641  ** it does. The exception is if the statement being parsed was passed
77642  ** to an sqlite3_declare_vtab() call. In that case only the column names
77643  ** and types will be used, so there is no need to test for namespace
77644  ** collisions.
77645  */
77646  if( !IN_DECLARE_VTAB ){
77647    char *zDb = db->aDb[iDb].zName;
77648    if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
77649      goto begin_table_error;
77650    }
77651    pTable = sqlite3FindTable(db, zName, zDb);
77652    if( pTable ){
77653      if( !noErr ){
77654        sqlite3ErrorMsg(pParse, "table %T already exists", pName);
77655      }else{
77656        assert( !db->init.busy );
77657        sqlite3CodeVerifySchema(pParse, iDb);
77658      }
77659      goto begin_table_error;
77660    }
77661    if( sqlite3FindIndex(db, zName, zDb)!=0 ){
77662      sqlite3ErrorMsg(pParse, "there is already an index named %s", zName);
77663      goto begin_table_error;
77664    }
77665  }
77666
77667  pTable = sqlite3DbMallocZero(db, sizeof(Table));
77668  if( pTable==0 ){
77669    db->mallocFailed = 1;
77670    pParse->rc = SQLITE_NOMEM;
77671    pParse->nErr++;
77672    goto begin_table_error;
77673  }
77674  pTable->zName = zName;
77675  pTable->iPKey = -1;
77676  pTable->pSchema = db->aDb[iDb].pSchema;
77677  pTable->nRef = 1;
77678  pTable->nRowEst = 1000000;
77679  assert( pParse->pNewTable==0 );
77680  pParse->pNewTable = pTable;
77681
77682  /* If this is the magic sqlite_sequence table used by autoincrement,
77683  ** then record a pointer to this table in the main database structure
77684  ** so that INSERT can find the table easily.
77685  */
77686#ifndef SQLITE_OMIT_AUTOINCREMENT
77687  if( !pParse->nested && strcmp(zName, "sqlite_sequence")==0 ){
77688    assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
77689    pTable->pSchema->pSeqTab = pTable;
77690  }
77691#endif
77692
77693  /* Begin generating the code that will insert the table record into
77694  ** the SQLITE_MASTER table.  Note in particular that we must go ahead
77695  ** and allocate the record number for the table entry now.  Before any
77696  ** PRIMARY KEY or UNIQUE keywords are parsed.  Those keywords will cause
77697  ** indices to be created and the table record must come before the
77698  ** indices.  Hence, the record number for the table must be allocated
77699  ** now.
77700  */
77701  if( !db->init.busy && (v = sqlite3GetVdbe(pParse))!=0 ){
77702    int j1;
77703    int fileFormat;
77704    int reg1, reg2, reg3;
77705    sqlite3BeginWriteOperation(pParse, 0, iDb);
77706
77707#ifndef SQLITE_OMIT_VIRTUALTABLE
77708    if( isVirtual ){
77709      sqlite3VdbeAddOp0(v, OP_VBegin);
77710    }
77711#endif
77712
77713    /* If the file format and encoding in the database have not been set,
77714    ** set them now.
77715    */
77716    reg1 = pParse->regRowid = ++pParse->nMem;
77717    reg2 = pParse->regRoot = ++pParse->nMem;
77718    reg3 = ++pParse->nMem;
77719    sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, reg3, BTREE_FILE_FORMAT);
77720    sqlite3VdbeUsesBtree(v, iDb);
77721    j1 = sqlite3VdbeAddOp1(v, OP_If, reg3);
77722    fileFormat = (db->flags & SQLITE_LegacyFileFmt)!=0 ?
77723                  1 : SQLITE_MAX_FILE_FORMAT;
77724    sqlite3VdbeAddOp2(v, OP_Integer, fileFormat, reg3);
77725    sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, reg3);
77726    sqlite3VdbeAddOp2(v, OP_Integer, ENC(db), reg3);
77727    sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_TEXT_ENCODING, reg3);
77728    sqlite3VdbeJumpHere(v, j1);
77729
77730    /* This just creates a place-holder record in the sqlite_master table.
77731    ** The record created does not contain anything yet.  It will be replaced
77732    ** by the real entry in code generated at sqlite3EndTable().
77733    **
77734    ** The rowid for the new entry is left in register pParse->regRowid.
77735    ** The root page number of the new table is left in reg pParse->regRoot.
77736    ** The rowid and root page number values are needed by the code that
77737    ** sqlite3EndTable will generate.
77738    */
77739#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
77740    if( isView || isVirtual ){
77741      sqlite3VdbeAddOp2(v, OP_Integer, 0, reg2);
77742    }else
77743#endif
77744    {
77745      sqlite3VdbeAddOp2(v, OP_CreateTable, iDb, reg2);
77746    }
77747    sqlite3OpenMasterTable(pParse, iDb);
77748    sqlite3VdbeAddOp2(v, OP_NewRowid, 0, reg1);
77749    sqlite3VdbeAddOp2(v, OP_Null, 0, reg3);
77750    sqlite3VdbeAddOp3(v, OP_Insert, 0, reg3, reg1);
77751    sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
77752    sqlite3VdbeAddOp0(v, OP_Close);
77753  }
77754
77755  /* Normal (non-error) return. */
77756  return;
77757
77758  /* If an error occurs, we jump here */
77759begin_table_error:
77760  sqlite3DbFree(db, zName);
77761  return;
77762}
77763
77764/*
77765** This macro is used to compare two strings in a case-insensitive manner.
77766** It is slightly faster than calling sqlite3StrICmp() directly, but
77767** produces larger code.
77768**
77769** WARNING: This macro is not compatible with the strcmp() family. It
77770** returns true if the two strings are equal, otherwise false.
77771*/
77772#define STRICMP(x, y) (\
77773sqlite3UpperToLower[*(unsigned char *)(x)]==   \
77774sqlite3UpperToLower[*(unsigned char *)(y)]     \
77775&& sqlite3StrICmp((x)+1,(y)+1)==0 )
77776
77777/*
77778** Add a new column to the table currently being constructed.
77779**
77780** The parser calls this routine once for each column declaration
77781** in a CREATE TABLE statement.  sqlite3StartTable() gets called
77782** first to get things going.  Then this routine is called for each
77783** column.
77784*/
77785SQLITE_PRIVATE void sqlite3AddColumn(Parse *pParse, Token *pName){
77786  Table *p;
77787  int i;
77788  char *z;
77789  Column *pCol;
77790  sqlite3 *db = pParse->db;
77791  if( (p = pParse->pNewTable)==0 ) return;
77792#if SQLITE_MAX_COLUMN
77793  if( p->nCol+1>db->aLimit[SQLITE_LIMIT_COLUMN] ){
77794    sqlite3ErrorMsg(pParse, "too many columns on %s", p->zName);
77795    return;
77796  }
77797#endif
77798  z = sqlite3NameFromToken(db, pName);
77799  if( z==0 ) return;
77800  for(i=0; i<p->nCol; i++){
77801    if( STRICMP(z, p->aCol[i].zName) ){
77802      sqlite3ErrorMsg(pParse, "duplicate column name: %s", z);
77803      sqlite3DbFree(db, z);
77804      return;
77805    }
77806  }
77807  if( (p->nCol & 0x7)==0 ){
77808    Column *aNew;
77809    aNew = sqlite3DbRealloc(db,p->aCol,(p->nCol+8)*sizeof(p->aCol[0]));
77810    if( aNew==0 ){
77811      sqlite3DbFree(db, z);
77812      return;
77813    }
77814    p->aCol = aNew;
77815  }
77816  pCol = &p->aCol[p->nCol];
77817  memset(pCol, 0, sizeof(p->aCol[0]));
77818  pCol->zName = z;
77819
77820  /* If there is no type specified, columns have the default affinity
77821  ** 'NONE'. If there is a type specified, then sqlite3AddColumnType() will
77822  ** be called next to set pCol->affinity correctly.
77823  */
77824  pCol->affinity = SQLITE_AFF_NONE;
77825  p->nCol++;
77826}
77827
77828/*
77829** This routine is called by the parser while in the middle of
77830** parsing a CREATE TABLE statement.  A "NOT NULL" constraint has
77831** been seen on a column.  This routine sets the notNull flag on
77832** the column currently under construction.
77833*/
77834SQLITE_PRIVATE void sqlite3AddNotNull(Parse *pParse, int onError){
77835  Table *p;
77836  p = pParse->pNewTable;
77837  if( p==0 || NEVER(p->nCol<1) ) return;
77838  p->aCol[p->nCol-1].notNull = (u8)onError;
77839}
77840
77841/*
77842** Scan the column type name zType (length nType) and return the
77843** associated affinity type.
77844**
77845** This routine does a case-independent search of zType for the
77846** substrings in the following table. If one of the substrings is
77847** found, the corresponding affinity is returned. If zType contains
77848** more than one of the substrings, entries toward the top of
77849** the table take priority. For example, if zType is 'BLOBINT',
77850** SQLITE_AFF_INTEGER is returned.
77851**
77852** Substring     | Affinity
77853** --------------------------------
77854** 'INT'         | SQLITE_AFF_INTEGER
77855** 'CHAR'        | SQLITE_AFF_TEXT
77856** 'CLOB'        | SQLITE_AFF_TEXT
77857** 'TEXT'        | SQLITE_AFF_TEXT
77858** 'BLOB'        | SQLITE_AFF_NONE
77859** 'REAL'        | SQLITE_AFF_REAL
77860** 'FLOA'        | SQLITE_AFF_REAL
77861** 'DOUB'        | SQLITE_AFF_REAL
77862**
77863** If none of the substrings in the above table are found,
77864** SQLITE_AFF_NUMERIC is returned.
77865*/
77866SQLITE_PRIVATE char sqlite3AffinityType(const char *zIn){
77867  u32 h = 0;
77868  char aff = SQLITE_AFF_NUMERIC;
77869
77870  if( zIn ) while( zIn[0] ){
77871    h = (h<<8) + sqlite3UpperToLower[(*zIn)&0xff];
77872    zIn++;
77873    if( h==(('c'<<24)+('h'<<16)+('a'<<8)+'r') ){             /* CHAR */
77874      aff = SQLITE_AFF_TEXT;
77875    }else if( h==(('c'<<24)+('l'<<16)+('o'<<8)+'b') ){       /* CLOB */
77876      aff = SQLITE_AFF_TEXT;
77877    }else if( h==(('t'<<24)+('e'<<16)+('x'<<8)+'t') ){       /* TEXT */
77878      aff = SQLITE_AFF_TEXT;
77879    }else if( h==(('b'<<24)+('l'<<16)+('o'<<8)+'b')          /* BLOB */
77880        && (aff==SQLITE_AFF_NUMERIC || aff==SQLITE_AFF_REAL) ){
77881      aff = SQLITE_AFF_NONE;
77882#ifndef SQLITE_OMIT_FLOATING_POINT
77883    }else if( h==(('r'<<24)+('e'<<16)+('a'<<8)+'l')          /* REAL */
77884        && aff==SQLITE_AFF_NUMERIC ){
77885      aff = SQLITE_AFF_REAL;
77886    }else if( h==(('f'<<24)+('l'<<16)+('o'<<8)+'a')          /* FLOA */
77887        && aff==SQLITE_AFF_NUMERIC ){
77888      aff = SQLITE_AFF_REAL;
77889    }else if( h==(('d'<<24)+('o'<<16)+('u'<<8)+'b')          /* DOUB */
77890        && aff==SQLITE_AFF_NUMERIC ){
77891      aff = SQLITE_AFF_REAL;
77892#endif
77893    }else if( (h&0x00FFFFFF)==(('i'<<16)+('n'<<8)+'t') ){    /* INT */
77894      aff = SQLITE_AFF_INTEGER;
77895      break;
77896    }
77897  }
77898
77899  return aff;
77900}
77901
77902/*
77903** This routine is called by the parser while in the middle of
77904** parsing a CREATE TABLE statement.  The pFirst token is the first
77905** token in the sequence of tokens that describe the type of the
77906** column currently under construction.   pLast is the last token
77907** in the sequence.  Use this information to construct a string
77908** that contains the typename of the column and store that string
77909** in zType.
77910*/
77911SQLITE_PRIVATE void sqlite3AddColumnType(Parse *pParse, Token *pType){
77912  Table *p;
77913  Column *pCol;
77914
77915  p = pParse->pNewTable;
77916  if( p==0 || NEVER(p->nCol<1) ) return;
77917  pCol = &p->aCol[p->nCol-1];
77918  assert( pCol->zType==0 );
77919  pCol->zType = sqlite3NameFromToken(pParse->db, pType);
77920  pCol->affinity = sqlite3AffinityType(pCol->zType);
77921}
77922
77923/*
77924** The expression is the default value for the most recently added column
77925** of the table currently under construction.
77926**
77927** Default value expressions must be constant.  Raise an exception if this
77928** is not the case.
77929**
77930** This routine is called by the parser while in the middle of
77931** parsing a CREATE TABLE statement.
77932*/
77933SQLITE_PRIVATE void sqlite3AddDefaultValue(Parse *pParse, ExprSpan *pSpan){
77934  Table *p;
77935  Column *pCol;
77936  sqlite3 *db = pParse->db;
77937  p = pParse->pNewTable;
77938  if( p!=0 ){
77939    pCol = &(p->aCol[p->nCol-1]);
77940    if( !sqlite3ExprIsConstantOrFunction(pSpan->pExpr) ){
77941      sqlite3ErrorMsg(pParse, "default value of column [%s] is not constant",
77942          pCol->zName);
77943    }else{
77944      /* A copy of pExpr is used instead of the original, as pExpr contains
77945      ** tokens that point to volatile memory. The 'span' of the expression
77946      ** is required by pragma table_info.
77947      */
77948      sqlite3ExprDelete(db, pCol->pDflt);
77949      pCol->pDflt = sqlite3ExprDup(db, pSpan->pExpr, EXPRDUP_REDUCE);
77950      sqlite3DbFree(db, pCol->zDflt);
77951      pCol->zDflt = sqlite3DbStrNDup(db, (char*)pSpan->zStart,
77952                                     (int)(pSpan->zEnd - pSpan->zStart));
77953    }
77954  }
77955  sqlite3ExprDelete(db, pSpan->pExpr);
77956}
77957
77958/*
77959** Designate the PRIMARY KEY for the table.  pList is a list of names
77960** of columns that form the primary key.  If pList is NULL, then the
77961** most recently added column of the table is the primary key.
77962**
77963** A table can have at most one primary key.  If the table already has
77964** a primary key (and this is the second primary key) then create an
77965** error.
77966**
77967** If the PRIMARY KEY is on a single column whose datatype is INTEGER,
77968** then we will try to use that column as the rowid.  Set the Table.iPKey
77969** field of the table under construction to be the index of the
77970** INTEGER PRIMARY KEY column.  Table.iPKey is set to -1 if there is
77971** no INTEGER PRIMARY KEY.
77972**
77973** If the key is not an INTEGER PRIMARY KEY, then create a unique
77974** index for the key.  No index is created for INTEGER PRIMARY KEYs.
77975*/
77976SQLITE_PRIVATE void sqlite3AddPrimaryKey(
77977  Parse *pParse,    /* Parsing context */
77978  ExprList *pList,  /* List of field names to be indexed */
77979  int onError,      /* What to do with a uniqueness conflict */
77980  int autoInc,      /* True if the AUTOINCREMENT keyword is present */
77981  int sortOrder     /* SQLITE_SO_ASC or SQLITE_SO_DESC */
77982){
77983  Table *pTab = pParse->pNewTable;
77984  char *zType = 0;
77985  int iCol = -1, i;
77986  if( pTab==0 || IN_DECLARE_VTAB ) goto primary_key_exit;
77987  if( pTab->tabFlags & TF_HasPrimaryKey ){
77988    sqlite3ErrorMsg(pParse,
77989      "table \"%s\" has more than one primary key", pTab->zName);
77990    goto primary_key_exit;
77991  }
77992  pTab->tabFlags |= TF_HasPrimaryKey;
77993  if( pList==0 ){
77994    iCol = pTab->nCol - 1;
77995    pTab->aCol[iCol].isPrimKey = 1;
77996  }else{
77997    for(i=0; i<pList->nExpr; i++){
77998      for(iCol=0; iCol<pTab->nCol; iCol++){
77999        if( sqlite3StrICmp(pList->a[i].zName, pTab->aCol[iCol].zName)==0 ){
78000          break;
78001        }
78002      }
78003      if( iCol<pTab->nCol ){
78004        pTab->aCol[iCol].isPrimKey = 1;
78005      }
78006    }
78007    if( pList->nExpr>1 ) iCol = -1;
78008  }
78009  if( iCol>=0 && iCol<pTab->nCol ){
78010    zType = pTab->aCol[iCol].zType;
78011  }
78012  if( zType && sqlite3StrICmp(zType, "INTEGER")==0
78013        && sortOrder==SQLITE_SO_ASC ){
78014    pTab->iPKey = iCol;
78015    pTab->keyConf = (u8)onError;
78016    assert( autoInc==0 || autoInc==1 );
78017    pTab->tabFlags |= autoInc*TF_Autoincrement;
78018  }else if( autoInc ){
78019#ifndef SQLITE_OMIT_AUTOINCREMENT
78020    sqlite3ErrorMsg(pParse, "AUTOINCREMENT is only allowed on an "
78021       "INTEGER PRIMARY KEY");
78022#endif
78023  }else{
78024    Index *p;
78025    p = sqlite3CreateIndex(pParse, 0, 0, 0, pList, onError, 0, 0, sortOrder, 0);
78026    if( p ){
78027      p->autoIndex = 2;
78028    }
78029    pList = 0;
78030  }
78031
78032primary_key_exit:
78033  sqlite3ExprListDelete(pParse->db, pList);
78034  return;
78035}
78036
78037/*
78038** Add a new CHECK constraint to the table currently under construction.
78039*/
78040SQLITE_PRIVATE void sqlite3AddCheckConstraint(
78041  Parse *pParse,    /* Parsing context */
78042  Expr *pCheckExpr  /* The check expression */
78043){
78044  sqlite3 *db = pParse->db;
78045#ifndef SQLITE_OMIT_CHECK
78046  Table *pTab = pParse->pNewTable;
78047  if( pTab && !IN_DECLARE_VTAB ){
78048    pTab->pCheck = sqlite3ExprAnd(db, pTab->pCheck, pCheckExpr);
78049  }else
78050#endif
78051  {
78052    sqlite3ExprDelete(db, pCheckExpr);
78053  }
78054}
78055
78056/*
78057** Set the collation function of the most recently parsed table column
78058** to the CollSeq given.
78059*/
78060SQLITE_PRIVATE void sqlite3AddCollateType(Parse *pParse, Token *pToken){
78061  Table *p;
78062  int i;
78063  char *zColl;              /* Dequoted name of collation sequence */
78064  sqlite3 *db;
78065
78066  if( (p = pParse->pNewTable)==0 ) return;
78067  i = p->nCol-1;
78068  db = pParse->db;
78069  zColl = sqlite3NameFromToken(db, pToken);
78070  if( !zColl ) return;
78071
78072  if( sqlite3LocateCollSeq(pParse, zColl) ){
78073    Index *pIdx;
78074    p->aCol[i].zColl = zColl;
78075
78076    /* If the column is declared as "<name> PRIMARY KEY COLLATE <type>",
78077    ** then an index may have been created on this column before the
78078    ** collation type was added. Correct this if it is the case.
78079    */
78080    for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
78081      assert( pIdx->nColumn==1 );
78082      if( pIdx->aiColumn[0]==i ){
78083        pIdx->azColl[0] = p->aCol[i].zColl;
78084      }
78085    }
78086  }else{
78087    sqlite3DbFree(db, zColl);
78088  }
78089}
78090
78091/*
78092** This function returns the collation sequence for database native text
78093** encoding identified by the string zName, length nName.
78094**
78095** If the requested collation sequence is not available, or not available
78096** in the database native encoding, the collation factory is invoked to
78097** request it. If the collation factory does not supply such a sequence,
78098** and the sequence is available in another text encoding, then that is
78099** returned instead.
78100**
78101** If no versions of the requested collations sequence are available, or
78102** another error occurs, NULL is returned and an error message written into
78103** pParse.
78104**
78105** This routine is a wrapper around sqlite3FindCollSeq().  This routine
78106** invokes the collation factory if the named collation cannot be found
78107** and generates an error message.
78108**
78109** See also: sqlite3FindCollSeq(), sqlite3GetCollSeq()
78110*/
78111SQLITE_PRIVATE CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char *zName){
78112  sqlite3 *db = pParse->db;
78113  u8 enc = ENC(db);
78114  u8 initbusy = db->init.busy;
78115  CollSeq *pColl;
78116
78117  pColl = sqlite3FindCollSeq(db, enc, zName, initbusy);
78118  if( !initbusy && (!pColl || !pColl->xCmp) ){
78119    pColl = sqlite3GetCollSeq(db, enc, pColl, zName);
78120    if( !pColl ){
78121      sqlite3ErrorMsg(pParse, "no such collation sequence: %s", zName);
78122    }
78123  }
78124
78125  return pColl;
78126}
78127
78128
78129/*
78130** Generate code that will increment the schema cookie.
78131**
78132** The schema cookie is used to determine when the schema for the
78133** database changes.  After each schema change, the cookie value
78134** changes.  When a process first reads the schema it records the
78135** cookie.  Thereafter, whenever it goes to access the database,
78136** it checks the cookie to make sure the schema has not changed
78137** since it was last read.
78138**
78139** This plan is not completely bullet-proof.  It is possible for
78140** the schema to change multiple times and for the cookie to be
78141** set back to prior value.  But schema changes are infrequent
78142** and the probability of hitting the same cookie value is only
78143** 1 chance in 2^32.  So we're safe enough.
78144*/
78145SQLITE_PRIVATE void sqlite3ChangeCookie(Parse *pParse, int iDb){
78146  int r1 = sqlite3GetTempReg(pParse);
78147  sqlite3 *db = pParse->db;
78148  Vdbe *v = pParse->pVdbe;
78149  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
78150  sqlite3VdbeAddOp2(v, OP_Integer, db->aDb[iDb].pSchema->schema_cookie+1, r1);
78151  sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_SCHEMA_VERSION, r1);
78152  sqlite3ReleaseTempReg(pParse, r1);
78153}
78154
78155/*
78156** Measure the number of characters needed to output the given
78157** identifier.  The number returned includes any quotes used
78158** but does not include the null terminator.
78159**
78160** The estimate is conservative.  It might be larger that what is
78161** really needed.
78162*/
78163static int identLength(const char *z){
78164  int n;
78165  for(n=0; *z; n++, z++){
78166    if( *z=='"' ){ n++; }
78167  }
78168  return n + 2;
78169}
78170
78171/*
78172** The first parameter is a pointer to an output buffer. The second
78173** parameter is a pointer to an integer that contains the offset at
78174** which to write into the output buffer. This function copies the
78175** nul-terminated string pointed to by the third parameter, zSignedIdent,
78176** to the specified offset in the buffer and updates *pIdx to refer
78177** to the first byte after the last byte written before returning.
78178**
78179** If the string zSignedIdent consists entirely of alpha-numeric
78180** characters, does not begin with a digit and is not an SQL keyword,
78181** then it is copied to the output buffer exactly as it is. Otherwise,
78182** it is quoted using double-quotes.
78183*/
78184static void identPut(char *z, int *pIdx, char *zSignedIdent){
78185  unsigned char *zIdent = (unsigned char*)zSignedIdent;
78186  int i, j, needQuote;
78187  i = *pIdx;
78188
78189  for(j=0; zIdent[j]; j++){
78190    if( !sqlite3Isalnum(zIdent[j]) && zIdent[j]!='_' ) break;
78191  }
78192  needQuote = sqlite3Isdigit(zIdent[0]) || sqlite3KeywordCode(zIdent, j)!=TK_ID;
78193  if( !needQuote ){
78194    needQuote = zIdent[j];
78195  }
78196
78197  if( needQuote ) z[i++] = '"';
78198  for(j=0; zIdent[j]; j++){
78199    z[i++] = zIdent[j];
78200    if( zIdent[j]=='"' ) z[i++] = '"';
78201  }
78202  if( needQuote ) z[i++] = '"';
78203  z[i] = 0;
78204  *pIdx = i;
78205}
78206
78207/*
78208** Generate a CREATE TABLE statement appropriate for the given
78209** table.  Memory to hold the text of the statement is obtained
78210** from sqliteMalloc() and must be freed by the calling function.
78211*/
78212static char *createTableStmt(sqlite3 *db, Table *p){
78213  int i, k, n;
78214  char *zStmt;
78215  char *zSep, *zSep2, *zEnd;
78216  Column *pCol;
78217  n = 0;
78218  for(pCol = p->aCol, i=0; i<p->nCol; i++, pCol++){
78219    n += identLength(pCol->zName) + 5;
78220  }
78221  n += identLength(p->zName);
78222  if( n<50 ){
78223    zSep = "";
78224    zSep2 = ",";
78225    zEnd = ")";
78226  }else{
78227    zSep = "\n  ";
78228    zSep2 = ",\n  ";
78229    zEnd = "\n)";
78230  }
78231  n += 35 + 6*p->nCol;
78232  zStmt = sqlite3DbMallocRaw(0, n);
78233  if( zStmt==0 ){
78234    db->mallocFailed = 1;
78235    return 0;
78236  }
78237  sqlite3_snprintf(n, zStmt, "CREATE TABLE ");
78238  k = sqlite3Strlen30(zStmt);
78239  identPut(zStmt, &k, p->zName);
78240  zStmt[k++] = '(';
78241  for(pCol=p->aCol, i=0; i<p->nCol; i++, pCol++){
78242    static const char * const azType[] = {
78243        /* SQLITE_AFF_TEXT    */ " TEXT",
78244        /* SQLITE_AFF_NONE    */ "",
78245        /* SQLITE_AFF_NUMERIC */ " NUM",
78246        /* SQLITE_AFF_INTEGER */ " INT",
78247        /* SQLITE_AFF_REAL    */ " REAL"
78248    };
78249    int len;
78250    const char *zType;
78251
78252    sqlite3_snprintf(n-k, &zStmt[k], zSep);
78253    k += sqlite3Strlen30(&zStmt[k]);
78254    zSep = zSep2;
78255    identPut(zStmt, &k, pCol->zName);
78256    assert( pCol->affinity-SQLITE_AFF_TEXT >= 0 );
78257    assert( pCol->affinity-SQLITE_AFF_TEXT < ArraySize(azType) );
78258    testcase( pCol->affinity==SQLITE_AFF_TEXT );
78259    testcase( pCol->affinity==SQLITE_AFF_NONE );
78260    testcase( pCol->affinity==SQLITE_AFF_NUMERIC );
78261    testcase( pCol->affinity==SQLITE_AFF_INTEGER );
78262    testcase( pCol->affinity==SQLITE_AFF_REAL );
78263
78264    zType = azType[pCol->affinity - SQLITE_AFF_TEXT];
78265    len = sqlite3Strlen30(zType);
78266    assert( pCol->affinity==SQLITE_AFF_NONE
78267            || pCol->affinity==sqlite3AffinityType(zType) );
78268    memcpy(&zStmt[k], zType, len);
78269    k += len;
78270    assert( k<=n );
78271  }
78272  sqlite3_snprintf(n-k, &zStmt[k], "%s", zEnd);
78273  return zStmt;
78274}
78275
78276/*
78277** This routine is called to report the final ")" that terminates
78278** a CREATE TABLE statement.
78279**
78280** The table structure that other action routines have been building
78281** is added to the internal hash tables, assuming no errors have
78282** occurred.
78283**
78284** An entry for the table is made in the master table on disk, unless
78285** this is a temporary table or db->init.busy==1.  When db->init.busy==1
78286** it means we are reading the sqlite_master table because we just
78287** connected to the database or because the sqlite_master table has
78288** recently changed, so the entry for this table already exists in
78289** the sqlite_master table.  We do not want to create it again.
78290**
78291** If the pSelect argument is not NULL, it means that this routine
78292** was called to create a table generated from a
78293** "CREATE TABLE ... AS SELECT ..." statement.  The column names of
78294** the new table will match the result set of the SELECT.
78295*/
78296SQLITE_PRIVATE void sqlite3EndTable(
78297  Parse *pParse,          /* Parse context */
78298  Token *pCons,           /* The ',' token after the last column defn. */
78299  Token *pEnd,            /* The final ')' token in the CREATE TABLE */
78300  Select *pSelect         /* Select from a "CREATE ... AS SELECT" */
78301){
78302  Table *p;
78303  sqlite3 *db = pParse->db;
78304  int iDb;
78305
78306  if( (pEnd==0 && pSelect==0) || db->mallocFailed ){
78307    return;
78308  }
78309  p = pParse->pNewTable;
78310  if( p==0 ) return;
78311
78312  assert( !db->init.busy || !pSelect );
78313
78314  iDb = sqlite3SchemaToIndex(db, p->pSchema);
78315
78316#ifndef SQLITE_OMIT_CHECK
78317  /* Resolve names in all CHECK constraint expressions.
78318  */
78319  if( p->pCheck ){
78320    SrcList sSrc;                   /* Fake SrcList for pParse->pNewTable */
78321    NameContext sNC;                /* Name context for pParse->pNewTable */
78322
78323    memset(&sNC, 0, sizeof(sNC));
78324    memset(&sSrc, 0, sizeof(sSrc));
78325    sSrc.nSrc = 1;
78326    sSrc.a[0].zName = p->zName;
78327    sSrc.a[0].pTab = p;
78328    sSrc.a[0].iCursor = -1;
78329    sNC.pParse = pParse;
78330    sNC.pSrcList = &sSrc;
78331    sNC.isCheck = 1;
78332    if( sqlite3ResolveExprNames(&sNC, p->pCheck) ){
78333      return;
78334    }
78335  }
78336#endif /* !defined(SQLITE_OMIT_CHECK) */
78337
78338  /* If the db->init.busy is 1 it means we are reading the SQL off the
78339  ** "sqlite_master" or "sqlite_temp_master" table on the disk.
78340  ** So do not write to the disk again.  Extract the root page number
78341  ** for the table from the db->init.newTnum field.  (The page number
78342  ** should have been put there by the sqliteOpenCb routine.)
78343  */
78344  if( db->init.busy ){
78345    p->tnum = db->init.newTnum;
78346  }
78347
78348  /* If not initializing, then create a record for the new table
78349  ** in the SQLITE_MASTER table of the database.
78350  **
78351  ** If this is a TEMPORARY table, write the entry into the auxiliary
78352  ** file instead of into the main database file.
78353  */
78354  if( !db->init.busy ){
78355    int n;
78356    Vdbe *v;
78357    char *zType;    /* "view" or "table" */
78358    char *zType2;   /* "VIEW" or "TABLE" */
78359    char *zStmt;    /* Text of the CREATE TABLE or CREATE VIEW statement */
78360
78361    v = sqlite3GetVdbe(pParse);
78362    if( NEVER(v==0) ) return;
78363
78364    sqlite3VdbeAddOp1(v, OP_Close, 0);
78365
78366    /*
78367    ** Initialize zType for the new view or table.
78368    */
78369    if( p->pSelect==0 ){
78370      /* A regular table */
78371      zType = "table";
78372      zType2 = "TABLE";
78373#ifndef SQLITE_OMIT_VIEW
78374    }else{
78375      /* A view */
78376      zType = "view";
78377      zType2 = "VIEW";
78378#endif
78379    }
78380
78381    /* If this is a CREATE TABLE xx AS SELECT ..., execute the SELECT
78382    ** statement to populate the new table. The root-page number for the
78383    ** new table is in register pParse->regRoot.
78384    **
78385    ** Once the SELECT has been coded by sqlite3Select(), it is in a
78386    ** suitable state to query for the column names and types to be used
78387    ** by the new table.
78388    **
78389    ** A shared-cache write-lock is not required to write to the new table,
78390    ** as a schema-lock must have already been obtained to create it. Since
78391    ** a schema-lock excludes all other database users, the write-lock would
78392    ** be redundant.
78393    */
78394    if( pSelect ){
78395      SelectDest dest;
78396      Table *pSelTab;
78397
78398      assert(pParse->nTab==1);
78399      sqlite3VdbeAddOp3(v, OP_OpenWrite, 1, pParse->regRoot, iDb);
78400      sqlite3VdbeChangeP5(v, 1);
78401      pParse->nTab = 2;
78402      sqlite3SelectDestInit(&dest, SRT_Table, 1);
78403      sqlite3Select(pParse, pSelect, &dest);
78404      sqlite3VdbeAddOp1(v, OP_Close, 1);
78405      if( pParse->nErr==0 ){
78406        pSelTab = sqlite3ResultSetOfSelect(pParse, pSelect);
78407        if( pSelTab==0 ) return;
78408        assert( p->aCol==0 );
78409        p->nCol = pSelTab->nCol;
78410        p->aCol = pSelTab->aCol;
78411        pSelTab->nCol = 0;
78412        pSelTab->aCol = 0;
78413        sqlite3DeleteTable(db, pSelTab);
78414      }
78415    }
78416
78417    /* Compute the complete text of the CREATE statement */
78418    if( pSelect ){
78419      zStmt = createTableStmt(db, p);
78420    }else{
78421      n = (int)(pEnd->z - pParse->sNameToken.z) + 1;
78422      zStmt = sqlite3MPrintf(db,
78423          "CREATE %s %.*s", zType2, n, pParse->sNameToken.z
78424      );
78425    }
78426
78427    /* A slot for the record has already been allocated in the
78428    ** SQLITE_MASTER table.  We just need to update that slot with all
78429    ** the information we've collected.
78430    */
78431    sqlite3NestedParse(pParse,
78432      "UPDATE %Q.%s "
78433         "SET type='%s', name=%Q, tbl_name=%Q, rootpage=#%d, sql=%Q "
78434       "WHERE rowid=#%d",
78435      db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
78436      zType,
78437      p->zName,
78438      p->zName,
78439      pParse->regRoot,
78440      zStmt,
78441      pParse->regRowid
78442    );
78443    sqlite3DbFree(db, zStmt);
78444    sqlite3ChangeCookie(pParse, iDb);
78445
78446#ifndef SQLITE_OMIT_AUTOINCREMENT
78447    /* Check to see if we need to create an sqlite_sequence table for
78448    ** keeping track of autoincrement keys.
78449    */
78450    if( p->tabFlags & TF_Autoincrement ){
78451      Db *pDb = &db->aDb[iDb];
78452      assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
78453      if( pDb->pSchema->pSeqTab==0 ){
78454        sqlite3NestedParse(pParse,
78455          "CREATE TABLE %Q.sqlite_sequence(name,seq)",
78456          pDb->zName
78457        );
78458      }
78459    }
78460#endif
78461
78462    /* Reparse everything to update our internal data structures */
78463    sqlite3VdbeAddOp4(v, OP_ParseSchema, iDb, 0, 0,
78464        sqlite3MPrintf(db, "tbl_name='%q'",p->zName), P4_DYNAMIC);
78465  }
78466
78467
78468  /* Add the table to the in-memory representation of the database.
78469  */
78470  if( db->init.busy ){
78471    Table *pOld;
78472    Schema *pSchema = p->pSchema;
78473    assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
78474    pOld = sqlite3HashInsert(&pSchema->tblHash, p->zName,
78475                             sqlite3Strlen30(p->zName),p);
78476    if( pOld ){
78477      assert( p==pOld );  /* Malloc must have failed inside HashInsert() */
78478      db->mallocFailed = 1;
78479      return;
78480    }
78481    pParse->pNewTable = 0;
78482    db->nTable++;
78483    db->flags |= SQLITE_InternChanges;
78484
78485#ifndef SQLITE_OMIT_ALTERTABLE
78486    if( !p->pSelect ){
78487      const char *zName = (const char *)pParse->sNameToken.z;
78488      int nName;
78489      assert( !pSelect && pCons && pEnd );
78490      if( pCons->z==0 ){
78491        pCons = pEnd;
78492      }
78493      nName = (int)((const char *)pCons->z - zName);
78494      p->addColOffset = 13 + sqlite3Utf8CharLen(zName, nName);
78495    }
78496#endif
78497  }
78498}
78499
78500#ifndef SQLITE_OMIT_VIEW
78501/*
78502** The parser calls this routine in order to create a new VIEW
78503*/
78504SQLITE_PRIVATE void sqlite3CreateView(
78505  Parse *pParse,     /* The parsing context */
78506  Token *pBegin,     /* The CREATE token that begins the statement */
78507  Token *pName1,     /* The token that holds the name of the view */
78508  Token *pName2,     /* The token that holds the name of the view */
78509  Select *pSelect,   /* A SELECT statement that will become the new view */
78510  int isTemp,        /* TRUE for a TEMPORARY view */
78511  int noErr          /* Suppress error messages if VIEW already exists */
78512){
78513  Table *p;
78514  int n;
78515  const char *z;
78516  Token sEnd;
78517  DbFixer sFix;
78518  Token *pName;
78519  int iDb;
78520  sqlite3 *db = pParse->db;
78521
78522  if( pParse->nVar>0 ){
78523    sqlite3ErrorMsg(pParse, "parameters are not allowed in views");
78524    sqlite3SelectDelete(db, pSelect);
78525    return;
78526  }
78527  sqlite3StartTable(pParse, pName1, pName2, isTemp, 1, 0, noErr);
78528  p = pParse->pNewTable;
78529  if( p==0 || pParse->nErr ){
78530    sqlite3SelectDelete(db, pSelect);
78531    return;
78532  }
78533  sqlite3TwoPartName(pParse, pName1, pName2, &pName);
78534  iDb = sqlite3SchemaToIndex(db, p->pSchema);
78535  if( sqlite3FixInit(&sFix, pParse, iDb, "view", pName)
78536    && sqlite3FixSelect(&sFix, pSelect)
78537  ){
78538    sqlite3SelectDelete(db, pSelect);
78539    return;
78540  }
78541
78542  /* Make a copy of the entire SELECT statement that defines the view.
78543  ** This will force all the Expr.token.z values to be dynamically
78544  ** allocated rather than point to the input string - which means that
78545  ** they will persist after the current sqlite3_exec() call returns.
78546  */
78547  p->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
78548  sqlite3SelectDelete(db, pSelect);
78549  if( db->mallocFailed ){
78550    return;
78551  }
78552  if( !db->init.busy ){
78553    sqlite3ViewGetColumnNames(pParse, p);
78554  }
78555
78556  /* Locate the end of the CREATE VIEW statement.  Make sEnd point to
78557  ** the end.
78558  */
78559  sEnd = pParse->sLastToken;
78560  if( ALWAYS(sEnd.z[0]!=0) && sEnd.z[0]!=';' ){
78561    sEnd.z += sEnd.n;
78562  }
78563  sEnd.n = 0;
78564  n = (int)(sEnd.z - pBegin->z);
78565  z = pBegin->z;
78566  while( ALWAYS(n>0) && sqlite3Isspace(z[n-1]) ){ n--; }
78567  sEnd.z = &z[n-1];
78568  sEnd.n = 1;
78569
78570  /* Use sqlite3EndTable() to add the view to the SQLITE_MASTER table */
78571  sqlite3EndTable(pParse, 0, &sEnd, 0);
78572  return;
78573}
78574#endif /* SQLITE_OMIT_VIEW */
78575
78576#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
78577/*
78578** The Table structure pTable is really a VIEW.  Fill in the names of
78579** the columns of the view in the pTable structure.  Return the number
78580** of errors.  If an error is seen leave an error message in pParse->zErrMsg.
78581*/
78582SQLITE_PRIVATE int sqlite3ViewGetColumnNames(Parse *pParse, Table *pTable){
78583  Table *pSelTab;   /* A fake table from which we get the result set */
78584  Select *pSel;     /* Copy of the SELECT that implements the view */
78585  int nErr = 0;     /* Number of errors encountered */
78586  int n;            /* Temporarily holds the number of cursors assigned */
78587  sqlite3 *db = pParse->db;  /* Database connection for malloc errors */
78588  int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
78589
78590  assert( pTable );
78591
78592#ifndef SQLITE_OMIT_VIRTUALTABLE
78593  if( sqlite3VtabCallConnect(pParse, pTable) ){
78594    return SQLITE_ERROR;
78595  }
78596  if( IsVirtual(pTable) ) return 0;
78597#endif
78598
78599#ifndef SQLITE_OMIT_VIEW
78600  /* A positive nCol means the columns names for this view are
78601  ** already known.
78602  */
78603  if( pTable->nCol>0 ) return 0;
78604
78605  /* A negative nCol is a special marker meaning that we are currently
78606  ** trying to compute the column names.  If we enter this routine with
78607  ** a negative nCol, it means two or more views form a loop, like this:
78608  **
78609  **     CREATE VIEW one AS SELECT * FROM two;
78610  **     CREATE VIEW two AS SELECT * FROM one;
78611  **
78612  ** Actually, the error above is now caught prior to reaching this point.
78613  ** But the following test is still important as it does come up
78614  ** in the following:
78615  **
78616  **     CREATE TABLE main.ex1(a);
78617  **     CREATE TEMP VIEW ex1 AS SELECT a FROM ex1;
78618  **     SELECT * FROM temp.ex1;
78619  */
78620  if( pTable->nCol<0 ){
78621    sqlite3ErrorMsg(pParse, "view %s is circularly defined", pTable->zName);
78622    return 1;
78623  }
78624  assert( pTable->nCol>=0 );
78625
78626  /* If we get this far, it means we need to compute the table names.
78627  ** Note that the call to sqlite3ResultSetOfSelect() will expand any
78628  ** "*" elements in the results set of the view and will assign cursors
78629  ** to the elements of the FROM clause.  But we do not want these changes
78630  ** to be permanent.  So the computation is done on a copy of the SELECT
78631  ** statement that defines the view.
78632  */
78633  assert( pTable->pSelect );
78634  pSel = sqlite3SelectDup(db, pTable->pSelect, 0);
78635  if( pSel ){
78636    u8 enableLookaside = db->lookaside.bEnabled;
78637    n = pParse->nTab;
78638    sqlite3SrcListAssignCursors(pParse, pSel->pSrc);
78639    pTable->nCol = -1;
78640    db->lookaside.bEnabled = 0;
78641#ifndef SQLITE_OMIT_AUTHORIZATION
78642    xAuth = db->xAuth;
78643    db->xAuth = 0;
78644    pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
78645    db->xAuth = xAuth;
78646#else
78647    pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
78648#endif
78649    db->lookaside.bEnabled = enableLookaside;
78650    pParse->nTab = n;
78651    if( pSelTab ){
78652      assert( pTable->aCol==0 );
78653      pTable->nCol = pSelTab->nCol;
78654      pTable->aCol = pSelTab->aCol;
78655      pSelTab->nCol = 0;
78656      pSelTab->aCol = 0;
78657      sqlite3DeleteTable(db, pSelTab);
78658      assert( sqlite3SchemaMutexHeld(db, 0, pTable->pSchema) );
78659      pTable->pSchema->flags |= DB_UnresetViews;
78660    }else{
78661      pTable->nCol = 0;
78662      nErr++;
78663    }
78664    sqlite3SelectDelete(db, pSel);
78665  } else {
78666    nErr++;
78667  }
78668#endif /* SQLITE_OMIT_VIEW */
78669  return nErr;
78670}
78671#endif /* !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) */
78672
78673#ifndef SQLITE_OMIT_VIEW
78674/*
78675** Clear the column names from every VIEW in database idx.
78676*/
78677static void sqliteViewResetAll(sqlite3 *db, int idx){
78678  HashElem *i;
78679  assert( sqlite3SchemaMutexHeld(db, idx, 0) );
78680  if( !DbHasProperty(db, idx, DB_UnresetViews) ) return;
78681  for(i=sqliteHashFirst(&db->aDb[idx].pSchema->tblHash); i;i=sqliteHashNext(i)){
78682    Table *pTab = sqliteHashData(i);
78683    if( pTab->pSelect ){
78684      sqliteDeleteColumnNames(db, pTab);
78685      pTab->aCol = 0;
78686      pTab->nCol = 0;
78687    }
78688  }
78689  DbClearProperty(db, idx, DB_UnresetViews);
78690}
78691#else
78692# define sqliteViewResetAll(A,B)
78693#endif /* SQLITE_OMIT_VIEW */
78694
78695/*
78696** This function is called by the VDBE to adjust the internal schema
78697** used by SQLite when the btree layer moves a table root page. The
78698** root-page of a table or index in database iDb has changed from iFrom
78699** to iTo.
78700**
78701** Ticket #1728:  The symbol table might still contain information
78702** on tables and/or indices that are the process of being deleted.
78703** If you are unlucky, one of those deleted indices or tables might
78704** have the same rootpage number as the real table or index that is
78705** being moved.  So we cannot stop searching after the first match
78706** because the first match might be for one of the deleted indices
78707** or tables and not the table/index that is actually being moved.
78708** We must continue looping until all tables and indices with
78709** rootpage==iFrom have been converted to have a rootpage of iTo
78710** in order to be certain that we got the right one.
78711*/
78712#ifndef SQLITE_OMIT_AUTOVACUUM
78713SQLITE_PRIVATE void sqlite3RootPageMoved(sqlite3 *db, int iDb, int iFrom, int iTo){
78714  HashElem *pElem;
78715  Hash *pHash;
78716  Db *pDb;
78717
78718  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
78719  pDb = &db->aDb[iDb];
78720  pHash = &pDb->pSchema->tblHash;
78721  for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
78722    Table *pTab = sqliteHashData(pElem);
78723    if( pTab->tnum==iFrom ){
78724      pTab->tnum = iTo;
78725    }
78726  }
78727  pHash = &pDb->pSchema->idxHash;
78728  for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
78729    Index *pIdx = sqliteHashData(pElem);
78730    if( pIdx->tnum==iFrom ){
78731      pIdx->tnum = iTo;
78732    }
78733  }
78734}
78735#endif
78736
78737/*
78738** Write code to erase the table with root-page iTable from database iDb.
78739** Also write code to modify the sqlite_master table and internal schema
78740** if a root-page of another table is moved by the btree-layer whilst
78741** erasing iTable (this can happen with an auto-vacuum database).
78742*/
78743static void destroyRootPage(Parse *pParse, int iTable, int iDb){
78744  Vdbe *v = sqlite3GetVdbe(pParse);
78745  int r1 = sqlite3GetTempReg(pParse);
78746  sqlite3VdbeAddOp3(v, OP_Destroy, iTable, r1, iDb);
78747  sqlite3MayAbort(pParse);
78748#ifndef SQLITE_OMIT_AUTOVACUUM
78749  /* OP_Destroy stores an in integer r1. If this integer
78750  ** is non-zero, then it is the root page number of a table moved to
78751  ** location iTable. The following code modifies the sqlite_master table to
78752  ** reflect this.
78753  **
78754  ** The "#NNN" in the SQL is a special constant that means whatever value
78755  ** is in register NNN.  See grammar rules associated with the TK_REGISTER
78756  ** token for additional information.
78757  */
78758  sqlite3NestedParse(pParse,
78759     "UPDATE %Q.%s SET rootpage=%d WHERE #%d AND rootpage=#%d",
78760     pParse->db->aDb[iDb].zName, SCHEMA_TABLE(iDb), iTable, r1, r1);
78761#endif
78762  sqlite3ReleaseTempReg(pParse, r1);
78763}
78764
78765/*
78766** Write VDBE code to erase table pTab and all associated indices on disk.
78767** Code to update the sqlite_master tables and internal schema definitions
78768** in case a root-page belonging to another table is moved by the btree layer
78769** is also added (this can happen with an auto-vacuum database).
78770*/
78771static void destroyTable(Parse *pParse, Table *pTab){
78772#ifdef SQLITE_OMIT_AUTOVACUUM
78773  Index *pIdx;
78774  int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
78775  destroyRootPage(pParse, pTab->tnum, iDb);
78776  for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
78777    destroyRootPage(pParse, pIdx->tnum, iDb);
78778  }
78779#else
78780  /* If the database may be auto-vacuum capable (if SQLITE_OMIT_AUTOVACUUM
78781  ** is not defined), then it is important to call OP_Destroy on the
78782  ** table and index root-pages in order, starting with the numerically
78783  ** largest root-page number. This guarantees that none of the root-pages
78784  ** to be destroyed is relocated by an earlier OP_Destroy. i.e. if the
78785  ** following were coded:
78786  **
78787  ** OP_Destroy 4 0
78788  ** ...
78789  ** OP_Destroy 5 0
78790  **
78791  ** and root page 5 happened to be the largest root-page number in the
78792  ** database, then root page 5 would be moved to page 4 by the
78793  ** "OP_Destroy 4 0" opcode. The subsequent "OP_Destroy 5 0" would hit
78794  ** a free-list page.
78795  */
78796  int iTab = pTab->tnum;
78797  int iDestroyed = 0;
78798
78799  while( 1 ){
78800    Index *pIdx;
78801    int iLargest = 0;
78802
78803    if( iDestroyed==0 || iTab<iDestroyed ){
78804      iLargest = iTab;
78805    }
78806    for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
78807      int iIdx = pIdx->tnum;
78808      assert( pIdx->pSchema==pTab->pSchema );
78809      if( (iDestroyed==0 || (iIdx<iDestroyed)) && iIdx>iLargest ){
78810        iLargest = iIdx;
78811      }
78812    }
78813    if( iLargest==0 ){
78814      return;
78815    }else{
78816      int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
78817      destroyRootPage(pParse, iLargest, iDb);
78818      iDestroyed = iLargest;
78819    }
78820  }
78821#endif
78822}
78823
78824/*
78825** This routine is called to do the work of a DROP TABLE statement.
78826** pName is the name of the table to be dropped.
78827*/
78828SQLITE_PRIVATE void sqlite3DropTable(Parse *pParse, SrcList *pName, int isView, int noErr){
78829  Table *pTab;
78830  Vdbe *v;
78831  sqlite3 *db = pParse->db;
78832  int iDb;
78833
78834  if( db->mallocFailed ){
78835    goto exit_drop_table;
78836  }
78837  assert( pParse->nErr==0 );
78838  assert( pName->nSrc==1 );
78839  if( noErr ) db->suppressErr++;
78840  pTab = sqlite3LocateTable(pParse, isView,
78841                            pName->a[0].zName, pName->a[0].zDatabase);
78842  if( noErr ) db->suppressErr--;
78843
78844  if( pTab==0 ){
78845    if( noErr ) sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase);
78846    goto exit_drop_table;
78847  }
78848  iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
78849  assert( iDb>=0 && iDb<db->nDb );
78850
78851  /* If pTab is a virtual table, call ViewGetColumnNames() to ensure
78852  ** it is initialized.
78853  */
78854  if( IsVirtual(pTab) && sqlite3ViewGetColumnNames(pParse, pTab) ){
78855    goto exit_drop_table;
78856  }
78857#ifndef SQLITE_OMIT_AUTHORIZATION
78858  {
78859    int code;
78860    const char *zTab = SCHEMA_TABLE(iDb);
78861    const char *zDb = db->aDb[iDb].zName;
78862    const char *zArg2 = 0;
78863    if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb)){
78864      goto exit_drop_table;
78865    }
78866    if( isView ){
78867      if( !OMIT_TEMPDB && iDb==1 ){
78868        code = SQLITE_DROP_TEMP_VIEW;
78869      }else{
78870        code = SQLITE_DROP_VIEW;
78871      }
78872#ifndef SQLITE_OMIT_VIRTUALTABLE
78873    }else if( IsVirtual(pTab) ){
78874      code = SQLITE_DROP_VTABLE;
78875      zArg2 = sqlite3GetVTable(db, pTab)->pMod->zName;
78876#endif
78877    }else{
78878      if( !OMIT_TEMPDB && iDb==1 ){
78879        code = SQLITE_DROP_TEMP_TABLE;
78880      }else{
78881        code = SQLITE_DROP_TABLE;
78882      }
78883    }
78884    if( sqlite3AuthCheck(pParse, code, pTab->zName, zArg2, zDb) ){
78885      goto exit_drop_table;
78886    }
78887    if( sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb) ){
78888      goto exit_drop_table;
78889    }
78890  }
78891#endif
78892  if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 ){
78893    sqlite3ErrorMsg(pParse, "table %s may not be dropped", pTab->zName);
78894    goto exit_drop_table;
78895  }
78896
78897#ifndef SQLITE_OMIT_VIEW
78898  /* Ensure DROP TABLE is not used on a view, and DROP VIEW is not used
78899  ** on a table.
78900  */
78901  if( isView && pTab->pSelect==0 ){
78902    sqlite3ErrorMsg(pParse, "use DROP TABLE to delete table %s", pTab->zName);
78903    goto exit_drop_table;
78904  }
78905  if( !isView && pTab->pSelect ){
78906    sqlite3ErrorMsg(pParse, "use DROP VIEW to delete view %s", pTab->zName);
78907    goto exit_drop_table;
78908  }
78909#endif
78910
78911  /* Generate code to remove the table from the master table
78912  ** on disk.
78913  */
78914  v = sqlite3GetVdbe(pParse);
78915  if( v ){
78916    Trigger *pTrigger;
78917    Db *pDb = &db->aDb[iDb];
78918    sqlite3BeginWriteOperation(pParse, 1, iDb);
78919
78920#ifndef SQLITE_OMIT_VIRTUALTABLE
78921    if( IsVirtual(pTab) ){
78922      sqlite3VdbeAddOp0(v, OP_VBegin);
78923    }
78924#endif
78925    sqlite3FkDropTable(pParse, pName, pTab);
78926
78927    /* Drop all triggers associated with the table being dropped. Code
78928    ** is generated to remove entries from sqlite_master and/or
78929    ** sqlite_temp_master if required.
78930    */
78931    pTrigger = sqlite3TriggerList(pParse, pTab);
78932    while( pTrigger ){
78933      assert( pTrigger->pSchema==pTab->pSchema ||
78934          pTrigger->pSchema==db->aDb[1].pSchema );
78935      sqlite3DropTriggerPtr(pParse, pTrigger);
78936      pTrigger = pTrigger->pNext;
78937    }
78938
78939#ifndef SQLITE_OMIT_AUTOINCREMENT
78940    /* Remove any entries of the sqlite_sequence table associated with
78941    ** the table being dropped. This is done before the table is dropped
78942    ** at the btree level, in case the sqlite_sequence table needs to
78943    ** move as a result of the drop (can happen in auto-vacuum mode).
78944    */
78945    if( pTab->tabFlags & TF_Autoincrement ){
78946      sqlite3NestedParse(pParse,
78947        "DELETE FROM %s.sqlite_sequence WHERE name=%Q",
78948        pDb->zName, pTab->zName
78949      );
78950    }
78951#endif
78952
78953    /* Drop all SQLITE_MASTER table and index entries that refer to the
78954    ** table. The program name loops through the master table and deletes
78955    ** every row that refers to a table of the same name as the one being
78956    ** dropped. Triggers are handled seperately because a trigger can be
78957    ** created in the temp database that refers to a table in another
78958    ** database.
78959    */
78960    sqlite3NestedParse(pParse,
78961        "DELETE FROM %Q.%s WHERE tbl_name=%Q and type!='trigger'",
78962        pDb->zName, SCHEMA_TABLE(iDb), pTab->zName);
78963
78964    /* Drop any statistics from the sqlite_stat1 table, if it exists */
78965    if( sqlite3FindTable(db, "sqlite_stat1", db->aDb[iDb].zName) ){
78966      sqlite3NestedParse(pParse,
78967        "DELETE FROM %Q.sqlite_stat1 WHERE tbl=%Q", pDb->zName, pTab->zName
78968      );
78969    }
78970
78971    if( !isView && !IsVirtual(pTab) ){
78972      destroyTable(pParse, pTab);
78973    }
78974
78975    /* Remove the table entry from SQLite's internal schema and modify
78976    ** the schema cookie.
78977    */
78978    if( IsVirtual(pTab) ){
78979      sqlite3VdbeAddOp4(v, OP_VDestroy, iDb, 0, 0, pTab->zName, 0);
78980    }
78981    sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
78982    sqlite3ChangeCookie(pParse, iDb);
78983  }
78984  sqliteViewResetAll(db, iDb);
78985
78986exit_drop_table:
78987  sqlite3SrcListDelete(db, pName);
78988}
78989
78990/*
78991** This routine is called to create a new foreign key on the table
78992** currently under construction.  pFromCol determines which columns
78993** in the current table point to the foreign key.  If pFromCol==0 then
78994** connect the key to the last column inserted.  pTo is the name of
78995** the table referred to.  pToCol is a list of tables in the other
78996** pTo table that the foreign key points to.  flags contains all
78997** information about the conflict resolution algorithms specified
78998** in the ON DELETE, ON UPDATE and ON INSERT clauses.
78999**
79000** An FKey structure is created and added to the table currently
79001** under construction in the pParse->pNewTable field.
79002**
79003** The foreign key is set for IMMEDIATE processing.  A subsequent call
79004** to sqlite3DeferForeignKey() might change this to DEFERRED.
79005*/
79006SQLITE_PRIVATE void sqlite3CreateForeignKey(
79007  Parse *pParse,       /* Parsing context */
79008  ExprList *pFromCol,  /* Columns in this table that point to other table */
79009  Token *pTo,          /* Name of the other table */
79010  ExprList *pToCol,    /* Columns in the other table */
79011  int flags            /* Conflict resolution algorithms. */
79012){
79013  sqlite3 *db = pParse->db;
79014#ifndef SQLITE_OMIT_FOREIGN_KEY
79015  FKey *pFKey = 0;
79016  FKey *pNextTo;
79017  Table *p = pParse->pNewTable;
79018  int nByte;
79019  int i;
79020  int nCol;
79021  char *z;
79022
79023  assert( pTo!=0 );
79024  if( p==0 || IN_DECLARE_VTAB ) goto fk_end;
79025  if( pFromCol==0 ){
79026    int iCol = p->nCol-1;
79027    if( NEVER(iCol<0) ) goto fk_end;
79028    if( pToCol && pToCol->nExpr!=1 ){
79029      sqlite3ErrorMsg(pParse, "foreign key on %s"
79030         " should reference only one column of table %T",
79031         p->aCol[iCol].zName, pTo);
79032      goto fk_end;
79033    }
79034    nCol = 1;
79035  }else if( pToCol && pToCol->nExpr!=pFromCol->nExpr ){
79036    sqlite3ErrorMsg(pParse,
79037        "number of columns in foreign key does not match the number of "
79038        "columns in the referenced table");
79039    goto fk_end;
79040  }else{
79041    nCol = pFromCol->nExpr;
79042  }
79043  nByte = sizeof(*pFKey) + (nCol-1)*sizeof(pFKey->aCol[0]) + pTo->n + 1;
79044  if( pToCol ){
79045    for(i=0; i<pToCol->nExpr; i++){
79046      nByte += sqlite3Strlen30(pToCol->a[i].zName) + 1;
79047    }
79048  }
79049  pFKey = sqlite3DbMallocZero(db, nByte );
79050  if( pFKey==0 ){
79051    goto fk_end;
79052  }
79053  pFKey->pFrom = p;
79054  pFKey->pNextFrom = p->pFKey;
79055  z = (char*)&pFKey->aCol[nCol];
79056  pFKey->zTo = z;
79057  memcpy(z, pTo->z, pTo->n);
79058  z[pTo->n] = 0;
79059  sqlite3Dequote(z);
79060  z += pTo->n+1;
79061  pFKey->nCol = nCol;
79062  if( pFromCol==0 ){
79063    pFKey->aCol[0].iFrom = p->nCol-1;
79064  }else{
79065    for(i=0; i<nCol; i++){
79066      int j;
79067      for(j=0; j<p->nCol; j++){
79068        if( sqlite3StrICmp(p->aCol[j].zName, pFromCol->a[i].zName)==0 ){
79069          pFKey->aCol[i].iFrom = j;
79070          break;
79071        }
79072      }
79073      if( j>=p->nCol ){
79074        sqlite3ErrorMsg(pParse,
79075          "unknown column \"%s\" in foreign key definition",
79076          pFromCol->a[i].zName);
79077        goto fk_end;
79078      }
79079    }
79080  }
79081  if( pToCol ){
79082    for(i=0; i<nCol; i++){
79083      int n = sqlite3Strlen30(pToCol->a[i].zName);
79084      pFKey->aCol[i].zCol = z;
79085      memcpy(z, pToCol->a[i].zName, n);
79086      z[n] = 0;
79087      z += n+1;
79088    }
79089  }
79090  pFKey->isDeferred = 0;
79091  pFKey->aAction[0] = (u8)(flags & 0xff);            /* ON DELETE action */
79092  pFKey->aAction[1] = (u8)((flags >> 8 ) & 0xff);    /* ON UPDATE action */
79093
79094  assert( sqlite3SchemaMutexHeld(db, 0, p->pSchema) );
79095  pNextTo = (FKey *)sqlite3HashInsert(&p->pSchema->fkeyHash,
79096      pFKey->zTo, sqlite3Strlen30(pFKey->zTo), (void *)pFKey
79097  );
79098  if( pNextTo==pFKey ){
79099    db->mallocFailed = 1;
79100    goto fk_end;
79101  }
79102  if( pNextTo ){
79103    assert( pNextTo->pPrevTo==0 );
79104    pFKey->pNextTo = pNextTo;
79105    pNextTo->pPrevTo = pFKey;
79106  }
79107
79108  /* Link the foreign key to the table as the last step.
79109  */
79110  p->pFKey = pFKey;
79111  pFKey = 0;
79112
79113fk_end:
79114  sqlite3DbFree(db, pFKey);
79115#endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
79116  sqlite3ExprListDelete(db, pFromCol);
79117  sqlite3ExprListDelete(db, pToCol);
79118}
79119
79120/*
79121** This routine is called when an INITIALLY IMMEDIATE or INITIALLY DEFERRED
79122** clause is seen as part of a foreign key definition.  The isDeferred
79123** parameter is 1 for INITIALLY DEFERRED and 0 for INITIALLY IMMEDIATE.
79124** The behavior of the most recently created foreign key is adjusted
79125** accordingly.
79126*/
79127SQLITE_PRIVATE void sqlite3DeferForeignKey(Parse *pParse, int isDeferred){
79128#ifndef SQLITE_OMIT_FOREIGN_KEY
79129  Table *pTab;
79130  FKey *pFKey;
79131  if( (pTab = pParse->pNewTable)==0 || (pFKey = pTab->pFKey)==0 ) return;
79132  assert( isDeferred==0 || isDeferred==1 ); /* EV: R-30323-21917 */
79133  pFKey->isDeferred = (u8)isDeferred;
79134#endif
79135}
79136
79137/*
79138** Generate code that will erase and refill index *pIdx.  This is
79139** used to initialize a newly created index or to recompute the
79140** content of an index in response to a REINDEX command.
79141**
79142** if memRootPage is not negative, it means that the index is newly
79143** created.  The register specified by memRootPage contains the
79144** root page number of the index.  If memRootPage is negative, then
79145** the index already exists and must be cleared before being refilled and
79146** the root page number of the index is taken from pIndex->tnum.
79147*/
79148static void sqlite3RefillIndex(Parse *pParse, Index *pIndex, int memRootPage){
79149  Table *pTab = pIndex->pTable;  /* The table that is indexed */
79150  int iTab = pParse->nTab++;     /* Btree cursor used for pTab */
79151  int iIdx = pParse->nTab++;     /* Btree cursor used for pIndex */
79152  int addr1;                     /* Address of top of loop */
79153  int tnum;                      /* Root page of index */
79154  Vdbe *v;                       /* Generate code into this virtual machine */
79155  KeyInfo *pKey;                 /* KeyInfo for index */
79156  int regIdxKey;                 /* Registers containing the index key */
79157  int regRecord;                 /* Register holding assemblied index record */
79158  sqlite3 *db = pParse->db;      /* The database connection */
79159  int iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
79160
79161#ifndef SQLITE_OMIT_AUTHORIZATION
79162  if( sqlite3AuthCheck(pParse, SQLITE_REINDEX, pIndex->zName, 0,
79163      db->aDb[iDb].zName ) ){
79164    return;
79165  }
79166#endif
79167
79168  /* Require a write-lock on the table to perform this operation */
79169  sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName);
79170
79171  v = sqlite3GetVdbe(pParse);
79172  if( v==0 ) return;
79173  if( memRootPage>=0 ){
79174    tnum = memRootPage;
79175  }else{
79176    tnum = pIndex->tnum;
79177    sqlite3VdbeAddOp2(v, OP_Clear, tnum, iDb);
79178  }
79179  pKey = sqlite3IndexKeyinfo(pParse, pIndex);
79180  sqlite3VdbeAddOp4(v, OP_OpenWrite, iIdx, tnum, iDb,
79181                    (char *)pKey, P4_KEYINFO_HANDOFF);
79182  if( memRootPage>=0 ){
79183    sqlite3VdbeChangeP5(v, 1);
79184  }
79185  sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
79186  addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0);
79187  regRecord = sqlite3GetTempReg(pParse);
79188  regIdxKey = sqlite3GenerateIndexKey(pParse, pIndex, iTab, regRecord, 1);
79189  if( pIndex->onError!=OE_None ){
79190    const int regRowid = regIdxKey + pIndex->nColumn;
79191    const int j2 = sqlite3VdbeCurrentAddr(v) + 2;
79192    void * const pRegKey = SQLITE_INT_TO_PTR(regIdxKey);
79193
79194    /* The registers accessed by the OP_IsUnique opcode were allocated
79195    ** using sqlite3GetTempRange() inside of the sqlite3GenerateIndexKey()
79196    ** call above. Just before that function was freed they were released
79197    ** (made available to the compiler for reuse) using
79198    ** sqlite3ReleaseTempRange(). So in some ways having the OP_IsUnique
79199    ** opcode use the values stored within seems dangerous. However, since
79200    ** we can be sure that no other temp registers have been allocated
79201    ** since sqlite3ReleaseTempRange() was called, it is safe to do so.
79202    */
79203    sqlite3VdbeAddOp4(v, OP_IsUnique, iIdx, j2, regRowid, pRegKey, P4_INT32);
79204    sqlite3HaltConstraint(
79205        pParse, OE_Abort, "indexed columns are not unique", P4_STATIC);
79206  }
79207  sqlite3VdbeAddOp2(v, OP_IdxInsert, iIdx, regRecord);
79208  sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
79209  sqlite3ReleaseTempReg(pParse, regRecord);
79210  sqlite3VdbeAddOp2(v, OP_Next, iTab, addr1+1);
79211  sqlite3VdbeJumpHere(v, addr1);
79212  sqlite3VdbeAddOp1(v, OP_Close, iTab);
79213  sqlite3VdbeAddOp1(v, OP_Close, iIdx);
79214}
79215
79216/*
79217** Create a new index for an SQL table.  pName1.pName2 is the name of the index
79218** and pTblList is the name of the table that is to be indexed.  Both will
79219** be NULL for a primary key or an index that is created to satisfy a
79220** UNIQUE constraint.  If pTable and pIndex are NULL, use pParse->pNewTable
79221** as the table to be indexed.  pParse->pNewTable is a table that is
79222** currently being constructed by a CREATE TABLE statement.
79223**
79224** pList is a list of columns to be indexed.  pList will be NULL if this
79225** is a primary key or unique-constraint on the most recent column added
79226** to the table currently under construction.
79227**
79228** If the index is created successfully, return a pointer to the new Index
79229** structure. This is used by sqlite3AddPrimaryKey() to mark the index
79230** as the tables primary key (Index.autoIndex==2).
79231*/
79232SQLITE_PRIVATE Index *sqlite3CreateIndex(
79233  Parse *pParse,     /* All information about this parse */
79234  Token *pName1,     /* First part of index name. May be NULL */
79235  Token *pName2,     /* Second part of index name. May be NULL */
79236  SrcList *pTblName, /* Table to index. Use pParse->pNewTable if 0 */
79237  ExprList *pList,   /* A list of columns to be indexed */
79238  int onError,       /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
79239  Token *pStart,     /* The CREATE token that begins this statement */
79240  Token *pEnd,       /* The ")" that closes the CREATE INDEX statement */
79241  int sortOrder,     /* Sort order of primary key when pList==NULL */
79242  int ifNotExist     /* Omit error if index already exists */
79243){
79244  Index *pRet = 0;     /* Pointer to return */
79245  Table *pTab = 0;     /* Table to be indexed */
79246  Index *pIndex = 0;   /* The index to be created */
79247  char *zName = 0;     /* Name of the index */
79248  int nName;           /* Number of characters in zName */
79249  int i, j;
79250  Token nullId;        /* Fake token for an empty ID list */
79251  DbFixer sFix;        /* For assigning database names to pTable */
79252  int sortOrderMask;   /* 1 to honor DESC in index.  0 to ignore. */
79253  sqlite3 *db = pParse->db;
79254  Db *pDb;             /* The specific table containing the indexed database */
79255  int iDb;             /* Index of the database that is being written */
79256  Token *pName = 0;    /* Unqualified name of the index to create */
79257  struct ExprList_item *pListItem; /* For looping over pList */
79258  int nCol;
79259  int nExtra = 0;
79260  char *zExtra;
79261
79262  assert( pStart==0 || pEnd!=0 ); /* pEnd must be non-NULL if pStart is */
79263  assert( pParse->nErr==0 );      /* Never called with prior errors */
79264  if( db->mallocFailed || IN_DECLARE_VTAB ){
79265    goto exit_create_index;
79266  }
79267  if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
79268    goto exit_create_index;
79269  }
79270
79271  /*
79272  ** Find the table that is to be indexed.  Return early if not found.
79273  */
79274  if( pTblName!=0 ){
79275
79276    /* Use the two-part index name to determine the database
79277    ** to search for the table. 'Fix' the table name to this db
79278    ** before looking up the table.
79279    */
79280    assert( pName1 && pName2 );
79281    iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
79282    if( iDb<0 ) goto exit_create_index;
79283
79284#ifndef SQLITE_OMIT_TEMPDB
79285    /* If the index name was unqualified, check if the the table
79286    ** is a temp table. If so, set the database to 1. Do not do this
79287    ** if initialising a database schema.
79288    */
79289    if( !db->init.busy ){
79290      pTab = sqlite3SrcListLookup(pParse, pTblName);
79291      if( pName2->n==0 && pTab && pTab->pSchema==db->aDb[1].pSchema ){
79292        iDb = 1;
79293      }
79294    }
79295#endif
79296
79297    if( sqlite3FixInit(&sFix, pParse, iDb, "index", pName) &&
79298        sqlite3FixSrcList(&sFix, pTblName)
79299    ){
79300      /* Because the parser constructs pTblName from a single identifier,
79301      ** sqlite3FixSrcList can never fail. */
79302      assert(0);
79303    }
79304    pTab = sqlite3LocateTable(pParse, 0, pTblName->a[0].zName,
79305        pTblName->a[0].zDatabase);
79306    if( !pTab || db->mallocFailed ) goto exit_create_index;
79307    assert( db->aDb[iDb].pSchema==pTab->pSchema );
79308  }else{
79309    assert( pName==0 );
79310    pTab = pParse->pNewTable;
79311    if( !pTab ) goto exit_create_index;
79312    iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
79313  }
79314  pDb = &db->aDb[iDb];
79315
79316  assert( pTab!=0 );
79317  assert( pParse->nErr==0 );
79318  if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0
79319       && sqlite3StrNICmp(&pTab->zName[7],"altertab_",9)!=0 ){
79320    sqlite3ErrorMsg(pParse, "table %s may not be indexed", pTab->zName);
79321    goto exit_create_index;
79322  }
79323#ifndef SQLITE_OMIT_VIEW
79324  if( pTab->pSelect ){
79325    sqlite3ErrorMsg(pParse, "views may not be indexed");
79326    goto exit_create_index;
79327  }
79328#endif
79329#ifndef SQLITE_OMIT_VIRTUALTABLE
79330  if( IsVirtual(pTab) ){
79331    sqlite3ErrorMsg(pParse, "virtual tables may not be indexed");
79332    goto exit_create_index;
79333  }
79334#endif
79335
79336  /*
79337  ** Find the name of the index.  Make sure there is not already another
79338  ** index or table with the same name.
79339  **
79340  ** Exception:  If we are reading the names of permanent indices from the
79341  ** sqlite_master table (because some other process changed the schema) and
79342  ** one of the index names collides with the name of a temporary table or
79343  ** index, then we will continue to process this index.
79344  **
79345  ** If pName==0 it means that we are
79346  ** dealing with a primary key or UNIQUE constraint.  We have to invent our
79347  ** own name.
79348  */
79349  if( pName ){
79350    zName = sqlite3NameFromToken(db, pName);
79351    if( zName==0 ) goto exit_create_index;
79352    if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
79353      goto exit_create_index;
79354    }
79355    if( !db->init.busy ){
79356      if( sqlite3FindTable(db, zName, 0)!=0 ){
79357        sqlite3ErrorMsg(pParse, "there is already a table named %s", zName);
79358        goto exit_create_index;
79359      }
79360    }
79361    if( sqlite3FindIndex(db, zName, pDb->zName)!=0 ){
79362      if( !ifNotExist ){
79363        sqlite3ErrorMsg(pParse, "index %s already exists", zName);
79364      }else{
79365        assert( !db->init.busy );
79366        sqlite3CodeVerifySchema(pParse, iDb);
79367      }
79368      goto exit_create_index;
79369    }
79370  }else{
79371    int n;
79372    Index *pLoop;
79373    for(pLoop=pTab->pIndex, n=1; pLoop; pLoop=pLoop->pNext, n++){}
79374    zName = sqlite3MPrintf(db, "sqlite_autoindex_%s_%d", pTab->zName, n);
79375    if( zName==0 ){
79376      goto exit_create_index;
79377    }
79378  }
79379
79380  /* Check for authorization to create an index.
79381  */
79382#ifndef SQLITE_OMIT_AUTHORIZATION
79383  {
79384    const char *zDb = pDb->zName;
79385    if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iDb), 0, zDb) ){
79386      goto exit_create_index;
79387    }
79388    i = SQLITE_CREATE_INDEX;
79389    if( !OMIT_TEMPDB && iDb==1 ) i = SQLITE_CREATE_TEMP_INDEX;
79390    if( sqlite3AuthCheck(pParse, i, zName, pTab->zName, zDb) ){
79391      goto exit_create_index;
79392    }
79393  }
79394#endif
79395
79396  /* If pList==0, it means this routine was called to make a primary
79397  ** key out of the last column added to the table under construction.
79398  ** So create a fake list to simulate this.
79399  */
79400  if( pList==0 ){
79401    nullId.z = pTab->aCol[pTab->nCol-1].zName;
79402    nullId.n = sqlite3Strlen30((char*)nullId.z);
79403    pList = sqlite3ExprListAppend(pParse, 0, 0);
79404    if( pList==0 ) goto exit_create_index;
79405    sqlite3ExprListSetName(pParse, pList, &nullId, 0);
79406    pList->a[0].sortOrder = (u8)sortOrder;
79407  }
79408
79409  /* Figure out how many bytes of space are required to store explicitly
79410  ** specified collation sequence names.
79411  */
79412  for(i=0; i<pList->nExpr; i++){
79413    Expr *pExpr = pList->a[i].pExpr;
79414    if( pExpr ){
79415      CollSeq *pColl = pExpr->pColl;
79416      /* Either pColl!=0 or there was an OOM failure.  But if an OOM
79417      ** failure we have quit before reaching this point. */
79418      if( ALWAYS(pColl) ){
79419        nExtra += (1 + sqlite3Strlen30(pColl->zName));
79420      }
79421    }
79422  }
79423
79424  /*
79425  ** Allocate the index structure.
79426  */
79427  nName = sqlite3Strlen30(zName);
79428  nCol = pList->nExpr;
79429  pIndex = sqlite3DbMallocZero(db,
79430      sizeof(Index) +              /* Index structure  */
79431      sizeof(int)*nCol +           /* Index.aiColumn   */
79432      sizeof(int)*(nCol+1) +       /* Index.aiRowEst   */
79433      sizeof(char *)*nCol +        /* Index.azColl     */
79434      sizeof(u8)*nCol +            /* Index.aSortOrder */
79435      nName + 1 +                  /* Index.zName      */
79436      nExtra                       /* Collation sequence names */
79437  );
79438  if( db->mallocFailed ){
79439    goto exit_create_index;
79440  }
79441  pIndex->azColl = (char**)(&pIndex[1]);
79442  pIndex->aiColumn = (int *)(&pIndex->azColl[nCol]);
79443  pIndex->aiRowEst = (unsigned *)(&pIndex->aiColumn[nCol]);
79444  pIndex->aSortOrder = (u8 *)(&pIndex->aiRowEst[nCol+1]);
79445  pIndex->zName = (char *)(&pIndex->aSortOrder[nCol]);
79446  zExtra = (char *)(&pIndex->zName[nName+1]);
79447  memcpy(pIndex->zName, zName, nName+1);
79448  pIndex->pTable = pTab;
79449  pIndex->nColumn = pList->nExpr;
79450  pIndex->onError = (u8)onError;
79451  pIndex->autoIndex = (u8)(pName==0);
79452  pIndex->pSchema = db->aDb[iDb].pSchema;
79453  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
79454
79455  /* Check to see if we should honor DESC requests on index columns
79456  */
79457  if( pDb->pSchema->file_format>=4 ){
79458    sortOrderMask = -1;   /* Honor DESC */
79459  }else{
79460    sortOrderMask = 0;    /* Ignore DESC */
79461  }
79462
79463  /* Scan the names of the columns of the table to be indexed and
79464  ** load the column indices into the Index structure.  Report an error
79465  ** if any column is not found.
79466  **
79467  ** TODO:  Add a test to make sure that the same column is not named
79468  ** more than once within the same index.  Only the first instance of
79469  ** the column will ever be used by the optimizer.  Note that using the
79470  ** same column more than once cannot be an error because that would
79471  ** break backwards compatibility - it needs to be a warning.
79472  */
79473  for(i=0, pListItem=pList->a; i<pList->nExpr; i++, pListItem++){
79474    const char *zColName = pListItem->zName;
79475    Column *pTabCol;
79476    int requestedSortOrder;
79477    char *zColl;                   /* Collation sequence name */
79478
79479    for(j=0, pTabCol=pTab->aCol; j<pTab->nCol; j++, pTabCol++){
79480      if( sqlite3StrICmp(zColName, pTabCol->zName)==0 ) break;
79481    }
79482    if( j>=pTab->nCol ){
79483      sqlite3ErrorMsg(pParse, "table %s has no column named %s",
79484        pTab->zName, zColName);
79485      pParse->checkSchema = 1;
79486      goto exit_create_index;
79487    }
79488    pIndex->aiColumn[i] = j;
79489    /* Justification of the ALWAYS(pListItem->pExpr->pColl):  Because of
79490    ** the way the "idxlist" non-terminal is constructed by the parser,
79491    ** if pListItem->pExpr is not null then either pListItem->pExpr->pColl
79492    ** must exist or else there must have been an OOM error.  But if there
79493    ** was an OOM error, we would never reach this point. */
79494    if( pListItem->pExpr && ALWAYS(pListItem->pExpr->pColl) ){
79495      int nColl;
79496      zColl = pListItem->pExpr->pColl->zName;
79497      nColl = sqlite3Strlen30(zColl) + 1;
79498      assert( nExtra>=nColl );
79499      memcpy(zExtra, zColl, nColl);
79500      zColl = zExtra;
79501      zExtra += nColl;
79502      nExtra -= nColl;
79503    }else{
79504      zColl = pTab->aCol[j].zColl;
79505      if( !zColl ){
79506        zColl = db->pDfltColl->zName;
79507      }
79508    }
79509    if( !db->init.busy && !sqlite3LocateCollSeq(pParse, zColl) ){
79510      goto exit_create_index;
79511    }
79512    pIndex->azColl[i] = zColl;
79513    requestedSortOrder = pListItem->sortOrder & sortOrderMask;
79514    pIndex->aSortOrder[i] = (u8)requestedSortOrder;
79515  }
79516  sqlite3DefaultRowEst(pIndex);
79517
79518  if( pTab==pParse->pNewTable ){
79519    /* This routine has been called to create an automatic index as a
79520    ** result of a PRIMARY KEY or UNIQUE clause on a column definition, or
79521    ** a PRIMARY KEY or UNIQUE clause following the column definitions.
79522    ** i.e. one of:
79523    **
79524    ** CREATE TABLE t(x PRIMARY KEY, y);
79525    ** CREATE TABLE t(x, y, UNIQUE(x, y));
79526    **
79527    ** Either way, check to see if the table already has such an index. If
79528    ** so, don't bother creating this one. This only applies to
79529    ** automatically created indices. Users can do as they wish with
79530    ** explicit indices.
79531    **
79532    ** Two UNIQUE or PRIMARY KEY constraints are considered equivalent
79533    ** (and thus suppressing the second one) even if they have different
79534    ** sort orders.
79535    **
79536    ** If there are different collating sequences or if the columns of
79537    ** the constraint occur in different orders, then the constraints are
79538    ** considered distinct and both result in separate indices.
79539    */
79540    Index *pIdx;
79541    for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
79542      int k;
79543      assert( pIdx->onError!=OE_None );
79544      assert( pIdx->autoIndex );
79545      assert( pIndex->onError!=OE_None );
79546
79547      if( pIdx->nColumn!=pIndex->nColumn ) continue;
79548      for(k=0; k<pIdx->nColumn; k++){
79549        const char *z1;
79550        const char *z2;
79551        if( pIdx->aiColumn[k]!=pIndex->aiColumn[k] ) break;
79552        z1 = pIdx->azColl[k];
79553        z2 = pIndex->azColl[k];
79554        if( z1!=z2 && sqlite3StrICmp(z1, z2) ) break;
79555      }
79556      if( k==pIdx->nColumn ){
79557        if( pIdx->onError!=pIndex->onError ){
79558          /* This constraint creates the same index as a previous
79559          ** constraint specified somewhere in the CREATE TABLE statement.
79560          ** However the ON CONFLICT clauses are different. If both this
79561          ** constraint and the previous equivalent constraint have explicit
79562          ** ON CONFLICT clauses this is an error. Otherwise, use the
79563          ** explicitly specified behaviour for the index.
79564          */
79565          if( !(pIdx->onError==OE_Default || pIndex->onError==OE_Default) ){
79566            sqlite3ErrorMsg(pParse,
79567                "conflicting ON CONFLICT clauses specified", 0);
79568          }
79569          if( pIdx->onError==OE_Default ){
79570            pIdx->onError = pIndex->onError;
79571          }
79572        }
79573        goto exit_create_index;
79574      }
79575    }
79576  }
79577
79578  /* Link the new Index structure to its table and to the other
79579  ** in-memory database structures.
79580  */
79581  if( db->init.busy ){
79582    Index *p;
79583    assert( sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) );
79584    p = sqlite3HashInsert(&pIndex->pSchema->idxHash,
79585                          pIndex->zName, sqlite3Strlen30(pIndex->zName),
79586                          pIndex);
79587    if( p ){
79588      assert( p==pIndex );  /* Malloc must have failed */
79589      db->mallocFailed = 1;
79590      goto exit_create_index;
79591    }
79592    db->flags |= SQLITE_InternChanges;
79593    if( pTblName!=0 ){
79594      pIndex->tnum = db->init.newTnum;
79595    }
79596  }
79597
79598  /* If the db->init.busy is 0 then create the index on disk.  This
79599  ** involves writing the index into the master table and filling in the
79600  ** index with the current table contents.
79601  **
79602  ** The db->init.busy is 0 when the user first enters a CREATE INDEX
79603  ** command.  db->init.busy is 1 when a database is opened and
79604  ** CREATE INDEX statements are read out of the master table.  In
79605  ** the latter case the index already exists on disk, which is why
79606  ** we don't want to recreate it.
79607  **
79608  ** If pTblName==0 it means this index is generated as a primary key
79609  ** or UNIQUE constraint of a CREATE TABLE statement.  Since the table
79610  ** has just been created, it contains no data and the index initialization
79611  ** step can be skipped.
79612  */
79613  else{ /* if( db->init.busy==0 ) */
79614    Vdbe *v;
79615    char *zStmt;
79616    int iMem = ++pParse->nMem;
79617
79618    v = sqlite3GetVdbe(pParse);
79619    if( v==0 ) goto exit_create_index;
79620
79621
79622    /* Create the rootpage for the index
79623    */
79624    sqlite3BeginWriteOperation(pParse, 1, iDb);
79625    sqlite3VdbeAddOp2(v, OP_CreateIndex, iDb, iMem);
79626
79627    /* Gather the complete text of the CREATE INDEX statement into
79628    ** the zStmt variable
79629    */
79630    if( pStart ){
79631      assert( pEnd!=0 );
79632      /* A named index with an explicit CREATE INDEX statement */
79633      zStmt = sqlite3MPrintf(db, "CREATE%s INDEX %.*s",
79634        onError==OE_None ? "" : " UNIQUE",
79635        pEnd->z - pName->z + 1,
79636        pName->z);
79637    }else{
79638      /* An automatic index created by a PRIMARY KEY or UNIQUE constraint */
79639      /* zStmt = sqlite3MPrintf(""); */
79640      zStmt = 0;
79641    }
79642
79643    /* Add an entry in sqlite_master for this index
79644    */
79645    sqlite3NestedParse(pParse,
79646        "INSERT INTO %Q.%s VALUES('index',%Q,%Q,#%d,%Q);",
79647        db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
79648        pIndex->zName,
79649        pTab->zName,
79650        iMem,
79651        zStmt
79652    );
79653    sqlite3DbFree(db, zStmt);
79654
79655    /* Fill the index with data and reparse the schema. Code an OP_Expire
79656    ** to invalidate all pre-compiled statements.
79657    */
79658    if( pTblName ){
79659      sqlite3RefillIndex(pParse, pIndex, iMem);
79660      sqlite3ChangeCookie(pParse, iDb);
79661      sqlite3VdbeAddOp4(v, OP_ParseSchema, iDb, 0, 0,
79662         sqlite3MPrintf(db, "name='%q' AND type='index'", pIndex->zName),
79663         P4_DYNAMIC);
79664      sqlite3VdbeAddOp1(v, OP_Expire, 0);
79665    }
79666  }
79667
79668  /* When adding an index to the list of indices for a table, make
79669  ** sure all indices labeled OE_Replace come after all those labeled
79670  ** OE_Ignore.  This is necessary for the correct constraint check
79671  ** processing (in sqlite3GenerateConstraintChecks()) as part of
79672  ** UPDATE and INSERT statements.
79673  */
79674  if( db->init.busy || pTblName==0 ){
79675    if( onError!=OE_Replace || pTab->pIndex==0
79676         || pTab->pIndex->onError==OE_Replace){
79677      pIndex->pNext = pTab->pIndex;
79678      pTab->pIndex = pIndex;
79679    }else{
79680      Index *pOther = pTab->pIndex;
79681      while( pOther->pNext && pOther->pNext->onError!=OE_Replace ){
79682        pOther = pOther->pNext;
79683      }
79684      pIndex->pNext = pOther->pNext;
79685      pOther->pNext = pIndex;
79686    }
79687    pRet = pIndex;
79688    pIndex = 0;
79689  }
79690
79691  /* Clean up before exiting */
79692exit_create_index:
79693  if( pIndex ){
79694    sqlite3DbFree(db, pIndex->zColAff);
79695    sqlite3DbFree(db, pIndex);
79696  }
79697  sqlite3ExprListDelete(db, pList);
79698  sqlite3SrcListDelete(db, pTblName);
79699  sqlite3DbFree(db, zName);
79700  return pRet;
79701}
79702
79703/*
79704** Fill the Index.aiRowEst[] array with default information - information
79705** to be used when we have not run the ANALYZE command.
79706**
79707** aiRowEst[0] is suppose to contain the number of elements in the index.
79708** Since we do not know, guess 1 million.  aiRowEst[1] is an estimate of the
79709** number of rows in the table that match any particular value of the
79710** first column of the index.  aiRowEst[2] is an estimate of the number
79711** of rows that match any particular combiniation of the first 2 columns
79712** of the index.  And so forth.  It must always be the case that
79713*
79714**           aiRowEst[N]<=aiRowEst[N-1]
79715**           aiRowEst[N]>=1
79716**
79717** Apart from that, we have little to go on besides intuition as to
79718** how aiRowEst[] should be initialized.  The numbers generated here
79719** are based on typical values found in actual indices.
79720*/
79721SQLITE_PRIVATE void sqlite3DefaultRowEst(Index *pIdx){
79722  unsigned *a = pIdx->aiRowEst;
79723  int i;
79724  unsigned n;
79725  assert( a!=0 );
79726  a[0] = pIdx->pTable->nRowEst;
79727  if( a[0]<10 ) a[0] = 10;
79728  n = 10;
79729  for(i=1; i<=pIdx->nColumn; i++){
79730    a[i] = n;
79731    if( n>5 ) n--;
79732  }
79733  if( pIdx->onError!=OE_None ){
79734    a[pIdx->nColumn] = 1;
79735  }
79736}
79737
79738/*
79739** This routine will drop an existing named index.  This routine
79740** implements the DROP INDEX statement.
79741*/
79742SQLITE_PRIVATE void sqlite3DropIndex(Parse *pParse, SrcList *pName, int ifExists){
79743  Index *pIndex;
79744  Vdbe *v;
79745  sqlite3 *db = pParse->db;
79746  int iDb;
79747
79748  assert( pParse->nErr==0 );   /* Never called with prior errors */
79749  if( db->mallocFailed ){
79750    goto exit_drop_index;
79751  }
79752  assert( pName->nSrc==1 );
79753  if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
79754    goto exit_drop_index;
79755  }
79756  pIndex = sqlite3FindIndex(db, pName->a[0].zName, pName->a[0].zDatabase);
79757  if( pIndex==0 ){
79758    if( !ifExists ){
79759      sqlite3ErrorMsg(pParse, "no such index: %S", pName, 0);
79760    }else{
79761      sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase);
79762    }
79763    pParse->checkSchema = 1;
79764    goto exit_drop_index;
79765  }
79766  if( pIndex->autoIndex ){
79767    sqlite3ErrorMsg(pParse, "index associated with UNIQUE "
79768      "or PRIMARY KEY constraint cannot be dropped", 0);
79769    goto exit_drop_index;
79770  }
79771  iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
79772#ifndef SQLITE_OMIT_AUTHORIZATION
79773  {
79774    int code = SQLITE_DROP_INDEX;
79775    Table *pTab = pIndex->pTable;
79776    const char *zDb = db->aDb[iDb].zName;
79777    const char *zTab = SCHEMA_TABLE(iDb);
79778    if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
79779      goto exit_drop_index;
79780    }
79781    if( !OMIT_TEMPDB && iDb ) code = SQLITE_DROP_TEMP_INDEX;
79782    if( sqlite3AuthCheck(pParse, code, pIndex->zName, pTab->zName, zDb) ){
79783      goto exit_drop_index;
79784    }
79785  }
79786#endif
79787
79788  /* Generate code to remove the index and from the master table */
79789  v = sqlite3GetVdbe(pParse);
79790  if( v ){
79791    sqlite3BeginWriteOperation(pParse, 1, iDb);
79792    sqlite3NestedParse(pParse,
79793       "DELETE FROM %Q.%s WHERE name=%Q AND type='index'",
79794       db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
79795       pIndex->zName
79796    );
79797    if( sqlite3FindTable(db, "sqlite_stat1", db->aDb[iDb].zName) ){
79798      sqlite3NestedParse(pParse,
79799        "DELETE FROM %Q.sqlite_stat1 WHERE idx=%Q",
79800        db->aDb[iDb].zName, pIndex->zName
79801      );
79802    }
79803    sqlite3ChangeCookie(pParse, iDb);
79804    destroyRootPage(pParse, pIndex->tnum, iDb);
79805    sqlite3VdbeAddOp4(v, OP_DropIndex, iDb, 0, 0, pIndex->zName, 0);
79806  }
79807
79808exit_drop_index:
79809  sqlite3SrcListDelete(db, pName);
79810}
79811
79812/*
79813** pArray is a pointer to an array of objects.  Each object in the
79814** array is szEntry bytes in size.  This routine allocates a new
79815** object on the end of the array.
79816**
79817** *pnEntry is the number of entries already in use.  *pnAlloc is
79818** the previously allocated size of the array.  initSize is the
79819** suggested initial array size allocation.
79820**
79821** The index of the new entry is returned in *pIdx.
79822**
79823** This routine returns a pointer to the array of objects.  This
79824** might be the same as the pArray parameter or it might be a different
79825** pointer if the array was resized.
79826*/
79827SQLITE_PRIVATE void *sqlite3ArrayAllocate(
79828  sqlite3 *db,      /* Connection to notify of malloc failures */
79829  void *pArray,     /* Array of objects.  Might be reallocated */
79830  int szEntry,      /* Size of each object in the array */
79831  int initSize,     /* Suggested initial allocation, in elements */
79832  int *pnEntry,     /* Number of objects currently in use */
79833  int *pnAlloc,     /* Current size of the allocation, in elements */
79834  int *pIdx         /* Write the index of a new slot here */
79835){
79836  char *z;
79837  if( *pnEntry >= *pnAlloc ){
79838    void *pNew;
79839    int newSize;
79840    newSize = (*pnAlloc)*2 + initSize;
79841    pNew = sqlite3DbRealloc(db, pArray, newSize*szEntry);
79842    if( pNew==0 ){
79843      *pIdx = -1;
79844      return pArray;
79845    }
79846    *pnAlloc = sqlite3DbMallocSize(db, pNew)/szEntry;
79847    pArray = pNew;
79848  }
79849  z = (char*)pArray;
79850  memset(&z[*pnEntry * szEntry], 0, szEntry);
79851  *pIdx = *pnEntry;
79852  ++*pnEntry;
79853  return pArray;
79854}
79855
79856/*
79857** Append a new element to the given IdList.  Create a new IdList if
79858** need be.
79859**
79860** A new IdList is returned, or NULL if malloc() fails.
79861*/
79862SQLITE_PRIVATE IdList *sqlite3IdListAppend(sqlite3 *db, IdList *pList, Token *pToken){
79863  int i;
79864  if( pList==0 ){
79865    pList = sqlite3DbMallocZero(db, sizeof(IdList) );
79866    if( pList==0 ) return 0;
79867    pList->nAlloc = 0;
79868  }
79869  pList->a = sqlite3ArrayAllocate(
79870      db,
79871      pList->a,
79872      sizeof(pList->a[0]),
79873      5,
79874      &pList->nId,
79875      &pList->nAlloc,
79876      &i
79877  );
79878  if( i<0 ){
79879    sqlite3IdListDelete(db, pList);
79880    return 0;
79881  }
79882  pList->a[i].zName = sqlite3NameFromToken(db, pToken);
79883  return pList;
79884}
79885
79886/*
79887** Delete an IdList.
79888*/
79889SQLITE_PRIVATE void sqlite3IdListDelete(sqlite3 *db, IdList *pList){
79890  int i;
79891  if( pList==0 ) return;
79892  for(i=0; i<pList->nId; i++){
79893    sqlite3DbFree(db, pList->a[i].zName);
79894  }
79895  sqlite3DbFree(db, pList->a);
79896  sqlite3DbFree(db, pList);
79897}
79898
79899/*
79900** Return the index in pList of the identifier named zId.  Return -1
79901** if not found.
79902*/
79903SQLITE_PRIVATE int sqlite3IdListIndex(IdList *pList, const char *zName){
79904  int i;
79905  if( pList==0 ) return -1;
79906  for(i=0; i<pList->nId; i++){
79907    if( sqlite3StrICmp(pList->a[i].zName, zName)==0 ) return i;
79908  }
79909  return -1;
79910}
79911
79912/*
79913** Expand the space allocated for the given SrcList object by
79914** creating nExtra new slots beginning at iStart.  iStart is zero based.
79915** New slots are zeroed.
79916**
79917** For example, suppose a SrcList initially contains two entries: A,B.
79918** To append 3 new entries onto the end, do this:
79919**
79920**    sqlite3SrcListEnlarge(db, pSrclist, 3, 2);
79921**
79922** After the call above it would contain:  A, B, nil, nil, nil.
79923** If the iStart argument had been 1 instead of 2, then the result
79924** would have been:  A, nil, nil, nil, B.  To prepend the new slots,
79925** the iStart value would be 0.  The result then would
79926** be: nil, nil, nil, A, B.
79927**
79928** If a memory allocation fails the SrcList is unchanged.  The
79929** db->mallocFailed flag will be set to true.
79930*/
79931SQLITE_PRIVATE SrcList *sqlite3SrcListEnlarge(
79932  sqlite3 *db,       /* Database connection to notify of OOM errors */
79933  SrcList *pSrc,     /* The SrcList to be enlarged */
79934  int nExtra,        /* Number of new slots to add to pSrc->a[] */
79935  int iStart         /* Index in pSrc->a[] of first new slot */
79936){
79937  int i;
79938
79939  /* Sanity checking on calling parameters */
79940  assert( iStart>=0 );
79941  assert( nExtra>=1 );
79942  assert( pSrc!=0 );
79943  assert( iStart<=pSrc->nSrc );
79944
79945  /* Allocate additional space if needed */
79946  if( pSrc->nSrc+nExtra>pSrc->nAlloc ){
79947    SrcList *pNew;
79948    int nAlloc = pSrc->nSrc+nExtra;
79949    int nGot;
79950    pNew = sqlite3DbRealloc(db, pSrc,
79951               sizeof(*pSrc) + (nAlloc-1)*sizeof(pSrc->a[0]) );
79952    if( pNew==0 ){
79953      assert( db->mallocFailed );
79954      return pSrc;
79955    }
79956    pSrc = pNew;
79957    nGot = (sqlite3DbMallocSize(db, pNew) - sizeof(*pSrc))/sizeof(pSrc->a[0])+1;
79958    pSrc->nAlloc = (u16)nGot;
79959  }
79960
79961  /* Move existing slots that come after the newly inserted slots
79962  ** out of the way */
79963  for(i=pSrc->nSrc-1; i>=iStart; i--){
79964    pSrc->a[i+nExtra] = pSrc->a[i];
79965  }
79966  pSrc->nSrc += (i16)nExtra;
79967
79968  /* Zero the newly allocated slots */
79969  memset(&pSrc->a[iStart], 0, sizeof(pSrc->a[0])*nExtra);
79970  for(i=iStart; i<iStart+nExtra; i++){
79971    pSrc->a[i].iCursor = -1;
79972  }
79973
79974  /* Return a pointer to the enlarged SrcList */
79975  return pSrc;
79976}
79977
79978
79979/*
79980** Append a new table name to the given SrcList.  Create a new SrcList if
79981** need be.  A new entry is created in the SrcList even if pTable is NULL.
79982**
79983** A SrcList is returned, or NULL if there is an OOM error.  The returned
79984** SrcList might be the same as the SrcList that was input or it might be
79985** a new one.  If an OOM error does occurs, then the prior value of pList
79986** that is input to this routine is automatically freed.
79987**
79988** If pDatabase is not null, it means that the table has an optional
79989** database name prefix.  Like this:  "database.table".  The pDatabase
79990** points to the table name and the pTable points to the database name.
79991** The SrcList.a[].zName field is filled with the table name which might
79992** come from pTable (if pDatabase is NULL) or from pDatabase.
79993** SrcList.a[].zDatabase is filled with the database name from pTable,
79994** or with NULL if no database is specified.
79995**
79996** In other words, if call like this:
79997**
79998**         sqlite3SrcListAppend(D,A,B,0);
79999**
80000** Then B is a table name and the database name is unspecified.  If called
80001** like this:
80002**
80003**         sqlite3SrcListAppend(D,A,B,C);
80004**
80005** Then C is the table name and B is the database name.  If C is defined
80006** then so is B.  In other words, we never have a case where:
80007**
80008**         sqlite3SrcListAppend(D,A,0,C);
80009**
80010** Both pTable and pDatabase are assumed to be quoted.  They are dequoted
80011** before being added to the SrcList.
80012*/
80013SQLITE_PRIVATE SrcList *sqlite3SrcListAppend(
80014  sqlite3 *db,        /* Connection to notify of malloc failures */
80015  SrcList *pList,     /* Append to this SrcList. NULL creates a new SrcList */
80016  Token *pTable,      /* Table to append */
80017  Token *pDatabase    /* Database of the table */
80018){
80019  struct SrcList_item *pItem;
80020  assert( pDatabase==0 || pTable!=0 );  /* Cannot have C without B */
80021  if( pList==0 ){
80022    pList = sqlite3DbMallocZero(db, sizeof(SrcList) );
80023    if( pList==0 ) return 0;
80024    pList->nAlloc = 1;
80025  }
80026  pList = sqlite3SrcListEnlarge(db, pList, 1, pList->nSrc);
80027  if( db->mallocFailed ){
80028    sqlite3SrcListDelete(db, pList);
80029    return 0;
80030  }
80031  pItem = &pList->a[pList->nSrc-1];
80032  if( pDatabase && pDatabase->z==0 ){
80033    pDatabase = 0;
80034  }
80035  if( pDatabase ){
80036    Token *pTemp = pDatabase;
80037    pDatabase = pTable;
80038    pTable = pTemp;
80039  }
80040  pItem->zName = sqlite3NameFromToken(db, pTable);
80041  pItem->zDatabase = sqlite3NameFromToken(db, pDatabase);
80042  return pList;
80043}
80044
80045/*
80046** Assign VdbeCursor index numbers to all tables in a SrcList
80047*/
80048SQLITE_PRIVATE void sqlite3SrcListAssignCursors(Parse *pParse, SrcList *pList){
80049  int i;
80050  struct SrcList_item *pItem;
80051  assert(pList || pParse->db->mallocFailed );
80052  if( pList ){
80053    for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
80054      if( pItem->iCursor>=0 ) break;
80055      pItem->iCursor = pParse->nTab++;
80056      if( pItem->pSelect ){
80057        sqlite3SrcListAssignCursors(pParse, pItem->pSelect->pSrc);
80058      }
80059    }
80060  }
80061}
80062
80063/*
80064** Delete an entire SrcList including all its substructure.
80065*/
80066SQLITE_PRIVATE void sqlite3SrcListDelete(sqlite3 *db, SrcList *pList){
80067  int i;
80068  struct SrcList_item *pItem;
80069  if( pList==0 ) return;
80070  for(pItem=pList->a, i=0; i<pList->nSrc; i++, pItem++){
80071    sqlite3DbFree(db, pItem->zDatabase);
80072    sqlite3DbFree(db, pItem->zName);
80073    sqlite3DbFree(db, pItem->zAlias);
80074    sqlite3DbFree(db, pItem->zIndex);
80075    sqlite3DeleteTable(db, pItem->pTab);
80076    sqlite3SelectDelete(db, pItem->pSelect);
80077    sqlite3ExprDelete(db, pItem->pOn);
80078    sqlite3IdListDelete(db, pItem->pUsing);
80079  }
80080  sqlite3DbFree(db, pList);
80081}
80082
80083/*
80084** This routine is called by the parser to add a new term to the
80085** end of a growing FROM clause.  The "p" parameter is the part of
80086** the FROM clause that has already been constructed.  "p" is NULL
80087** if this is the first term of the FROM clause.  pTable and pDatabase
80088** are the name of the table and database named in the FROM clause term.
80089** pDatabase is NULL if the database name qualifier is missing - the
80090** usual case.  If the term has a alias, then pAlias points to the
80091** alias token.  If the term is a subquery, then pSubquery is the
80092** SELECT statement that the subquery encodes.  The pTable and
80093** pDatabase parameters are NULL for subqueries.  The pOn and pUsing
80094** parameters are the content of the ON and USING clauses.
80095**
80096** Return a new SrcList which encodes is the FROM with the new
80097** term added.
80098*/
80099SQLITE_PRIVATE SrcList *sqlite3SrcListAppendFromTerm(
80100  Parse *pParse,          /* Parsing context */
80101  SrcList *p,             /* The left part of the FROM clause already seen */
80102  Token *pTable,          /* Name of the table to add to the FROM clause */
80103  Token *pDatabase,       /* Name of the database containing pTable */
80104  Token *pAlias,          /* The right-hand side of the AS subexpression */
80105  Select *pSubquery,      /* A subquery used in place of a table name */
80106  Expr *pOn,              /* The ON clause of a join */
80107  IdList *pUsing          /* The USING clause of a join */
80108){
80109  struct SrcList_item *pItem;
80110  sqlite3 *db = pParse->db;
80111  if( !p && (pOn || pUsing) ){
80112    sqlite3ErrorMsg(pParse, "a JOIN clause is required before %s",
80113      (pOn ? "ON" : "USING")
80114    );
80115    goto append_from_error;
80116  }
80117  p = sqlite3SrcListAppend(db, p, pTable, pDatabase);
80118  if( p==0 || NEVER(p->nSrc==0) ){
80119    goto append_from_error;
80120  }
80121  pItem = &p->a[p->nSrc-1];
80122  assert( pAlias!=0 );
80123  if( pAlias->n ){
80124    pItem->zAlias = sqlite3NameFromToken(db, pAlias);
80125  }
80126  pItem->pSelect = pSubquery;
80127  pItem->pOn = pOn;
80128  pItem->pUsing = pUsing;
80129  return p;
80130
80131 append_from_error:
80132  assert( p==0 );
80133  sqlite3ExprDelete(db, pOn);
80134  sqlite3IdListDelete(db, pUsing);
80135  sqlite3SelectDelete(db, pSubquery);
80136  return 0;
80137}
80138
80139/*
80140** Add an INDEXED BY or NOT INDEXED clause to the most recently added
80141** element of the source-list passed as the second argument.
80142*/
80143SQLITE_PRIVATE void sqlite3SrcListIndexedBy(Parse *pParse, SrcList *p, Token *pIndexedBy){
80144  assert( pIndexedBy!=0 );
80145  if( p && ALWAYS(p->nSrc>0) ){
80146    struct SrcList_item *pItem = &p->a[p->nSrc-1];
80147    assert( pItem->notIndexed==0 && pItem->zIndex==0 );
80148    if( pIndexedBy->n==1 && !pIndexedBy->z ){
80149      /* A "NOT INDEXED" clause was supplied. See parse.y
80150      ** construct "indexed_opt" for details. */
80151      pItem->notIndexed = 1;
80152    }else{
80153      pItem->zIndex = sqlite3NameFromToken(pParse->db, pIndexedBy);
80154    }
80155  }
80156}
80157
80158/*
80159** When building up a FROM clause in the parser, the join operator
80160** is initially attached to the left operand.  But the code generator
80161** expects the join operator to be on the right operand.  This routine
80162** Shifts all join operators from left to right for an entire FROM
80163** clause.
80164**
80165** Example: Suppose the join is like this:
80166**
80167**           A natural cross join B
80168**
80169** The operator is "natural cross join".  The A and B operands are stored
80170** in p->a[0] and p->a[1], respectively.  The parser initially stores the
80171** operator with A.  This routine shifts that operator over to B.
80172*/
80173SQLITE_PRIVATE void sqlite3SrcListShiftJoinType(SrcList *p){
80174  if( p && p->a ){
80175    int i;
80176    for(i=p->nSrc-1; i>0; i--){
80177      p->a[i].jointype = p->a[i-1].jointype;
80178    }
80179    p->a[0].jointype = 0;
80180  }
80181}
80182
80183/*
80184** Begin a transaction
80185*/
80186SQLITE_PRIVATE void sqlite3BeginTransaction(Parse *pParse, int type){
80187  sqlite3 *db;
80188  Vdbe *v;
80189  int i;
80190
80191  assert( pParse!=0 );
80192  db = pParse->db;
80193  assert( db!=0 );
80194/*  if( db->aDb[0].pBt==0 ) return; */
80195  if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "BEGIN", 0, 0) ){
80196    return;
80197  }
80198  v = sqlite3GetVdbe(pParse);
80199  if( !v ) return;
80200  if( type!=TK_DEFERRED ){
80201    for(i=0; i<db->nDb; i++){
80202      sqlite3VdbeAddOp2(v, OP_Transaction, i, (type==TK_EXCLUSIVE)+1);
80203      sqlite3VdbeUsesBtree(v, i);
80204    }
80205  }
80206  sqlite3VdbeAddOp2(v, OP_AutoCommit, 0, 0);
80207}
80208
80209/*
80210** Commit a transaction
80211*/
80212SQLITE_PRIVATE void sqlite3CommitTransaction(Parse *pParse){
80213  sqlite3 *db;
80214  Vdbe *v;
80215
80216  assert( pParse!=0 );
80217  db = pParse->db;
80218  assert( db!=0 );
80219/*  if( db->aDb[0].pBt==0 ) return; */
80220  if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "COMMIT", 0, 0) ){
80221    return;
80222  }
80223  v = sqlite3GetVdbe(pParse);
80224  if( v ){
80225    sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 0);
80226  }
80227}
80228
80229/*
80230** Rollback a transaction
80231*/
80232SQLITE_PRIVATE void sqlite3RollbackTransaction(Parse *pParse){
80233  sqlite3 *db;
80234  Vdbe *v;
80235
80236  assert( pParse!=0 );
80237  db = pParse->db;
80238  assert( db!=0 );
80239/*  if( db->aDb[0].pBt==0 ) return; */
80240  if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "ROLLBACK", 0, 0) ){
80241    return;
80242  }
80243  v = sqlite3GetVdbe(pParse);
80244  if( v ){
80245    sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 1);
80246  }
80247}
80248
80249/*
80250** This function is called by the parser when it parses a command to create,
80251** release or rollback an SQL savepoint.
80252*/
80253SQLITE_PRIVATE void sqlite3Savepoint(Parse *pParse, int op, Token *pName){
80254  char *zName = sqlite3NameFromToken(pParse->db, pName);
80255  if( zName ){
80256    Vdbe *v = sqlite3GetVdbe(pParse);
80257#ifndef SQLITE_OMIT_AUTHORIZATION
80258    static const char * const az[] = { "BEGIN", "RELEASE", "ROLLBACK" };
80259    assert( !SAVEPOINT_BEGIN && SAVEPOINT_RELEASE==1 && SAVEPOINT_ROLLBACK==2 );
80260#endif
80261    if( !v || sqlite3AuthCheck(pParse, SQLITE_SAVEPOINT, az[op], zName, 0) ){
80262      sqlite3DbFree(pParse->db, zName);
80263      return;
80264    }
80265    sqlite3VdbeAddOp4(v, OP_Savepoint, op, 0, 0, zName, P4_DYNAMIC);
80266  }
80267}
80268
80269/*
80270** Make sure the TEMP database is open and available for use.  Return
80271** the number of errors.  Leave any error messages in the pParse structure.
80272*/
80273SQLITE_PRIVATE int sqlite3OpenTempDatabase(Parse *pParse){
80274  sqlite3 *db = pParse->db;
80275  if( db->aDb[1].pBt==0 && !pParse->explain ){
80276    int rc;
80277    Btree *pBt;
80278    static const int flags =
80279          SQLITE_OPEN_READWRITE |
80280          SQLITE_OPEN_CREATE |
80281          SQLITE_OPEN_EXCLUSIVE |
80282          SQLITE_OPEN_DELETEONCLOSE |
80283          SQLITE_OPEN_TEMP_DB;
80284
80285    rc = sqlite3BtreeOpen(0, db, &pBt, 0, flags);
80286    if( rc!=SQLITE_OK ){
80287      sqlite3ErrorMsg(pParse, "unable to open a temporary database "
80288        "file for storing temporary tables");
80289      pParse->rc = rc;
80290      return 1;
80291    }
80292    db->aDb[1].pBt = pBt;
80293    assert( db->aDb[1].pSchema );
80294    if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize, -1, 0) ){
80295      db->mallocFailed = 1;
80296      return 1;
80297    }
80298  }
80299  return 0;
80300}
80301
80302/*
80303** Generate VDBE code that will verify the schema cookie and start
80304** a read-transaction for all named database files.
80305**
80306** It is important that all schema cookies be verified and all
80307** read transactions be started before anything else happens in
80308** the VDBE program.  But this routine can be called after much other
80309** code has been generated.  So here is what we do:
80310**
80311** The first time this routine is called, we code an OP_Goto that
80312** will jump to a subroutine at the end of the program.  Then we
80313** record every database that needs its schema verified in the
80314** pParse->cookieMask field.  Later, after all other code has been
80315** generated, the subroutine that does the cookie verifications and
80316** starts the transactions will be coded and the OP_Goto P2 value
80317** will be made to point to that subroutine.  The generation of the
80318** cookie verification subroutine code happens in sqlite3FinishCoding().
80319**
80320** If iDb<0 then code the OP_Goto only - don't set flag to verify the
80321** schema on any databases.  This can be used to position the OP_Goto
80322** early in the code, before we know if any database tables will be used.
80323*/
80324SQLITE_PRIVATE void sqlite3CodeVerifySchema(Parse *pParse, int iDb){
80325  Parse *pToplevel = sqlite3ParseToplevel(pParse);
80326
80327  if( pToplevel->cookieGoto==0 ){
80328    Vdbe *v = sqlite3GetVdbe(pToplevel);
80329    if( v==0 ) return;  /* This only happens if there was a prior error */
80330    pToplevel->cookieGoto = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0)+1;
80331  }
80332  if( iDb>=0 ){
80333    sqlite3 *db = pToplevel->db;
80334    yDbMask mask;
80335
80336    assert( iDb<db->nDb );
80337    assert( db->aDb[iDb].pBt!=0 || iDb==1 );
80338    assert( iDb<SQLITE_MAX_ATTACHED+2 );
80339    assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
80340    mask = ((yDbMask)1)<<iDb;
80341    if( (pToplevel->cookieMask & mask)==0 ){
80342      pToplevel->cookieMask |= mask;
80343      pToplevel->cookieValue[iDb] = db->aDb[iDb].pSchema->schema_cookie;
80344      if( !OMIT_TEMPDB && iDb==1 ){
80345        sqlite3OpenTempDatabase(pToplevel);
80346      }
80347    }
80348  }
80349}
80350
80351/*
80352** If argument zDb is NULL, then call sqlite3CodeVerifySchema() for each
80353** attached database. Otherwise, invoke it for the database named zDb only.
80354*/
80355SQLITE_PRIVATE void sqlite3CodeVerifyNamedSchema(Parse *pParse, const char *zDb){
80356  sqlite3 *db = pParse->db;
80357  int i;
80358  for(i=0; i<db->nDb; i++){
80359    Db *pDb = &db->aDb[i];
80360    if( pDb->pBt && (!zDb || 0==sqlite3StrICmp(zDb, pDb->zName)) ){
80361      sqlite3CodeVerifySchema(pParse, i);
80362    }
80363  }
80364}
80365
80366/*
80367** Generate VDBE code that prepares for doing an operation that
80368** might change the database.
80369**
80370** This routine starts a new transaction if we are not already within
80371** a transaction.  If we are already within a transaction, then a checkpoint
80372** is set if the setStatement parameter is true.  A checkpoint should
80373** be set for operations that might fail (due to a constraint) part of
80374** the way through and which will need to undo some writes without having to
80375** rollback the whole transaction.  For operations where all constraints
80376** can be checked before any changes are made to the database, it is never
80377** necessary to undo a write and the checkpoint should not be set.
80378*/
80379SQLITE_PRIVATE void sqlite3BeginWriteOperation(Parse *pParse, int setStatement, int iDb){
80380  Parse *pToplevel = sqlite3ParseToplevel(pParse);
80381  sqlite3CodeVerifySchema(pParse, iDb);
80382  pToplevel->writeMask |= ((yDbMask)1)<<iDb;
80383  pToplevel->isMultiWrite |= setStatement;
80384}
80385
80386/*
80387** Indicate that the statement currently under construction might write
80388** more than one entry (example: deleting one row then inserting another,
80389** inserting multiple rows in a table, or inserting a row and index entries.)
80390** If an abort occurs after some of these writes have completed, then it will
80391** be necessary to undo the completed writes.
80392*/
80393SQLITE_PRIVATE void sqlite3MultiWrite(Parse *pParse){
80394  Parse *pToplevel = sqlite3ParseToplevel(pParse);
80395  pToplevel->isMultiWrite = 1;
80396}
80397
80398/*
80399** The code generator calls this routine if is discovers that it is
80400** possible to abort a statement prior to completion.  In order to
80401** perform this abort without corrupting the database, we need to make
80402** sure that the statement is protected by a statement transaction.
80403**
80404** Technically, we only need to set the mayAbort flag if the
80405** isMultiWrite flag was previously set.  There is a time dependency
80406** such that the abort must occur after the multiwrite.  This makes
80407** some statements involving the REPLACE conflict resolution algorithm
80408** go a little faster.  But taking advantage of this time dependency
80409** makes it more difficult to prove that the code is correct (in
80410** particular, it prevents us from writing an effective
80411** implementation of sqlite3AssertMayAbort()) and so we have chosen
80412** to take the safe route and skip the optimization.
80413*/
80414SQLITE_PRIVATE void sqlite3MayAbort(Parse *pParse){
80415  Parse *pToplevel = sqlite3ParseToplevel(pParse);
80416  pToplevel->mayAbort = 1;
80417}
80418
80419/*
80420** Code an OP_Halt that causes the vdbe to return an SQLITE_CONSTRAINT
80421** error. The onError parameter determines which (if any) of the statement
80422** and/or current transaction is rolled back.
80423*/
80424SQLITE_PRIVATE void sqlite3HaltConstraint(Parse *pParse, int onError, char *p4, int p4type){
80425  Vdbe *v = sqlite3GetVdbe(pParse);
80426  if( onError==OE_Abort ){
80427    sqlite3MayAbort(pParse);
80428  }
80429  sqlite3VdbeAddOp4(v, OP_Halt, SQLITE_CONSTRAINT, onError, 0, p4, p4type);
80430}
80431
80432/*
80433** Check to see if pIndex uses the collating sequence pColl.  Return
80434** true if it does and false if it does not.
80435*/
80436#ifndef SQLITE_OMIT_REINDEX
80437static int collationMatch(const char *zColl, Index *pIndex){
80438  int i;
80439  assert( zColl!=0 );
80440  for(i=0; i<pIndex->nColumn; i++){
80441    const char *z = pIndex->azColl[i];
80442    assert( z!=0 );
80443    if( 0==sqlite3StrICmp(z, zColl) ){
80444      return 1;
80445    }
80446  }
80447  return 0;
80448}
80449#endif
80450
80451/*
80452** Recompute all indices of pTab that use the collating sequence pColl.
80453** If pColl==0 then recompute all indices of pTab.
80454*/
80455#ifndef SQLITE_OMIT_REINDEX
80456static void reindexTable(Parse *pParse, Table *pTab, char const *zColl){
80457  Index *pIndex;              /* An index associated with pTab */
80458
80459  for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
80460    if( zColl==0 || collationMatch(zColl, pIndex) ){
80461      int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
80462      sqlite3BeginWriteOperation(pParse, 0, iDb);
80463      sqlite3RefillIndex(pParse, pIndex, -1);
80464    }
80465  }
80466}
80467#endif
80468
80469/*
80470** Recompute all indices of all tables in all databases where the
80471** indices use the collating sequence pColl.  If pColl==0 then recompute
80472** all indices everywhere.
80473*/
80474#ifndef SQLITE_OMIT_REINDEX
80475static void reindexDatabases(Parse *pParse, char const *zColl){
80476  Db *pDb;                    /* A single database */
80477  int iDb;                    /* The database index number */
80478  sqlite3 *db = pParse->db;   /* The database connection */
80479  HashElem *k;                /* For looping over tables in pDb */
80480  Table *pTab;                /* A table in the database */
80481
80482  assert( sqlite3BtreeHoldsAllMutexes(db) );  /* Needed for schema access */
80483  for(iDb=0, pDb=db->aDb; iDb<db->nDb; iDb++, pDb++){
80484    assert( pDb!=0 );
80485    for(k=sqliteHashFirst(&pDb->pSchema->tblHash);  k; k=sqliteHashNext(k)){
80486      pTab = (Table*)sqliteHashData(k);
80487      reindexTable(pParse, pTab, zColl);
80488    }
80489  }
80490}
80491#endif
80492
80493/*
80494** Generate code for the REINDEX command.
80495**
80496**        REINDEX                            -- 1
80497**        REINDEX  <collation>               -- 2
80498**        REINDEX  ?<database>.?<tablename>  -- 3
80499**        REINDEX  ?<database>.?<indexname>  -- 4
80500**
80501** Form 1 causes all indices in all attached databases to be rebuilt.
80502** Form 2 rebuilds all indices in all databases that use the named
80503** collating function.  Forms 3 and 4 rebuild the named index or all
80504** indices associated with the named table.
80505*/
80506#ifndef SQLITE_OMIT_REINDEX
80507SQLITE_PRIVATE void sqlite3Reindex(Parse *pParse, Token *pName1, Token *pName2){
80508  CollSeq *pColl;             /* Collating sequence to be reindexed, or NULL */
80509  char *z;                    /* Name of a table or index */
80510  const char *zDb;            /* Name of the database */
80511  Table *pTab;                /* A table in the database */
80512  Index *pIndex;              /* An index associated with pTab */
80513  int iDb;                    /* The database index number */
80514  sqlite3 *db = pParse->db;   /* The database connection */
80515  Token *pObjName;            /* Name of the table or index to be reindexed */
80516
80517  /* Read the database schema. If an error occurs, leave an error message
80518  ** and code in pParse and return NULL. */
80519  if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
80520    return;
80521  }
80522
80523  if( pName1==0 ){
80524    reindexDatabases(pParse, 0);
80525    return;
80526  }else if( NEVER(pName2==0) || pName2->z==0 ){
80527    char *zColl;
80528    assert( pName1->z );
80529    zColl = sqlite3NameFromToken(pParse->db, pName1);
80530    if( !zColl ) return;
80531    pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
80532    if( pColl ){
80533      reindexDatabases(pParse, zColl);
80534      sqlite3DbFree(db, zColl);
80535      return;
80536    }
80537    sqlite3DbFree(db, zColl);
80538  }
80539  iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pObjName);
80540  if( iDb<0 ) return;
80541  z = sqlite3NameFromToken(db, pObjName);
80542  if( z==0 ) return;
80543  zDb = db->aDb[iDb].zName;
80544  pTab = sqlite3FindTable(db, z, zDb);
80545  if( pTab ){
80546    reindexTable(pParse, pTab, 0);
80547    sqlite3DbFree(db, z);
80548    return;
80549  }
80550  pIndex = sqlite3FindIndex(db, z, zDb);
80551  sqlite3DbFree(db, z);
80552  if( pIndex ){
80553    sqlite3BeginWriteOperation(pParse, 0, iDb);
80554    sqlite3RefillIndex(pParse, pIndex, -1);
80555    return;
80556  }
80557  sqlite3ErrorMsg(pParse, "unable to identify the object to be reindexed");
80558}
80559#endif
80560
80561/*
80562** Return a dynamicly allocated KeyInfo structure that can be used
80563** with OP_OpenRead or OP_OpenWrite to access database index pIdx.
80564**
80565** If successful, a pointer to the new structure is returned. In this case
80566** the caller is responsible for calling sqlite3DbFree(db, ) on the returned
80567** pointer. If an error occurs (out of memory or missing collation
80568** sequence), NULL is returned and the state of pParse updated to reflect
80569** the error.
80570*/
80571SQLITE_PRIVATE KeyInfo *sqlite3IndexKeyinfo(Parse *pParse, Index *pIdx){
80572  int i;
80573  int nCol = pIdx->nColumn;
80574  int nBytes = sizeof(KeyInfo) + (nCol-1)*sizeof(CollSeq*) + nCol;
80575  sqlite3 *db = pParse->db;
80576  KeyInfo *pKey = (KeyInfo *)sqlite3DbMallocZero(db, nBytes);
80577
80578  if( pKey ){
80579    pKey->db = pParse->db;
80580    pKey->aSortOrder = (u8 *)&(pKey->aColl[nCol]);
80581    assert( &pKey->aSortOrder[nCol]==&(((u8 *)pKey)[nBytes]) );
80582    for(i=0; i<nCol; i++){
80583      char *zColl = pIdx->azColl[i];
80584      assert( zColl );
80585      pKey->aColl[i] = sqlite3LocateCollSeq(pParse, zColl);
80586      pKey->aSortOrder[i] = pIdx->aSortOrder[i];
80587    }
80588    pKey->nField = (u16)nCol;
80589  }
80590
80591  if( pParse->nErr ){
80592    sqlite3DbFree(db, pKey);
80593    pKey = 0;
80594  }
80595  return pKey;
80596}
80597
80598/************** End of build.c ***********************************************/
80599/************** Begin file callback.c ****************************************/
80600/*
80601** 2005 May 23
80602**
80603** The author disclaims copyright to this source code.  In place of
80604** a legal notice, here is a blessing:
80605**
80606**    May you do good and not evil.
80607**    May you find forgiveness for yourself and forgive others.
80608**    May you share freely, never taking more than you give.
80609**
80610*************************************************************************
80611**
80612** This file contains functions used to access the internal hash tables
80613** of user defined functions and collation sequences.
80614*/
80615
80616
80617/*
80618** Invoke the 'collation needed' callback to request a collation sequence
80619** in the encoding enc of name zName, length nName.
80620*/
80621static void callCollNeeded(sqlite3 *db, int enc, const char *zName){
80622  assert( !db->xCollNeeded || !db->xCollNeeded16 );
80623  if( db->xCollNeeded ){
80624    char *zExternal = sqlite3DbStrDup(db, zName);
80625    if( !zExternal ) return;
80626    db->xCollNeeded(db->pCollNeededArg, db, enc, zExternal);
80627    sqlite3DbFree(db, zExternal);
80628  }
80629#ifndef SQLITE_OMIT_UTF16
80630  if( db->xCollNeeded16 ){
80631    char const *zExternal;
80632    sqlite3_value *pTmp = sqlite3ValueNew(db);
80633    sqlite3ValueSetStr(pTmp, -1, zName, SQLITE_UTF8, SQLITE_STATIC);
80634    zExternal = sqlite3ValueText(pTmp, SQLITE_UTF16NATIVE);
80635    if( zExternal ){
80636      db->xCollNeeded16(db->pCollNeededArg, db, (int)ENC(db), zExternal);
80637    }
80638    sqlite3ValueFree(pTmp);
80639  }
80640#endif
80641}
80642
80643/*
80644** This routine is called if the collation factory fails to deliver a
80645** collation function in the best encoding but there may be other versions
80646** of this collation function (for other text encodings) available. Use one
80647** of these instead if they exist. Avoid a UTF-8 <-> UTF-16 conversion if
80648** possible.
80649*/
80650static int synthCollSeq(sqlite3 *db, CollSeq *pColl){
80651  CollSeq *pColl2;
80652  char *z = pColl->zName;
80653  int i;
80654  static const u8 aEnc[] = { SQLITE_UTF16BE, SQLITE_UTF16LE, SQLITE_UTF8 };
80655  for(i=0; i<3; i++){
80656    pColl2 = sqlite3FindCollSeq(db, aEnc[i], z, 0);
80657    if( pColl2->xCmp!=0 ){
80658      memcpy(pColl, pColl2, sizeof(CollSeq));
80659      pColl->xDel = 0;         /* Do not copy the destructor */
80660      return SQLITE_OK;
80661    }
80662  }
80663  return SQLITE_ERROR;
80664}
80665
80666/*
80667** This function is responsible for invoking the collation factory callback
80668** or substituting a collation sequence of a different encoding when the
80669** requested collation sequence is not available in the desired encoding.
80670**
80671** If it is not NULL, then pColl must point to the database native encoding
80672** collation sequence with name zName, length nName.
80673**
80674** The return value is either the collation sequence to be used in database
80675** db for collation type name zName, length nName, or NULL, if no collation
80676** sequence can be found.
80677**
80678** See also: sqlite3LocateCollSeq(), sqlite3FindCollSeq()
80679*/
80680SQLITE_PRIVATE CollSeq *sqlite3GetCollSeq(
80681  sqlite3* db,          /* The database connection */
80682  u8 enc,               /* The desired encoding for the collating sequence */
80683  CollSeq *pColl,       /* Collating sequence with native encoding, or NULL */
80684  const char *zName     /* Collating sequence name */
80685){
80686  CollSeq *p;
80687
80688  p = pColl;
80689  if( !p ){
80690    p = sqlite3FindCollSeq(db, enc, zName, 0);
80691  }
80692  if( !p || !p->xCmp ){
80693    /* No collation sequence of this type for this encoding is registered.
80694    ** Call the collation factory to see if it can supply us with one.
80695    */
80696    callCollNeeded(db, enc, zName);
80697    p = sqlite3FindCollSeq(db, enc, zName, 0);
80698  }
80699  if( p && !p->xCmp && synthCollSeq(db, p) ){
80700    p = 0;
80701  }
80702  assert( !p || p->xCmp );
80703  return p;
80704}
80705
80706/*
80707** This routine is called on a collation sequence before it is used to
80708** check that it is defined. An undefined collation sequence exists when
80709** a database is loaded that contains references to collation sequences
80710** that have not been defined by sqlite3_create_collation() etc.
80711**
80712** If required, this routine calls the 'collation needed' callback to
80713** request a definition of the collating sequence. If this doesn't work,
80714** an equivalent collating sequence that uses a text encoding different
80715** from the main database is substituted, if one is available.
80716*/
80717SQLITE_PRIVATE int sqlite3CheckCollSeq(Parse *pParse, CollSeq *pColl){
80718  if( pColl ){
80719    const char *zName = pColl->zName;
80720    sqlite3 *db = pParse->db;
80721    CollSeq *p = sqlite3GetCollSeq(db, ENC(db), pColl, zName);
80722    if( !p ){
80723      sqlite3ErrorMsg(pParse, "no such collation sequence: %s", zName);
80724      pParse->nErr++;
80725      return SQLITE_ERROR;
80726    }
80727    assert( p==pColl );
80728  }
80729  return SQLITE_OK;
80730}
80731
80732
80733
80734/*
80735** Locate and return an entry from the db.aCollSeq hash table. If the entry
80736** specified by zName and nName is not found and parameter 'create' is
80737** true, then create a new entry. Otherwise return NULL.
80738**
80739** Each pointer stored in the sqlite3.aCollSeq hash table contains an
80740** array of three CollSeq structures. The first is the collation sequence
80741** prefferred for UTF-8, the second UTF-16le, and the third UTF-16be.
80742**
80743** Stored immediately after the three collation sequences is a copy of
80744** the collation sequence name. A pointer to this string is stored in
80745** each collation sequence structure.
80746*/
80747static CollSeq *findCollSeqEntry(
80748  sqlite3 *db,          /* Database connection */
80749  const char *zName,    /* Name of the collating sequence */
80750  int create            /* Create a new entry if true */
80751){
80752  CollSeq *pColl;
80753  int nName = sqlite3Strlen30(zName);
80754  pColl = sqlite3HashFind(&db->aCollSeq, zName, nName);
80755
80756  if( 0==pColl && create ){
80757    pColl = sqlite3DbMallocZero(db, 3*sizeof(*pColl) + nName + 1 );
80758    if( pColl ){
80759      CollSeq *pDel = 0;
80760      pColl[0].zName = (char*)&pColl[3];
80761      pColl[0].enc = SQLITE_UTF8;
80762      pColl[1].zName = (char*)&pColl[3];
80763      pColl[1].enc = SQLITE_UTF16LE;
80764      pColl[2].zName = (char*)&pColl[3];
80765      pColl[2].enc = SQLITE_UTF16BE;
80766      memcpy(pColl[0].zName, zName, nName);
80767      pColl[0].zName[nName] = 0;
80768      pDel = sqlite3HashInsert(&db->aCollSeq, pColl[0].zName, nName, pColl);
80769
80770      /* If a malloc() failure occurred in sqlite3HashInsert(), it will
80771      ** return the pColl pointer to be deleted (because it wasn't added
80772      ** to the hash table).
80773      */
80774      assert( pDel==0 || pDel==pColl );
80775      if( pDel!=0 ){
80776        db->mallocFailed = 1;
80777        sqlite3DbFree(db, pDel);
80778        pColl = 0;
80779      }
80780    }
80781  }
80782  return pColl;
80783}
80784
80785/*
80786** Parameter zName points to a UTF-8 encoded string nName bytes long.
80787** Return the CollSeq* pointer for the collation sequence named zName
80788** for the encoding 'enc' from the database 'db'.
80789**
80790** If the entry specified is not found and 'create' is true, then create a
80791** new entry.  Otherwise return NULL.
80792**
80793** A separate function sqlite3LocateCollSeq() is a wrapper around
80794** this routine.  sqlite3LocateCollSeq() invokes the collation factory
80795** if necessary and generates an error message if the collating sequence
80796** cannot be found.
80797**
80798** See also: sqlite3LocateCollSeq(), sqlite3GetCollSeq()
80799*/
80800SQLITE_PRIVATE CollSeq *sqlite3FindCollSeq(
80801  sqlite3 *db,
80802  u8 enc,
80803  const char *zName,
80804  int create
80805){
80806  CollSeq *pColl;
80807  if( zName ){
80808    pColl = findCollSeqEntry(db, zName, create);
80809  }else{
80810    pColl = db->pDfltColl;
80811  }
80812  assert( SQLITE_UTF8==1 && SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
80813  assert( enc>=SQLITE_UTF8 && enc<=SQLITE_UTF16BE );
80814  if( pColl ) pColl += enc-1;
80815  return pColl;
80816}
80817
80818/* During the search for the best function definition, this procedure
80819** is called to test how well the function passed as the first argument
80820** matches the request for a function with nArg arguments in a system
80821** that uses encoding enc. The value returned indicates how well the
80822** request is matched. A higher value indicates a better match.
80823**
80824** The returned value is always between 0 and 6, as follows:
80825**
80826** 0: Not a match, or if nArg<0 and the function is has no implementation.
80827** 1: A variable arguments function that prefers UTF-8 when a UTF-16
80828**    encoding is requested, or vice versa.
80829** 2: A variable arguments function that uses UTF-16BE when UTF-16LE is
80830**    requested, or vice versa.
80831** 3: A variable arguments function using the same text encoding.
80832** 4: A function with the exact number of arguments requested that
80833**    prefers UTF-8 when a UTF-16 encoding is requested, or vice versa.
80834** 5: A function with the exact number of arguments requested that
80835**    prefers UTF-16LE when UTF-16BE is requested, or vice versa.
80836** 6: An exact match.
80837**
80838*/
80839static int matchQuality(FuncDef *p, int nArg, u8 enc){
80840  int match = 0;
80841  if( p->nArg==-1 || p->nArg==nArg
80842   || (nArg==-1 && (p->xFunc!=0 || p->xStep!=0))
80843  ){
80844    match = 1;
80845    if( p->nArg==nArg || nArg==-1 ){
80846      match = 4;
80847    }
80848    if( enc==p->iPrefEnc ){
80849      match += 2;
80850    }
80851    else if( (enc==SQLITE_UTF16LE && p->iPrefEnc==SQLITE_UTF16BE) ||
80852             (enc==SQLITE_UTF16BE && p->iPrefEnc==SQLITE_UTF16LE) ){
80853      match += 1;
80854    }
80855  }
80856  return match;
80857}
80858
80859/*
80860** Search a FuncDefHash for a function with the given name.  Return
80861** a pointer to the matching FuncDef if found, or 0 if there is no match.
80862*/
80863static FuncDef *functionSearch(
80864  FuncDefHash *pHash,  /* Hash table to search */
80865  int h,               /* Hash of the name */
80866  const char *zFunc,   /* Name of function */
80867  int nFunc            /* Number of bytes in zFunc */
80868){
80869  FuncDef *p;
80870  for(p=pHash->a[h]; p; p=p->pHash){
80871    if( sqlite3StrNICmp(p->zName, zFunc, nFunc)==0 && p->zName[nFunc]==0 ){
80872      return p;
80873    }
80874  }
80875  return 0;
80876}
80877
80878/*
80879** Insert a new FuncDef into a FuncDefHash hash table.
80880*/
80881SQLITE_PRIVATE void sqlite3FuncDefInsert(
80882  FuncDefHash *pHash,  /* The hash table into which to insert */
80883  FuncDef *pDef        /* The function definition to insert */
80884){
80885  FuncDef *pOther;
80886  int nName = sqlite3Strlen30(pDef->zName);
80887  u8 c1 = (u8)pDef->zName[0];
80888  int h = (sqlite3UpperToLower[c1] + nName) % ArraySize(pHash->a);
80889  pOther = functionSearch(pHash, h, pDef->zName, nName);
80890  if( pOther ){
80891    assert( pOther!=pDef && pOther->pNext!=pDef );
80892    pDef->pNext = pOther->pNext;
80893    pOther->pNext = pDef;
80894  }else{
80895    pDef->pNext = 0;
80896    pDef->pHash = pHash->a[h];
80897    pHash->a[h] = pDef;
80898  }
80899}
80900
80901
80902
80903/*
80904** Locate a user function given a name, a number of arguments and a flag
80905** indicating whether the function prefers UTF-16 over UTF-8.  Return a
80906** pointer to the FuncDef structure that defines that function, or return
80907** NULL if the function does not exist.
80908**
80909** If the createFlag argument is true, then a new (blank) FuncDef
80910** structure is created and liked into the "db" structure if a
80911** no matching function previously existed.  When createFlag is true
80912** and the nArg parameter is -1, then only a function that accepts
80913** any number of arguments will be returned.
80914**
80915** If createFlag is false and nArg is -1, then the first valid
80916** function found is returned.  A function is valid if either xFunc
80917** or xStep is non-zero.
80918**
80919** If createFlag is false, then a function with the required name and
80920** number of arguments may be returned even if the eTextRep flag does not
80921** match that requested.
80922*/
80923SQLITE_PRIVATE FuncDef *sqlite3FindFunction(
80924  sqlite3 *db,       /* An open database */
80925  const char *zName, /* Name of the function.  Not null-terminated */
80926  int nName,         /* Number of characters in the name */
80927  int nArg,          /* Number of arguments.  -1 means any number */
80928  u8 enc,            /* Preferred text encoding */
80929  int createFlag     /* Create new entry if true and does not otherwise exist */
80930){
80931  FuncDef *p;         /* Iterator variable */
80932  FuncDef *pBest = 0; /* Best match found so far */
80933  int bestScore = 0;  /* Score of best match */
80934  int h;              /* Hash value */
80935
80936
80937  assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE );
80938  h = (sqlite3UpperToLower[(u8)zName[0]] + nName) % ArraySize(db->aFunc.a);
80939
80940  /* First search for a match amongst the application-defined functions.
80941  */
80942  p = functionSearch(&db->aFunc, h, zName, nName);
80943  while( p ){
80944    int score = matchQuality(p, nArg, enc);
80945    if( score>bestScore ){
80946      pBest = p;
80947      bestScore = score;
80948    }
80949    p = p->pNext;
80950  }
80951
80952  /* If no match is found, search the built-in functions.
80953  **
80954  ** If the SQLITE_PreferBuiltin flag is set, then search the built-in
80955  ** functions even if a prior app-defined function was found.  And give
80956  ** priority to built-in functions.
80957  **
80958  ** Except, if createFlag is true, that means that we are trying to
80959  ** install a new function.  Whatever FuncDef structure is returned it will
80960  ** have fields overwritten with new information appropriate for the
80961  ** new function.  But the FuncDefs for built-in functions are read-only.
80962  ** So we must not search for built-ins when creating a new function.
80963  */
80964  if( !createFlag && (pBest==0 || (db->flags & SQLITE_PreferBuiltin)!=0) ){
80965    FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
80966    bestScore = 0;
80967    p = functionSearch(pHash, h, zName, nName);
80968    while( p ){
80969      int score = matchQuality(p, nArg, enc);
80970      if( score>bestScore ){
80971        pBest = p;
80972        bestScore = score;
80973      }
80974      p = p->pNext;
80975    }
80976  }
80977
80978  /* If the createFlag parameter is true and the search did not reveal an
80979  ** exact match for the name, number of arguments and encoding, then add a
80980  ** new entry to the hash table and return it.
80981  */
80982  if( createFlag && (bestScore<6 || pBest->nArg!=nArg) &&
80983      (pBest = sqlite3DbMallocZero(db, sizeof(*pBest)+nName+1))!=0 ){
80984    pBest->zName = (char *)&pBest[1];
80985    pBest->nArg = (u16)nArg;
80986    pBest->iPrefEnc = enc;
80987    memcpy(pBest->zName, zName, nName);
80988    pBest->zName[nName] = 0;
80989    sqlite3FuncDefInsert(&db->aFunc, pBest);
80990  }
80991
80992  if( pBest && (pBest->xStep || pBest->xFunc || createFlag) ){
80993    return pBest;
80994  }
80995  return 0;
80996}
80997
80998/*
80999** Free all resources held by the schema structure. The void* argument points
81000** at a Schema struct. This function does not call sqlite3DbFree(db, ) on the
81001** pointer itself, it just cleans up subsidiary resources (i.e. the contents
81002** of the schema hash tables).
81003**
81004** The Schema.cache_size variable is not cleared.
81005*/
81006SQLITE_PRIVATE void sqlite3SchemaClear(void *p){
81007  Hash temp1;
81008  Hash temp2;
81009  HashElem *pElem;
81010  Schema *pSchema = (Schema *)p;
81011
81012  temp1 = pSchema->tblHash;
81013  temp2 = pSchema->trigHash;
81014  sqlite3HashInit(&pSchema->trigHash);
81015  sqlite3HashClear(&pSchema->idxHash);
81016  for(pElem=sqliteHashFirst(&temp2); pElem; pElem=sqliteHashNext(pElem)){
81017    sqlite3DeleteTrigger(0, (Trigger*)sqliteHashData(pElem));
81018  }
81019  sqlite3HashClear(&temp2);
81020  sqlite3HashInit(&pSchema->tblHash);
81021  for(pElem=sqliteHashFirst(&temp1); pElem; pElem=sqliteHashNext(pElem)){
81022    Table *pTab = sqliteHashData(pElem);
81023    sqlite3DeleteTable(0, pTab);
81024  }
81025  sqlite3HashClear(&temp1);
81026  sqlite3HashClear(&pSchema->fkeyHash);
81027  pSchema->pSeqTab = 0;
81028  if( pSchema->flags & DB_SchemaLoaded ){
81029    pSchema->iGeneration++;
81030    pSchema->flags &= ~DB_SchemaLoaded;
81031  }
81032}
81033
81034/*
81035** Find and return the schema associated with a BTree.  Create
81036** a new one if necessary.
81037*/
81038SQLITE_PRIVATE Schema *sqlite3SchemaGet(sqlite3 *db, Btree *pBt){
81039  Schema * p;
81040  if( pBt ){
81041    p = (Schema *)sqlite3BtreeSchema(pBt, sizeof(Schema), sqlite3SchemaClear);
81042  }else{
81043    p = (Schema *)sqlite3DbMallocZero(0, sizeof(Schema));
81044  }
81045  if( !p ){
81046    db->mallocFailed = 1;
81047  }else if ( 0==p->file_format ){
81048    sqlite3HashInit(&p->tblHash);
81049    sqlite3HashInit(&p->idxHash);
81050    sqlite3HashInit(&p->trigHash);
81051    sqlite3HashInit(&p->fkeyHash);
81052    p->enc = SQLITE_UTF8;
81053  }
81054  return p;
81055}
81056
81057/************** End of callback.c ********************************************/
81058/************** Begin file delete.c ******************************************/
81059/*
81060** 2001 September 15
81061**
81062** The author disclaims copyright to this source code.  In place of
81063** a legal notice, here is a blessing:
81064**
81065**    May you do good and not evil.
81066**    May you find forgiveness for yourself and forgive others.
81067**    May you share freely, never taking more than you give.
81068**
81069*************************************************************************
81070** This file contains C code routines that are called by the parser
81071** in order to generate code for DELETE FROM statements.
81072*/
81073
81074/*
81075** While a SrcList can in general represent multiple tables and subqueries
81076** (as in the FROM clause of a SELECT statement) in this case it contains
81077** the name of a single table, as one might find in an INSERT, DELETE,
81078** or UPDATE statement.  Look up that table in the symbol table and
81079** return a pointer.  Set an error message and return NULL if the table
81080** name is not found or if any other error occurs.
81081**
81082** The following fields are initialized appropriate in pSrc:
81083**
81084**    pSrc->a[0].pTab       Pointer to the Table object
81085**    pSrc->a[0].pIndex     Pointer to the INDEXED BY index, if there is one
81086**
81087*/
81088SQLITE_PRIVATE Table *sqlite3SrcListLookup(Parse *pParse, SrcList *pSrc){
81089  struct SrcList_item *pItem = pSrc->a;
81090  Table *pTab;
81091  assert( pItem && pSrc->nSrc==1 );
81092  pTab = sqlite3LocateTable(pParse, 0, pItem->zName, pItem->zDatabase);
81093  sqlite3DeleteTable(pParse->db, pItem->pTab);
81094  pItem->pTab = pTab;
81095  if( pTab ){
81096    pTab->nRef++;
81097  }
81098  if( sqlite3IndexedByLookup(pParse, pItem) ){
81099    pTab = 0;
81100  }
81101  return pTab;
81102}
81103
81104/*
81105** Check to make sure the given table is writable.  If it is not
81106** writable, generate an error message and return 1.  If it is
81107** writable return 0;
81108*/
81109SQLITE_PRIVATE int sqlite3IsReadOnly(Parse *pParse, Table *pTab, int viewOk){
81110  /* A table is not writable under the following circumstances:
81111  **
81112  **   1) It is a virtual table and no implementation of the xUpdate method
81113  **      has been provided, or
81114  **   2) It is a system table (i.e. sqlite_master), this call is not
81115  **      part of a nested parse and writable_schema pragma has not
81116  **      been specified.
81117  **
81118  ** In either case leave an error message in pParse and return non-zero.
81119  */
81120  if( ( IsVirtual(pTab)
81121     && sqlite3GetVTable(pParse->db, pTab)->pMod->pModule->xUpdate==0 )
81122   || ( (pTab->tabFlags & TF_Readonly)!=0
81123     && (pParse->db->flags & SQLITE_WriteSchema)==0
81124     && pParse->nested==0 )
81125  ){
81126    sqlite3ErrorMsg(pParse, "table %s may not be modified", pTab->zName);
81127    return 1;
81128  }
81129
81130#ifndef SQLITE_OMIT_VIEW
81131  if( !viewOk && pTab->pSelect ){
81132    sqlite3ErrorMsg(pParse,"cannot modify %s because it is a view",pTab->zName);
81133    return 1;
81134  }
81135#endif
81136  return 0;
81137}
81138
81139
81140#if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
81141/*
81142** Evaluate a view and store its result in an ephemeral table.  The
81143** pWhere argument is an optional WHERE clause that restricts the
81144** set of rows in the view that are to be added to the ephemeral table.
81145*/
81146SQLITE_PRIVATE void sqlite3MaterializeView(
81147  Parse *pParse,       /* Parsing context */
81148  Table *pView,        /* View definition */
81149  Expr *pWhere,        /* Optional WHERE clause to be added */
81150  int iCur             /* Cursor number for ephemerial table */
81151){
81152  SelectDest dest;
81153  Select *pDup;
81154  sqlite3 *db = pParse->db;
81155
81156  pDup = sqlite3SelectDup(db, pView->pSelect, 0);
81157  if( pWhere ){
81158    SrcList *pFrom;
81159
81160    pWhere = sqlite3ExprDup(db, pWhere, 0);
81161    pFrom = sqlite3SrcListAppend(db, 0, 0, 0);
81162    if( pFrom ){
81163      assert( pFrom->nSrc==1 );
81164      pFrom->a[0].zAlias = sqlite3DbStrDup(db, pView->zName);
81165      pFrom->a[0].pSelect = pDup;
81166      assert( pFrom->a[0].pOn==0 );
81167      assert( pFrom->a[0].pUsing==0 );
81168    }else{
81169      sqlite3SelectDelete(db, pDup);
81170    }
81171    pDup = sqlite3SelectNew(pParse, 0, pFrom, pWhere, 0, 0, 0, 0, 0, 0);
81172  }
81173  sqlite3SelectDestInit(&dest, SRT_EphemTab, iCur);
81174  sqlite3Select(pParse, pDup, &dest);
81175  sqlite3SelectDelete(db, pDup);
81176}
81177#endif /* !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER) */
81178
81179#if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
81180/*
81181** Generate an expression tree to implement the WHERE, ORDER BY,
81182** and LIMIT/OFFSET portion of DELETE and UPDATE statements.
81183**
81184**     DELETE FROM table_wxyz WHERE a<5 ORDER BY a LIMIT 1;
81185**                            \__________________________/
81186**                               pLimitWhere (pInClause)
81187*/
81188SQLITE_PRIVATE Expr *sqlite3LimitWhere(
81189  Parse *pParse,               /* The parser context */
81190  SrcList *pSrc,               /* the FROM clause -- which tables to scan */
81191  Expr *pWhere,                /* The WHERE clause.  May be null */
81192  ExprList *pOrderBy,          /* The ORDER BY clause.  May be null */
81193  Expr *pLimit,                /* The LIMIT clause.  May be null */
81194  Expr *pOffset,               /* The OFFSET clause.  May be null */
81195  char *zStmtType              /* Either DELETE or UPDATE.  For error messages. */
81196){
81197  Expr *pWhereRowid = NULL;    /* WHERE rowid .. */
81198  Expr *pInClause = NULL;      /* WHERE rowid IN ( select ) */
81199  Expr *pSelectRowid = NULL;   /* SELECT rowid ... */
81200  ExprList *pEList = NULL;     /* Expression list contaning only pSelectRowid */
81201  SrcList *pSelectSrc = NULL;  /* SELECT rowid FROM x ... (dup of pSrc) */
81202  Select *pSelect = NULL;      /* Complete SELECT tree */
81203
81204  /* Check that there isn't an ORDER BY without a LIMIT clause.
81205  */
81206  if( pOrderBy && (pLimit == 0) ) {
81207    sqlite3ErrorMsg(pParse, "ORDER BY without LIMIT on %s", zStmtType);
81208    pParse->parseError = 1;
81209    goto limit_where_cleanup_2;
81210  }
81211
81212  /* We only need to generate a select expression if there
81213  ** is a limit/offset term to enforce.
81214  */
81215  if( pLimit == 0 ) {
81216    /* if pLimit is null, pOffset will always be null as well. */
81217    assert( pOffset == 0 );
81218    return pWhere;
81219  }
81220
81221  /* Generate a select expression tree to enforce the limit/offset
81222  ** term for the DELETE or UPDATE statement.  For example:
81223  **   DELETE FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1
81224  ** becomes:
81225  **   DELETE FROM table_a WHERE rowid IN (
81226  **     SELECT rowid FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1
81227  **   );
81228  */
81229
81230  pSelectRowid = sqlite3PExpr(pParse, TK_ROW, 0, 0, 0);
81231  if( pSelectRowid == 0 ) goto limit_where_cleanup_2;
81232  pEList = sqlite3ExprListAppend(pParse, 0, pSelectRowid);
81233  if( pEList == 0 ) goto limit_where_cleanup_2;
81234
81235  /* duplicate the FROM clause as it is needed by both the DELETE/UPDATE tree
81236  ** and the SELECT subtree. */
81237  pSelectSrc = sqlite3SrcListDup(pParse->db, pSrc, 0);
81238  if( pSelectSrc == 0 ) {
81239    sqlite3ExprListDelete(pParse->db, pEList);
81240    goto limit_where_cleanup_2;
81241  }
81242
81243  /* generate the SELECT expression tree. */
81244  pSelect = sqlite3SelectNew(pParse,pEList,pSelectSrc,pWhere,0,0,
81245                             pOrderBy,0,pLimit,pOffset);
81246  if( pSelect == 0 ) return 0;
81247
81248  /* now generate the new WHERE rowid IN clause for the DELETE/UDPATE */
81249  pWhereRowid = sqlite3PExpr(pParse, TK_ROW, 0, 0, 0);
81250  if( pWhereRowid == 0 ) goto limit_where_cleanup_1;
81251  pInClause = sqlite3PExpr(pParse, TK_IN, pWhereRowid, 0, 0);
81252  if( pInClause == 0 ) goto limit_where_cleanup_1;
81253
81254  pInClause->x.pSelect = pSelect;
81255  pInClause->flags |= EP_xIsSelect;
81256  sqlite3ExprSetHeight(pParse, pInClause);
81257  return pInClause;
81258
81259  /* something went wrong. clean up anything allocated. */
81260limit_where_cleanup_1:
81261  sqlite3SelectDelete(pParse->db, pSelect);
81262  return 0;
81263
81264limit_where_cleanup_2:
81265  sqlite3ExprDelete(pParse->db, pWhere);
81266  sqlite3ExprListDelete(pParse->db, pOrderBy);
81267  sqlite3ExprDelete(pParse->db, pLimit);
81268  sqlite3ExprDelete(pParse->db, pOffset);
81269  return 0;
81270}
81271#endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY) */
81272
81273/*
81274** Generate code for a DELETE FROM statement.
81275**
81276**     DELETE FROM table_wxyz WHERE a<5 AND b NOT NULL;
81277**                 \________/       \________________/
81278**                  pTabList              pWhere
81279*/
81280SQLITE_PRIVATE void sqlite3DeleteFrom(
81281  Parse *pParse,         /* The parser context */
81282  SrcList *pTabList,     /* The table from which we should delete things */
81283  Expr *pWhere           /* The WHERE clause.  May be null */
81284){
81285  Vdbe *v;               /* The virtual database engine */
81286  Table *pTab;           /* The table from which records will be deleted */
81287  const char *zDb;       /* Name of database holding pTab */
81288  int end, addr = 0;     /* A couple addresses of generated code */
81289  int i;                 /* Loop counter */
81290  WhereInfo *pWInfo;     /* Information about the WHERE clause */
81291  Index *pIdx;           /* For looping over indices of the table */
81292  int iCur;              /* VDBE Cursor number for pTab */
81293  sqlite3 *db;           /* Main database structure */
81294  AuthContext sContext;  /* Authorization context */
81295  NameContext sNC;       /* Name context to resolve expressions in */
81296  int iDb;               /* Database number */
81297  int memCnt = -1;       /* Memory cell used for change counting */
81298  int rcauth;            /* Value returned by authorization callback */
81299
81300#ifndef SQLITE_OMIT_TRIGGER
81301  int isView;                  /* True if attempting to delete from a view */
81302  Trigger *pTrigger;           /* List of table triggers, if required */
81303#endif
81304
81305  memset(&sContext, 0, sizeof(sContext));
81306  db = pParse->db;
81307  if( pParse->nErr || db->mallocFailed ){
81308    goto delete_from_cleanup;
81309  }
81310  assert( pTabList->nSrc==1 );
81311
81312  /* Locate the table which we want to delete.  This table has to be
81313  ** put in an SrcList structure because some of the subroutines we
81314  ** will be calling are designed to work with multiple tables and expect
81315  ** an SrcList* parameter instead of just a Table* parameter.
81316  */
81317  pTab = sqlite3SrcListLookup(pParse, pTabList);
81318  if( pTab==0 )  goto delete_from_cleanup;
81319
81320  /* Figure out if we have any triggers and if the table being
81321  ** deleted from is a view
81322  */
81323#ifndef SQLITE_OMIT_TRIGGER
81324  pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
81325  isView = pTab->pSelect!=0;
81326#else
81327# define pTrigger 0
81328# define isView 0
81329#endif
81330#ifdef SQLITE_OMIT_VIEW
81331# undef isView
81332# define isView 0
81333#endif
81334
81335  /* If pTab is really a view, make sure it has been initialized.
81336  */
81337  if( sqlite3ViewGetColumnNames(pParse, pTab) ){
81338    goto delete_from_cleanup;
81339  }
81340
81341  if( sqlite3IsReadOnly(pParse, pTab, (pTrigger?1:0)) ){
81342    goto delete_from_cleanup;
81343  }
81344  iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
81345  assert( iDb<db->nDb );
81346  zDb = db->aDb[iDb].zName;
81347  rcauth = sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb);
81348  assert( rcauth==SQLITE_OK || rcauth==SQLITE_DENY || rcauth==SQLITE_IGNORE );
81349  if( rcauth==SQLITE_DENY ){
81350    goto delete_from_cleanup;
81351  }
81352  assert(!isView || pTrigger);
81353
81354  /* Assign  cursor number to the table and all its indices.
81355  */
81356  assert( pTabList->nSrc==1 );
81357  iCur = pTabList->a[0].iCursor = pParse->nTab++;
81358  for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
81359    pParse->nTab++;
81360  }
81361
81362  /* Start the view context
81363  */
81364  if( isView ){
81365    sqlite3AuthContextPush(pParse, &sContext, pTab->zName);
81366  }
81367
81368  /* Begin generating code.
81369  */
81370  v = sqlite3GetVdbe(pParse);
81371  if( v==0 ){
81372    goto delete_from_cleanup;
81373  }
81374  if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
81375  sqlite3BeginWriteOperation(pParse, 1, iDb);
81376
81377  /* If we are trying to delete from a view, realize that view into
81378  ** a ephemeral table.
81379  */
81380#if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
81381  if( isView ){
81382    sqlite3MaterializeView(pParse, pTab, pWhere, iCur);
81383  }
81384#endif
81385
81386  /* Resolve the column names in the WHERE clause.
81387  */
81388  memset(&sNC, 0, sizeof(sNC));
81389  sNC.pParse = pParse;
81390  sNC.pSrcList = pTabList;
81391  if( sqlite3ResolveExprNames(&sNC, pWhere) ){
81392    goto delete_from_cleanup;
81393  }
81394
81395  /* Initialize the counter of the number of rows deleted, if
81396  ** we are counting rows.
81397  */
81398  if( db->flags & SQLITE_CountRows ){
81399    memCnt = ++pParse->nMem;
81400    sqlite3VdbeAddOp2(v, OP_Integer, 0, memCnt);
81401  }
81402
81403#ifndef SQLITE_OMIT_TRUNCATE_OPTIMIZATION
81404  /* Special case: A DELETE without a WHERE clause deletes everything.
81405  ** It is easier just to erase the whole table. Prior to version 3.6.5,
81406  ** this optimization caused the row change count (the value returned by
81407  ** API function sqlite3_count_changes) to be set incorrectly.  */
81408  if( rcauth==SQLITE_OK && pWhere==0 && !pTrigger && !IsVirtual(pTab)
81409   && 0==sqlite3FkRequired(pParse, pTab, 0, 0)
81410  ){
81411    assert( !isView );
81412    sqlite3VdbeAddOp4(v, OP_Clear, pTab->tnum, iDb, memCnt,
81413                      pTab->zName, P4_STATIC);
81414    for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
81415      assert( pIdx->pSchema==pTab->pSchema );
81416      sqlite3VdbeAddOp2(v, OP_Clear, pIdx->tnum, iDb);
81417    }
81418  }else
81419#endif /* SQLITE_OMIT_TRUNCATE_OPTIMIZATION */
81420  /* The usual case: There is a WHERE clause so we have to scan through
81421  ** the table and pick which records to delete.
81422  */
81423  {
81424    int iRowSet = ++pParse->nMem;   /* Register for rowset of rows to delete */
81425    int iRowid = ++pParse->nMem;    /* Used for storing rowid values. */
81426    int regRowid;                   /* Actual register containing rowids */
81427
81428    /* Collect rowids of every row to be deleted.
81429    */
81430    sqlite3VdbeAddOp2(v, OP_Null, 0, iRowSet);
81431    pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere,0,WHERE_DUPLICATES_OK);
81432    if( pWInfo==0 ) goto delete_from_cleanup;
81433    regRowid = sqlite3ExprCodeGetColumn(pParse, pTab, -1, iCur, iRowid);
81434    sqlite3VdbeAddOp2(v, OP_RowSetAdd, iRowSet, regRowid);
81435    if( db->flags & SQLITE_CountRows ){
81436      sqlite3VdbeAddOp2(v, OP_AddImm, memCnt, 1);
81437    }
81438    sqlite3WhereEnd(pWInfo);
81439
81440    /* Delete every item whose key was written to the list during the
81441    ** database scan.  We have to delete items after the scan is complete
81442    ** because deleting an item can change the scan order.  */
81443    end = sqlite3VdbeMakeLabel(v);
81444
81445    /* Unless this is a view, open cursors for the table we are
81446    ** deleting from and all its indices. If this is a view, then the
81447    ** only effect this statement has is to fire the INSTEAD OF
81448    ** triggers.  */
81449    if( !isView ){
81450      sqlite3OpenTableAndIndices(pParse, pTab, iCur, OP_OpenWrite);
81451    }
81452
81453    addr = sqlite3VdbeAddOp3(v, OP_RowSetRead, iRowSet, end, iRowid);
81454
81455    /* Delete the row */
81456#ifndef SQLITE_OMIT_VIRTUALTABLE
81457    if( IsVirtual(pTab) ){
81458      const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
81459      sqlite3VtabMakeWritable(pParse, pTab);
81460      sqlite3VdbeAddOp4(v, OP_VUpdate, 0, 1, iRowid, pVTab, P4_VTAB);
81461      sqlite3MayAbort(pParse);
81462    }else
81463#endif
81464    {
81465      int count = (pParse->nested==0);    /* True to count changes */
81466      sqlite3GenerateRowDelete(pParse, pTab, iCur, iRowid, count, pTrigger, OE_Default);
81467    }
81468
81469    /* End of the delete loop */
81470    sqlite3VdbeAddOp2(v, OP_Goto, 0, addr);
81471    sqlite3VdbeResolveLabel(v, end);
81472
81473    /* Close the cursors open on the table and its indexes. */
81474    if( !isView && !IsVirtual(pTab) ){
81475      for(i=1, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
81476        sqlite3VdbeAddOp2(v, OP_Close, iCur + i, pIdx->tnum);
81477      }
81478      sqlite3VdbeAddOp1(v, OP_Close, iCur);
81479    }
81480  }
81481
81482  /* Update the sqlite_sequence table by storing the content of the
81483  ** maximum rowid counter values recorded while inserting into
81484  ** autoincrement tables.
81485  */
81486  if( pParse->nested==0 && pParse->pTriggerTab==0 ){
81487    sqlite3AutoincrementEnd(pParse);
81488  }
81489
81490  /* Return the number of rows that were deleted. If this routine is
81491  ** generating code because of a call to sqlite3NestedParse(), do not
81492  ** invoke the callback function.
81493  */
81494  if( (db->flags&SQLITE_CountRows) && !pParse->nested && !pParse->pTriggerTab ){
81495    sqlite3VdbeAddOp2(v, OP_ResultRow, memCnt, 1);
81496    sqlite3VdbeSetNumCols(v, 1);
81497    sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows deleted", SQLITE_STATIC);
81498  }
81499
81500delete_from_cleanup:
81501  sqlite3AuthContextPop(&sContext);
81502  sqlite3SrcListDelete(db, pTabList);
81503  sqlite3ExprDelete(db, pWhere);
81504  return;
81505}
81506/* Make sure "isView" and other macros defined above are undefined. Otherwise
81507** thely may interfere with compilation of other functions in this file
81508** (or in another file, if this file becomes part of the amalgamation).  */
81509#ifdef isView
81510 #undef isView
81511#endif
81512#ifdef pTrigger
81513 #undef pTrigger
81514#endif
81515
81516/*
81517** This routine generates VDBE code that causes a single row of a
81518** single table to be deleted.
81519**
81520** The VDBE must be in a particular state when this routine is called.
81521** These are the requirements:
81522**
81523**   1.  A read/write cursor pointing to pTab, the table containing the row
81524**       to be deleted, must be opened as cursor number $iCur.
81525**
81526**   2.  Read/write cursors for all indices of pTab must be open as
81527**       cursor number base+i for the i-th index.
81528**
81529**   3.  The record number of the row to be deleted must be stored in
81530**       memory cell iRowid.
81531**
81532** This routine generates code to remove both the table record and all
81533** index entries that point to that record.
81534*/
81535SQLITE_PRIVATE void sqlite3GenerateRowDelete(
81536  Parse *pParse,     /* Parsing context */
81537  Table *pTab,       /* Table containing the row to be deleted */
81538  int iCur,          /* Cursor number for the table */
81539  int iRowid,        /* Memory cell that contains the rowid to delete */
81540  int count,         /* If non-zero, increment the row change counter */
81541  Trigger *pTrigger, /* List of triggers to (potentially) fire */
81542  int onconf         /* Default ON CONFLICT policy for triggers */
81543){
81544  Vdbe *v = pParse->pVdbe;        /* Vdbe */
81545  int iOld = 0;                   /* First register in OLD.* array */
81546  int iLabel;                     /* Label resolved to end of generated code */
81547
81548  /* Vdbe is guaranteed to have been allocated by this stage. */
81549  assert( v );
81550
81551  /* Seek cursor iCur to the row to delete. If this row no longer exists
81552  ** (this can happen if a trigger program has already deleted it), do
81553  ** not attempt to delete it or fire any DELETE triggers.  */
81554  iLabel = sqlite3VdbeMakeLabel(v);
81555  sqlite3VdbeAddOp3(v, OP_NotExists, iCur, iLabel, iRowid);
81556
81557  /* If there are any triggers to fire, allocate a range of registers to
81558  ** use for the old.* references in the triggers.  */
81559  if( sqlite3FkRequired(pParse, pTab, 0, 0) || pTrigger ){
81560    u32 mask;                     /* Mask of OLD.* columns in use */
81561    int iCol;                     /* Iterator used while populating OLD.* */
81562
81563    /* TODO: Could use temporary registers here. Also could attempt to
81564    ** avoid copying the contents of the rowid register.  */
81565    mask = sqlite3TriggerColmask(
81566        pParse, pTrigger, 0, 0, TRIGGER_BEFORE|TRIGGER_AFTER, pTab, onconf
81567    );
81568    mask |= sqlite3FkOldmask(pParse, pTab);
81569    iOld = pParse->nMem+1;
81570    pParse->nMem += (1 + pTab->nCol);
81571
81572    /* Populate the OLD.* pseudo-table register array. These values will be
81573    ** used by any BEFORE and AFTER triggers that exist.  */
81574    sqlite3VdbeAddOp2(v, OP_Copy, iRowid, iOld);
81575    for(iCol=0; iCol<pTab->nCol; iCol++){
81576      if( mask==0xffffffff || mask&(1<<iCol) ){
81577        sqlite3ExprCodeGetColumnOfTable(v, pTab, iCur, iCol, iOld+iCol+1);
81578      }
81579    }
81580
81581    /* Invoke BEFORE DELETE trigger programs. */
81582    sqlite3CodeRowTrigger(pParse, pTrigger,
81583        TK_DELETE, 0, TRIGGER_BEFORE, pTab, iOld, onconf, iLabel
81584    );
81585
81586    /* Seek the cursor to the row to be deleted again. It may be that
81587    ** the BEFORE triggers coded above have already removed the row
81588    ** being deleted. Do not attempt to delete the row a second time, and
81589    ** do not fire AFTER triggers.  */
81590    sqlite3VdbeAddOp3(v, OP_NotExists, iCur, iLabel, iRowid);
81591
81592    /* Do FK processing. This call checks that any FK constraints that
81593    ** refer to this table (i.e. constraints attached to other tables)
81594    ** are not violated by deleting this row.  */
81595    sqlite3FkCheck(pParse, pTab, iOld, 0);
81596  }
81597
81598  /* Delete the index and table entries. Skip this step if pTab is really
81599  ** a view (in which case the only effect of the DELETE statement is to
81600  ** fire the INSTEAD OF triggers).  */
81601  if( pTab->pSelect==0 ){
81602    sqlite3GenerateRowIndexDelete(pParse, pTab, iCur, 0);
81603    sqlite3VdbeAddOp2(v, OP_Delete, iCur, (count?OPFLAG_NCHANGE:0));
81604    if( count ){
81605      sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_TRANSIENT);
81606    }
81607  }
81608
81609  /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to
81610  ** handle rows (possibly in other tables) that refer via a foreign key
81611  ** to the row just deleted. */
81612  sqlite3FkActions(pParse, pTab, 0, iOld);
81613
81614  /* Invoke AFTER DELETE trigger programs. */
81615  sqlite3CodeRowTrigger(pParse, pTrigger,
81616      TK_DELETE, 0, TRIGGER_AFTER, pTab, iOld, onconf, iLabel
81617  );
81618
81619  /* Jump here if the row had already been deleted before any BEFORE
81620  ** trigger programs were invoked. Or if a trigger program throws a
81621  ** RAISE(IGNORE) exception.  */
81622  sqlite3VdbeResolveLabel(v, iLabel);
81623}
81624
81625/*
81626** This routine generates VDBE code that causes the deletion of all
81627** index entries associated with a single row of a single table.
81628**
81629** The VDBE must be in a particular state when this routine is called.
81630** These are the requirements:
81631**
81632**   1.  A read/write cursor pointing to pTab, the table containing the row
81633**       to be deleted, must be opened as cursor number "iCur".
81634**
81635**   2.  Read/write cursors for all indices of pTab must be open as
81636**       cursor number iCur+i for the i-th index.
81637**
81638**   3.  The "iCur" cursor must be pointing to the row that is to be
81639**       deleted.
81640*/
81641SQLITE_PRIVATE void sqlite3GenerateRowIndexDelete(
81642  Parse *pParse,     /* Parsing and code generating context */
81643  Table *pTab,       /* Table containing the row to be deleted */
81644  int iCur,          /* Cursor number for the table */
81645  int *aRegIdx       /* Only delete if aRegIdx!=0 && aRegIdx[i]>0 */
81646){
81647  int i;
81648  Index *pIdx;
81649  int r1;
81650
81651  for(i=1, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
81652    if( aRegIdx!=0 && aRegIdx[i-1]==0 ) continue;
81653    r1 = sqlite3GenerateIndexKey(pParse, pIdx, iCur, 0, 0);
81654    sqlite3VdbeAddOp3(pParse->pVdbe, OP_IdxDelete, iCur+i, r1,pIdx->nColumn+1);
81655  }
81656}
81657
81658/*
81659** Generate code that will assemble an index key and put it in register
81660** regOut.  The key with be for index pIdx which is an index on pTab.
81661** iCur is the index of a cursor open on the pTab table and pointing to
81662** the entry that needs indexing.
81663**
81664** Return a register number which is the first in a block of
81665** registers that holds the elements of the index key.  The
81666** block of registers has already been deallocated by the time
81667** this routine returns.
81668*/
81669SQLITE_PRIVATE int sqlite3GenerateIndexKey(
81670  Parse *pParse,     /* Parsing context */
81671  Index *pIdx,       /* The index for which to generate a key */
81672  int iCur,          /* Cursor number for the pIdx->pTable table */
81673  int regOut,        /* Write the new index key to this register */
81674  int doMakeRec      /* Run the OP_MakeRecord instruction if true */
81675){
81676  Vdbe *v = pParse->pVdbe;
81677  int j;
81678  Table *pTab = pIdx->pTable;
81679  int regBase;
81680  int nCol;
81681
81682  nCol = pIdx->nColumn;
81683  regBase = sqlite3GetTempRange(pParse, nCol+1);
81684  sqlite3VdbeAddOp2(v, OP_Rowid, iCur, regBase+nCol);
81685  for(j=0; j<nCol; j++){
81686    int idx = pIdx->aiColumn[j];
81687    if( idx==pTab->iPKey ){
81688      sqlite3VdbeAddOp2(v, OP_SCopy, regBase+nCol, regBase+j);
81689    }else{
81690      sqlite3VdbeAddOp3(v, OP_Column, iCur, idx, regBase+j);
81691      sqlite3ColumnDefault(v, pTab, idx, -1);
81692    }
81693  }
81694  if( doMakeRec ){
81695    sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol+1, regOut);
81696    sqlite3VdbeChangeP4(v, -1, sqlite3IndexAffinityStr(v, pIdx), P4_TRANSIENT);
81697  }
81698  sqlite3ReleaseTempRange(pParse, regBase, nCol+1);
81699  return regBase;
81700}
81701
81702/************** End of delete.c **********************************************/
81703/************** Begin file func.c ********************************************/
81704/*
81705** 2002 February 23
81706**
81707** The author disclaims copyright to this source code.  In place of
81708** a legal notice, here is a blessing:
81709**
81710**    May you do good and not evil.
81711**    May you find forgiveness for yourself and forgive others.
81712**    May you share freely, never taking more than you give.
81713**
81714*************************************************************************
81715** This file contains the C functions that implement various SQL
81716** functions of SQLite.
81717**
81718** There is only one exported symbol in this file - the function
81719** sqliteRegisterBuildinFunctions() found at the bottom of the file.
81720** All other code has file scope.
81721*/
81722
81723/*
81724** Return the collating function associated with a function.
81725*/
81726static CollSeq *sqlite3GetFuncCollSeq(sqlite3_context *context){
81727  return context->pColl;
81728}
81729
81730/*
81731** Implementation of the non-aggregate min() and max() functions
81732*/
81733static void minmaxFunc(
81734  sqlite3_context *context,
81735  int argc,
81736  sqlite3_value **argv
81737){
81738  int i;
81739  int mask;    /* 0 for min() or 0xffffffff for max() */
81740  int iBest;
81741  CollSeq *pColl;
81742
81743  assert( argc>1 );
81744  mask = sqlite3_user_data(context)==0 ? 0 : -1;
81745  pColl = sqlite3GetFuncCollSeq(context);
81746  assert( pColl );
81747  assert( mask==-1 || mask==0 );
81748  iBest = 0;
81749  if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
81750  for(i=1; i<argc; i++){
81751    if( sqlite3_value_type(argv[i])==SQLITE_NULL ) return;
81752    if( (sqlite3MemCompare(argv[iBest], argv[i], pColl)^mask)>=0 ){
81753      testcase( mask==0 );
81754      iBest = i;
81755    }
81756  }
81757  sqlite3_result_value(context, argv[iBest]);
81758}
81759
81760/*
81761** Return the type of the argument.
81762*/
81763static void typeofFunc(
81764  sqlite3_context *context,
81765  int NotUsed,
81766  sqlite3_value **argv
81767){
81768  const char *z = 0;
81769  UNUSED_PARAMETER(NotUsed);
81770  switch( sqlite3_value_type(argv[0]) ){
81771    case SQLITE_INTEGER: z = "integer"; break;
81772    case SQLITE_TEXT:    z = "text";    break;
81773    case SQLITE_FLOAT:   z = "real";    break;
81774    case SQLITE_BLOB:    z = "blob";    break;
81775    default:             z = "null";    break;
81776  }
81777  sqlite3_result_text(context, z, -1, SQLITE_STATIC);
81778}
81779
81780
81781/*
81782** Implementation of the length() function
81783*/
81784static void lengthFunc(
81785  sqlite3_context *context,
81786  int argc,
81787  sqlite3_value **argv
81788){
81789  int len;
81790
81791  assert( argc==1 );
81792  UNUSED_PARAMETER(argc);
81793  switch( sqlite3_value_type(argv[0]) ){
81794    case SQLITE_BLOB:
81795    case SQLITE_INTEGER:
81796    case SQLITE_FLOAT: {
81797      sqlite3_result_int(context, sqlite3_value_bytes(argv[0]));
81798      break;
81799    }
81800    case SQLITE_TEXT: {
81801      const unsigned char *z = sqlite3_value_text(argv[0]);
81802      if( z==0 ) return;
81803      len = 0;
81804      while( *z ){
81805        len++;
81806        SQLITE_SKIP_UTF8(z);
81807      }
81808      sqlite3_result_int(context, len);
81809      break;
81810    }
81811    default: {
81812      sqlite3_result_null(context);
81813      break;
81814    }
81815  }
81816}
81817
81818/*
81819** Implementation of the abs() function.
81820**
81821** IMP: R-23979-26855 The abs(X) function returns the absolute value of
81822** the numeric argument X.
81823*/
81824static void absFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
81825  assert( argc==1 );
81826  UNUSED_PARAMETER(argc);
81827  switch( sqlite3_value_type(argv[0]) ){
81828    case SQLITE_INTEGER: {
81829      i64 iVal = sqlite3_value_int64(argv[0]);
81830      if( iVal<0 ){
81831        if( (iVal<<1)==0 ){
81832          /* IMP: R-35460-15084 If X is the integer -9223372036854775807 then
81833          ** abs(X) throws an integer overflow error since there is no
81834          ** equivalent positive 64-bit two complement value. */
81835          sqlite3_result_error(context, "integer overflow", -1);
81836          return;
81837        }
81838        iVal = -iVal;
81839      }
81840      sqlite3_result_int64(context, iVal);
81841      break;
81842    }
81843    case SQLITE_NULL: {
81844      /* IMP: R-37434-19929 Abs(X) returns NULL if X is NULL. */
81845      sqlite3_result_null(context);
81846      break;
81847    }
81848    default: {
81849      /* Because sqlite3_value_double() returns 0.0 if the argument is not
81850      ** something that can be converted into a number, we have:
81851      ** IMP: R-57326-31541 Abs(X) return 0.0 if X is a string or blob that
81852      ** cannot be converted to a numeric value.
81853      */
81854      double rVal = sqlite3_value_double(argv[0]);
81855      if( rVal<0 ) rVal = -rVal;
81856      sqlite3_result_double(context, rVal);
81857      break;
81858    }
81859  }
81860}
81861
81862/*
81863** Implementation of the substr() function.
81864**
81865** substr(x,p1,p2)  returns p2 characters of x[] beginning with p1.
81866** p1 is 1-indexed.  So substr(x,1,1) returns the first character
81867** of x.  If x is text, then we actually count UTF-8 characters.
81868** If x is a blob, then we count bytes.
81869**
81870** If p1 is negative, then we begin abs(p1) from the end of x[].
81871**
81872** If p2 is negative, return the p2 characters preceeding p1.
81873*/
81874static void substrFunc(
81875  sqlite3_context *context,
81876  int argc,
81877  sqlite3_value **argv
81878){
81879  const unsigned char *z;
81880  const unsigned char *z2;
81881  int len;
81882  int p0type;
81883  i64 p1, p2;
81884  int negP2 = 0;
81885
81886  assert( argc==3 || argc==2 );
81887  if( sqlite3_value_type(argv[1])==SQLITE_NULL
81888   || (argc==3 && sqlite3_value_type(argv[2])==SQLITE_NULL)
81889  ){
81890    return;
81891  }
81892  p0type = sqlite3_value_type(argv[0]);
81893  p1 = sqlite3_value_int(argv[1]);
81894  if( p0type==SQLITE_BLOB ){
81895    len = sqlite3_value_bytes(argv[0]);
81896    z = sqlite3_value_blob(argv[0]);
81897    if( z==0 ) return;
81898    assert( len==sqlite3_value_bytes(argv[0]) );
81899  }else{
81900    z = sqlite3_value_text(argv[0]);
81901    if( z==0 ) return;
81902    len = 0;
81903    if( p1<0 ){
81904      for(z2=z; *z2; len++){
81905        SQLITE_SKIP_UTF8(z2);
81906      }
81907    }
81908  }
81909  if( argc==3 ){
81910    p2 = sqlite3_value_int(argv[2]);
81911    if( p2<0 ){
81912      p2 = -p2;
81913      negP2 = 1;
81914    }
81915  }else{
81916    p2 = sqlite3_context_db_handle(context)->aLimit[SQLITE_LIMIT_LENGTH];
81917  }
81918  if( p1<0 ){
81919    p1 += len;
81920    if( p1<0 ){
81921      p2 += p1;
81922      if( p2<0 ) p2 = 0;
81923      p1 = 0;
81924    }
81925  }else if( p1>0 ){
81926    p1--;
81927  }else if( p2>0 ){
81928    p2--;
81929  }
81930  if( negP2 ){
81931    p1 -= p2;
81932    if( p1<0 ){
81933      p2 += p1;
81934      p1 = 0;
81935    }
81936  }
81937  assert( p1>=0 && p2>=0 );
81938  if( p0type!=SQLITE_BLOB ){
81939    while( *z && p1 ){
81940      SQLITE_SKIP_UTF8(z);
81941      p1--;
81942    }
81943    for(z2=z; *z2 && p2; p2--){
81944      SQLITE_SKIP_UTF8(z2);
81945    }
81946    sqlite3_result_text(context, (char*)z, (int)(z2-z), SQLITE_TRANSIENT);
81947  }else{
81948    if( p1+p2>len ){
81949      p2 = len-p1;
81950      if( p2<0 ) p2 = 0;
81951    }
81952    sqlite3_result_blob(context, (char*)&z[p1], (int)p2, SQLITE_TRANSIENT);
81953  }
81954}
81955
81956/*
81957** Implementation of the round() function
81958*/
81959#ifndef SQLITE_OMIT_FLOATING_POINT
81960static void roundFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
81961  int n = 0;
81962  double r;
81963  char *zBuf;
81964  assert( argc==1 || argc==2 );
81965  if( argc==2 ){
81966    if( SQLITE_NULL==sqlite3_value_type(argv[1]) ) return;
81967    n = sqlite3_value_int(argv[1]);
81968    if( n>30 ) n = 30;
81969    if( n<0 ) n = 0;
81970  }
81971  if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
81972  r = sqlite3_value_double(argv[0]);
81973  /* If Y==0 and X will fit in a 64-bit int,
81974  ** handle the rounding directly,
81975  ** otherwise use printf.
81976  */
81977  if( n==0 && r>=0 && r<LARGEST_INT64-1 ){
81978    r = (double)((sqlite_int64)(r+0.5));
81979  }else if( n==0 && r<0 && (-r)<LARGEST_INT64-1 ){
81980    r = -(double)((sqlite_int64)((-r)+0.5));
81981  }else{
81982    zBuf = sqlite3_mprintf("%.*f",n,r);
81983    if( zBuf==0 ){
81984      sqlite3_result_error_nomem(context);
81985      return;
81986    }
81987    sqlite3AtoF(zBuf, &r, sqlite3Strlen30(zBuf), SQLITE_UTF8);
81988    sqlite3_free(zBuf);
81989  }
81990  sqlite3_result_double(context, r);
81991}
81992#endif
81993
81994/*
81995** Allocate nByte bytes of space using sqlite3_malloc(). If the
81996** allocation fails, call sqlite3_result_error_nomem() to notify
81997** the database handle that malloc() has failed and return NULL.
81998** If nByte is larger than the maximum string or blob length, then
81999** raise an SQLITE_TOOBIG exception and return NULL.
82000*/
82001static void *contextMalloc(sqlite3_context *context, i64 nByte){
82002  char *z;
82003  sqlite3 *db = sqlite3_context_db_handle(context);
82004  assert( nByte>0 );
82005  testcase( nByte==db->aLimit[SQLITE_LIMIT_LENGTH] );
82006  testcase( nByte==db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
82007  if( nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
82008    sqlite3_result_error_toobig(context);
82009    z = 0;
82010  }else{
82011    z = sqlite3Malloc((int)nByte);
82012    if( !z ){
82013      sqlite3_result_error_nomem(context);
82014    }
82015  }
82016  return z;
82017}
82018
82019/*
82020** Implementation of the upper() and lower() SQL functions.
82021*/
82022static void upperFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
82023  char *z1;
82024  const char *z2;
82025  int i, n;
82026  UNUSED_PARAMETER(argc);
82027  z2 = (char*)sqlite3_value_text(argv[0]);
82028  n = sqlite3_value_bytes(argv[0]);
82029  /* Verify that the call to _bytes() does not invalidate the _text() pointer */
82030  assert( z2==(char*)sqlite3_value_text(argv[0]) );
82031  if( z2 ){
82032    z1 = contextMalloc(context, ((i64)n)+1);
82033    if( z1 ){
82034      memcpy(z1, z2, n+1);
82035      for(i=0; z1[i]; i++){
82036        z1[i] = (char)sqlite3Toupper(z1[i]);
82037      }
82038      sqlite3_result_text(context, z1, -1, sqlite3_free);
82039    }
82040  }
82041}
82042static void lowerFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
82043  u8 *z1;
82044  const char *z2;
82045  int i, n;
82046  UNUSED_PARAMETER(argc);
82047  z2 = (char*)sqlite3_value_text(argv[0]);
82048  n = sqlite3_value_bytes(argv[0]);
82049  /* Verify that the call to _bytes() does not invalidate the _text() pointer */
82050  assert( z2==(char*)sqlite3_value_text(argv[0]) );
82051  if( z2 ){
82052    z1 = contextMalloc(context, ((i64)n)+1);
82053    if( z1 ){
82054      memcpy(z1, z2, n+1);
82055      for(i=0; z1[i]; i++){
82056        z1[i] = sqlite3Tolower(z1[i]);
82057      }
82058      sqlite3_result_text(context, (char *)z1, -1, sqlite3_free);
82059    }
82060  }
82061}
82062
82063
82064#if 0  /* This function is never used. */
82065/*
82066** The COALESCE() and IFNULL() functions used to be implemented as shown
82067** here.  But now they are implemented as VDBE code so that unused arguments
82068** do not have to be computed.  This legacy implementation is retained as
82069** comment.
82070*/
82071/*
82072** Implementation of the IFNULL(), NVL(), and COALESCE() functions.
82073** All three do the same thing.  They return the first non-NULL
82074** argument.
82075*/
82076static void ifnullFunc(
82077  sqlite3_context *context,
82078  int argc,
82079  sqlite3_value **argv
82080){
82081  int i;
82082  for(i=0; i<argc; i++){
82083    if( SQLITE_NULL!=sqlite3_value_type(argv[i]) ){
82084      sqlite3_result_value(context, argv[i]);
82085      break;
82086    }
82087  }
82088}
82089#endif /* NOT USED */
82090#define ifnullFunc versionFunc   /* Substitute function - never called */
82091
82092/*
82093** Implementation of random().  Return a random integer.
82094*/
82095static void randomFunc(
82096  sqlite3_context *context,
82097  int NotUsed,
82098  sqlite3_value **NotUsed2
82099){
82100  sqlite_int64 r;
82101  UNUSED_PARAMETER2(NotUsed, NotUsed2);
82102  sqlite3_randomness(sizeof(r), &r);
82103  if( r<0 ){
82104    /* We need to prevent a random number of 0x8000000000000000
82105    ** (or -9223372036854775808) since when you do abs() of that
82106    ** number of you get the same value back again.  To do this
82107    ** in a way that is testable, mask the sign bit off of negative
82108    ** values, resulting in a positive value.  Then take the
82109    ** 2s complement of that positive value.  The end result can
82110    ** therefore be no less than -9223372036854775807.
82111    */
82112    r = -(r ^ (((sqlite3_int64)1)<<63));
82113  }
82114  sqlite3_result_int64(context, r);
82115}
82116
82117/*
82118** Implementation of randomblob(N).  Return a random blob
82119** that is N bytes long.
82120*/
82121static void randomBlob(
82122  sqlite3_context *context,
82123  int argc,
82124  sqlite3_value **argv
82125){
82126  int n;
82127  unsigned char *p;
82128  assert( argc==1 );
82129  UNUSED_PARAMETER(argc);
82130  n = sqlite3_value_int(argv[0]);
82131  if( n<1 ){
82132    n = 1;
82133  }
82134  p = contextMalloc(context, n);
82135  if( p ){
82136    sqlite3_randomness(n, p);
82137    sqlite3_result_blob(context, (char*)p, n, sqlite3_free);
82138  }
82139}
82140
82141/*
82142** Implementation of the last_insert_rowid() SQL function.  The return
82143** value is the same as the sqlite3_last_insert_rowid() API function.
82144*/
82145static void last_insert_rowid(
82146  sqlite3_context *context,
82147  int NotUsed,
82148  sqlite3_value **NotUsed2
82149){
82150  sqlite3 *db = sqlite3_context_db_handle(context);
82151  UNUSED_PARAMETER2(NotUsed, NotUsed2);
82152  /* IMP: R-51513-12026 The last_insert_rowid() SQL function is a
82153  ** wrapper around the sqlite3_last_insert_rowid() C/C++ interface
82154  ** function. */
82155  sqlite3_result_int64(context, sqlite3_last_insert_rowid(db));
82156}
82157
82158/*
82159** Implementation of the changes() SQL function.
82160**
82161** IMP: R-62073-11209 The changes() SQL function is a wrapper
82162** around the sqlite3_changes() C/C++ function and hence follows the same
82163** rules for counting changes.
82164*/
82165static void changes(
82166  sqlite3_context *context,
82167  int NotUsed,
82168  sqlite3_value **NotUsed2
82169){
82170  sqlite3 *db = sqlite3_context_db_handle(context);
82171  UNUSED_PARAMETER2(NotUsed, NotUsed2);
82172  sqlite3_result_int(context, sqlite3_changes(db));
82173}
82174
82175/*
82176** Implementation of the total_changes() SQL function.  The return value is
82177** the same as the sqlite3_total_changes() API function.
82178*/
82179static void total_changes(
82180  sqlite3_context *context,
82181  int NotUsed,
82182  sqlite3_value **NotUsed2
82183){
82184  sqlite3 *db = sqlite3_context_db_handle(context);
82185  UNUSED_PARAMETER2(NotUsed, NotUsed2);
82186  /* IMP: R-52756-41993 This function is a wrapper around the
82187  ** sqlite3_total_changes() C/C++ interface. */
82188  sqlite3_result_int(context, sqlite3_total_changes(db));
82189}
82190
82191/*
82192** A structure defining how to do GLOB-style comparisons.
82193*/
82194struct compareInfo {
82195  u8 matchAll;
82196  u8 matchOne;
82197  u8 matchSet;
82198  u8 noCase;
82199};
82200
82201/*
82202** For LIKE and GLOB matching on EBCDIC machines, assume that every
82203** character is exactly one byte in size.  Also, all characters are
82204** able to participate in upper-case-to-lower-case mappings in EBCDIC
82205** whereas only characters less than 0x80 do in ASCII.
82206*/
82207#if defined(SQLITE_EBCDIC)
82208# define sqlite3Utf8Read(A,C)    (*(A++))
82209# define GlogUpperToLower(A)     A = sqlite3UpperToLower[A]
82210#else
82211# define GlogUpperToLower(A)     if( A<0x80 ){ A = sqlite3UpperToLower[A]; }
82212#endif
82213
82214static const struct compareInfo globInfo = { '*', '?', '[', 0 };
82215/* The correct SQL-92 behavior is for the LIKE operator to ignore
82216** case.  Thus  'a' LIKE 'A' would be true. */
82217static const struct compareInfo likeInfoNorm = { '%', '_',   0, 1 };
82218/* If SQLITE_CASE_SENSITIVE_LIKE is defined, then the LIKE operator
82219** is case sensitive causing 'a' LIKE 'A' to be false */
82220static const struct compareInfo likeInfoAlt = { '%', '_',   0, 0 };
82221
82222/*
82223** Compare two UTF-8 strings for equality where the first string can
82224** potentially be a "glob" expression.  Return true (1) if they
82225** are the same and false (0) if they are different.
82226**
82227** Globbing rules:
82228**
82229**      '*'       Matches any sequence of zero or more characters.
82230**
82231**      '?'       Matches exactly one character.
82232**
82233**     [...]      Matches one character from the enclosed list of
82234**                characters.
82235**
82236**     [^...]     Matches one character not in the enclosed list.
82237**
82238** With the [...] and [^...] matching, a ']' character can be included
82239** in the list by making it the first character after '[' or '^'.  A
82240** range of characters can be specified using '-'.  Example:
82241** "[a-z]" matches any single lower-case letter.  To match a '-', make
82242** it the last character in the list.
82243**
82244** This routine is usually quick, but can be N**2 in the worst case.
82245**
82246** Hints: to match '*' or '?', put them in "[]".  Like this:
82247**
82248**         abc[*]xyz        Matches "abc*xyz" only
82249*/
82250static int patternCompare(
82251  const u8 *zPattern,              /* The glob pattern */
82252  const u8 *zString,               /* The string to compare against the glob */
82253  const struct compareInfo *pInfo, /* Information about how to do the compare */
82254  const int esc                    /* The escape character */
82255){
82256  int c, c2;
82257  int invert;
82258  int seen;
82259  u8 matchOne = pInfo->matchOne;
82260  u8 matchAll = pInfo->matchAll;
82261  u8 matchSet = pInfo->matchSet;
82262  u8 noCase = pInfo->noCase;
82263  int prevEscape = 0;     /* True if the previous character was 'escape' */
82264
82265  while( (c = sqlite3Utf8Read(zPattern,&zPattern))!=0 ){
82266    if( !prevEscape && c==matchAll ){
82267      while( (c=sqlite3Utf8Read(zPattern,&zPattern)) == matchAll
82268               || c == matchOne ){
82269        if( c==matchOne && sqlite3Utf8Read(zString, &zString)==0 ){
82270          return 0;
82271        }
82272      }
82273      if( c==0 ){
82274        return 1;
82275      }else if( c==esc ){
82276        c = sqlite3Utf8Read(zPattern, &zPattern);
82277        if( c==0 ){
82278          return 0;
82279        }
82280      }else if( c==matchSet ){
82281        assert( esc==0 );         /* This is GLOB, not LIKE */
82282        assert( matchSet<0x80 );  /* '[' is a single-byte character */
82283        while( *zString && patternCompare(&zPattern[-1],zString,pInfo,esc)==0 ){
82284          SQLITE_SKIP_UTF8(zString);
82285        }
82286        return *zString!=0;
82287      }
82288      while( (c2 = sqlite3Utf8Read(zString,&zString))!=0 ){
82289        if( noCase ){
82290          GlogUpperToLower(c2);
82291          GlogUpperToLower(c);
82292          while( c2 != 0 && c2 != c ){
82293            c2 = sqlite3Utf8Read(zString, &zString);
82294            GlogUpperToLower(c2);
82295          }
82296        }else{
82297          while( c2 != 0 && c2 != c ){
82298            c2 = sqlite3Utf8Read(zString, &zString);
82299          }
82300        }
82301        if( c2==0 ) return 0;
82302        if( patternCompare(zPattern,zString,pInfo,esc) ) return 1;
82303      }
82304      return 0;
82305    }else if( !prevEscape && c==matchOne ){
82306      if( sqlite3Utf8Read(zString, &zString)==0 ){
82307        return 0;
82308      }
82309    }else if( c==matchSet ){
82310      int prior_c = 0;
82311      assert( esc==0 );    /* This only occurs for GLOB, not LIKE */
82312      seen = 0;
82313      invert = 0;
82314      c = sqlite3Utf8Read(zString, &zString);
82315      if( c==0 ) return 0;
82316      c2 = sqlite3Utf8Read(zPattern, &zPattern);
82317      if( c2=='^' ){
82318        invert = 1;
82319        c2 = sqlite3Utf8Read(zPattern, &zPattern);
82320      }
82321      if( c2==']' ){
82322        if( c==']' ) seen = 1;
82323        c2 = sqlite3Utf8Read(zPattern, &zPattern);
82324      }
82325      while( c2 && c2!=']' ){
82326        if( c2=='-' && zPattern[0]!=']' && zPattern[0]!=0 && prior_c>0 ){
82327          c2 = sqlite3Utf8Read(zPattern, &zPattern);
82328          if( c>=prior_c && c<=c2 ) seen = 1;
82329          prior_c = 0;
82330        }else{
82331          if( c==c2 ){
82332            seen = 1;
82333          }
82334          prior_c = c2;
82335        }
82336        c2 = sqlite3Utf8Read(zPattern, &zPattern);
82337      }
82338      if( c2==0 || (seen ^ invert)==0 ){
82339        return 0;
82340      }
82341    }else if( esc==c && !prevEscape ){
82342      prevEscape = 1;
82343    }else{
82344      c2 = sqlite3Utf8Read(zString, &zString);
82345      if( noCase ){
82346        GlogUpperToLower(c);
82347        GlogUpperToLower(c2);
82348      }
82349      if( c!=c2 ){
82350        return 0;
82351      }
82352      prevEscape = 0;
82353    }
82354  }
82355  return *zString==0;
82356}
82357
82358/*
82359** Count the number of times that the LIKE operator (or GLOB which is
82360** just a variation of LIKE) gets called.  This is used for testing
82361** only.
82362*/
82363#ifdef SQLITE_TEST
82364SQLITE_API int sqlite3_like_count = 0;
82365#endif
82366
82367
82368/*
82369** Implementation of the like() SQL function.  This function implements
82370** the build-in LIKE operator.  The first argument to the function is the
82371** pattern and the second argument is the string.  So, the SQL statements:
82372**
82373**       A LIKE B
82374**
82375** is implemented as like(B,A).
82376**
82377** This same function (with a different compareInfo structure) computes
82378** the GLOB operator.
82379*/
82380static void likeFunc(
82381  sqlite3_context *context,
82382  int argc,
82383  sqlite3_value **argv
82384){
82385  const unsigned char *zA, *zB;
82386  int escape = 0;
82387  int nPat;
82388  sqlite3 *db = sqlite3_context_db_handle(context);
82389
82390  zB = sqlite3_value_text(argv[0]);
82391  zA = sqlite3_value_text(argv[1]);
82392
82393  /* Limit the length of the LIKE or GLOB pattern to avoid problems
82394  ** of deep recursion and N*N behavior in patternCompare().
82395  */
82396  nPat = sqlite3_value_bytes(argv[0]);
82397  testcase( nPat==db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] );
82398  testcase( nPat==db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]+1 );
82399  if( nPat > db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] ){
82400    sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1);
82401    return;
82402  }
82403  assert( zB==sqlite3_value_text(argv[0]) );  /* Encoding did not change */
82404
82405  if( argc==3 ){
82406    /* The escape character string must consist of a single UTF-8 character.
82407    ** Otherwise, return an error.
82408    */
82409    const unsigned char *zEsc = sqlite3_value_text(argv[2]);
82410    if( zEsc==0 ) return;
82411    if( sqlite3Utf8CharLen((char*)zEsc, -1)!=1 ){
82412      sqlite3_result_error(context,
82413          "ESCAPE expression must be a single character", -1);
82414      return;
82415    }
82416    escape = sqlite3Utf8Read(zEsc, &zEsc);
82417  }
82418  if( zA && zB ){
82419    struct compareInfo *pInfo = sqlite3_user_data(context);
82420#ifdef SQLITE_TEST
82421    sqlite3_like_count++;
82422#endif
82423
82424    sqlite3_result_int(context, patternCompare(zB, zA, pInfo, escape));
82425  }
82426}
82427
82428/*
82429** Implementation of the NULLIF(x,y) function.  The result is the first
82430** argument if the arguments are different.  The result is NULL if the
82431** arguments are equal to each other.
82432*/
82433static void nullifFunc(
82434  sqlite3_context *context,
82435  int NotUsed,
82436  sqlite3_value **argv
82437){
82438  CollSeq *pColl = sqlite3GetFuncCollSeq(context);
82439  UNUSED_PARAMETER(NotUsed);
82440  if( sqlite3MemCompare(argv[0], argv[1], pColl)!=0 ){
82441    sqlite3_result_value(context, argv[0]);
82442  }
82443}
82444
82445/*
82446** Implementation of the sqlite_version() function.  The result is the version
82447** of the SQLite library that is running.
82448*/
82449static void versionFunc(
82450  sqlite3_context *context,
82451  int NotUsed,
82452  sqlite3_value **NotUsed2
82453){
82454  UNUSED_PARAMETER2(NotUsed, NotUsed2);
82455  /* IMP: R-48699-48617 This function is an SQL wrapper around the
82456  ** sqlite3_libversion() C-interface. */
82457  sqlite3_result_text(context, sqlite3_libversion(), -1, SQLITE_STATIC);
82458}
82459
82460/*
82461** Implementation of the sqlite_source_id() function. The result is a string
82462** that identifies the particular version of the source code used to build
82463** SQLite.
82464*/
82465static void sourceidFunc(
82466  sqlite3_context *context,
82467  int NotUsed,
82468  sqlite3_value **NotUsed2
82469){
82470  UNUSED_PARAMETER2(NotUsed, NotUsed2);
82471  /* IMP: R-24470-31136 This function is an SQL wrapper around the
82472  ** sqlite3_sourceid() C interface. */
82473  sqlite3_result_text(context, sqlite3_sourceid(), -1, SQLITE_STATIC);
82474}
82475
82476/*
82477** Implementation of the sqlite_compileoption_used() function.
82478** The result is an integer that identifies if the compiler option
82479** was used to build SQLite.
82480*/
82481#ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
82482static void compileoptionusedFunc(
82483  sqlite3_context *context,
82484  int argc,
82485  sqlite3_value **argv
82486){
82487  const char *zOptName;
82488  assert( argc==1 );
82489  UNUSED_PARAMETER(argc);
82490  /* IMP: R-39564-36305 The sqlite_compileoption_used() SQL
82491  ** function is a wrapper around the sqlite3_compileoption_used() C/C++
82492  ** function.
82493  */
82494  if( (zOptName = (const char*)sqlite3_value_text(argv[0]))!=0 ){
82495    sqlite3_result_int(context, sqlite3_compileoption_used(zOptName));
82496  }
82497}
82498#endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
82499
82500/*
82501** Implementation of the sqlite_compileoption_get() function.
82502** The result is a string that identifies the compiler options
82503** used to build SQLite.
82504*/
82505#ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
82506static void compileoptiongetFunc(
82507  sqlite3_context *context,
82508  int argc,
82509  sqlite3_value **argv
82510){
82511  int n;
82512  assert( argc==1 );
82513  UNUSED_PARAMETER(argc);
82514  /* IMP: R-04922-24076 The sqlite_compileoption_get() SQL function
82515  ** is a wrapper around the sqlite3_compileoption_get() C/C++ function.
82516  */
82517  n = sqlite3_value_int(argv[0]);
82518  sqlite3_result_text(context, sqlite3_compileoption_get(n), -1, SQLITE_STATIC);
82519}
82520#endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
82521
82522/* Array for converting from half-bytes (nybbles) into ASCII hex
82523** digits. */
82524static const char hexdigits[] = {
82525  '0', '1', '2', '3', '4', '5', '6', '7',
82526  '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'
82527};
82528
82529/*
82530** EXPERIMENTAL - This is not an official function.  The interface may
82531** change.  This function may disappear.  Do not write code that depends
82532** on this function.
82533**
82534** Implementation of the QUOTE() function.  This function takes a single
82535** argument.  If the argument is numeric, the return value is the same as
82536** the argument.  If the argument is NULL, the return value is the string
82537** "NULL".  Otherwise, the argument is enclosed in single quotes with
82538** single-quote escapes.
82539*/
82540static void quoteFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
82541  assert( argc==1 );
82542  UNUSED_PARAMETER(argc);
82543  switch( sqlite3_value_type(argv[0]) ){
82544    case SQLITE_INTEGER:
82545    case SQLITE_FLOAT: {
82546      sqlite3_result_value(context, argv[0]);
82547      break;
82548    }
82549    case SQLITE_BLOB: {
82550      char *zText = 0;
82551      char const *zBlob = sqlite3_value_blob(argv[0]);
82552      int nBlob = sqlite3_value_bytes(argv[0]);
82553      assert( zBlob==sqlite3_value_blob(argv[0]) ); /* No encoding change */
82554      zText = (char *)contextMalloc(context, (2*(i64)nBlob)+4);
82555      if( zText ){
82556        int i;
82557        for(i=0; i<nBlob; i++){
82558          zText[(i*2)+2] = hexdigits[(zBlob[i]>>4)&0x0F];
82559          zText[(i*2)+3] = hexdigits[(zBlob[i])&0x0F];
82560        }
82561        zText[(nBlob*2)+2] = '\'';
82562        zText[(nBlob*2)+3] = '\0';
82563        zText[0] = 'X';
82564        zText[1] = '\'';
82565        sqlite3_result_text(context, zText, -1, SQLITE_TRANSIENT);
82566        sqlite3_free(zText);
82567      }
82568      break;
82569    }
82570    case SQLITE_TEXT: {
82571      int i,j;
82572      u64 n;
82573      const unsigned char *zArg = sqlite3_value_text(argv[0]);
82574      char *z;
82575
82576      if( zArg==0 ) return;
82577      for(i=0, n=0; zArg[i]; i++){ if( zArg[i]=='\'' ) n++; }
82578      z = contextMalloc(context, ((i64)i)+((i64)n)+3);
82579      if( z ){
82580        z[0] = '\'';
82581        for(i=0, j=1; zArg[i]; i++){
82582          z[j++] = zArg[i];
82583          if( zArg[i]=='\'' ){
82584            z[j++] = '\'';
82585          }
82586        }
82587        z[j++] = '\'';
82588        z[j] = 0;
82589        sqlite3_result_text(context, z, j, sqlite3_free);
82590      }
82591      break;
82592    }
82593    default: {
82594      assert( sqlite3_value_type(argv[0])==SQLITE_NULL );
82595      sqlite3_result_text(context, "NULL", 4, SQLITE_STATIC);
82596      break;
82597    }
82598  }
82599}
82600
82601/*
82602** The hex() function.  Interpret the argument as a blob.  Return
82603** a hexadecimal rendering as text.
82604*/
82605static void hexFunc(
82606  sqlite3_context *context,
82607  int argc,
82608  sqlite3_value **argv
82609){
82610  int i, n;
82611  const unsigned char *pBlob;
82612  char *zHex, *z;
82613  assert( argc==1 );
82614  UNUSED_PARAMETER(argc);
82615  pBlob = sqlite3_value_blob(argv[0]);
82616  n = sqlite3_value_bytes(argv[0]);
82617  assert( pBlob==sqlite3_value_blob(argv[0]) );  /* No encoding change */
82618  z = zHex = contextMalloc(context, ((i64)n)*2 + 1);
82619  if( zHex ){
82620    for(i=0; i<n; i++, pBlob++){
82621      unsigned char c = *pBlob;
82622      *(z++) = hexdigits[(c>>4)&0xf];
82623      *(z++) = hexdigits[c&0xf];
82624    }
82625    *z = 0;
82626    sqlite3_result_text(context, zHex, n*2, sqlite3_free);
82627  }
82628}
82629
82630/*
82631** The zeroblob(N) function returns a zero-filled blob of size N bytes.
82632*/
82633static void zeroblobFunc(
82634  sqlite3_context *context,
82635  int argc,
82636  sqlite3_value **argv
82637){
82638  i64 n;
82639  sqlite3 *db = sqlite3_context_db_handle(context);
82640  assert( argc==1 );
82641  UNUSED_PARAMETER(argc);
82642  n = sqlite3_value_int64(argv[0]);
82643  testcase( n==db->aLimit[SQLITE_LIMIT_LENGTH] );
82644  testcase( n==db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
82645  if( n>db->aLimit[SQLITE_LIMIT_LENGTH] ){
82646    sqlite3_result_error_toobig(context);
82647  }else{
82648    sqlite3_result_zeroblob(context, (int)n); /* IMP: R-00293-64994 */
82649  }
82650}
82651
82652/*
82653** The replace() function.  Three arguments are all strings: call
82654** them A, B, and C. The result is also a string which is derived
82655** from A by replacing every occurance of B with C.  The match
82656** must be exact.  Collating sequences are not used.
82657*/
82658static void replaceFunc(
82659  sqlite3_context *context,
82660  int argc,
82661  sqlite3_value **argv
82662){
82663  const unsigned char *zStr;        /* The input string A */
82664  const unsigned char *zPattern;    /* The pattern string B */
82665  const unsigned char *zRep;        /* The replacement string C */
82666  unsigned char *zOut;              /* The output */
82667  int nStr;                /* Size of zStr */
82668  int nPattern;            /* Size of zPattern */
82669  int nRep;                /* Size of zRep */
82670  i64 nOut;                /* Maximum size of zOut */
82671  int loopLimit;           /* Last zStr[] that might match zPattern[] */
82672  int i, j;                /* Loop counters */
82673
82674  assert( argc==3 );
82675  UNUSED_PARAMETER(argc);
82676  zStr = sqlite3_value_text(argv[0]);
82677  if( zStr==0 ) return;
82678  nStr = sqlite3_value_bytes(argv[0]);
82679  assert( zStr==sqlite3_value_text(argv[0]) );  /* No encoding change */
82680  zPattern = sqlite3_value_text(argv[1]);
82681  if( zPattern==0 ){
82682    assert( sqlite3_value_type(argv[1])==SQLITE_NULL
82683            || sqlite3_context_db_handle(context)->mallocFailed );
82684    return;
82685  }
82686  if( zPattern[0]==0 ){
82687    assert( sqlite3_value_type(argv[1])!=SQLITE_NULL );
82688    sqlite3_result_value(context, argv[0]);
82689    return;
82690  }
82691  nPattern = sqlite3_value_bytes(argv[1]);
82692  assert( zPattern==sqlite3_value_text(argv[1]) );  /* No encoding change */
82693  zRep = sqlite3_value_text(argv[2]);
82694  if( zRep==0 ) return;
82695  nRep = sqlite3_value_bytes(argv[2]);
82696  assert( zRep==sqlite3_value_text(argv[2]) );
82697  nOut = nStr + 1;
82698  assert( nOut<SQLITE_MAX_LENGTH );
82699  zOut = contextMalloc(context, (i64)nOut);
82700  if( zOut==0 ){
82701    return;
82702  }
82703  loopLimit = nStr - nPattern;
82704  for(i=j=0; i<=loopLimit; i++){
82705    if( zStr[i]!=zPattern[0] || memcmp(&zStr[i], zPattern, nPattern) ){
82706      zOut[j++] = zStr[i];
82707    }else{
82708      u8 *zOld;
82709      sqlite3 *db = sqlite3_context_db_handle(context);
82710      nOut += nRep - nPattern;
82711      testcase( nOut-1==db->aLimit[SQLITE_LIMIT_LENGTH] );
82712      testcase( nOut-2==db->aLimit[SQLITE_LIMIT_LENGTH] );
82713      if( nOut-1>db->aLimit[SQLITE_LIMIT_LENGTH] ){
82714        sqlite3_result_error_toobig(context);
82715        sqlite3_free(zOut);
82716        return;
82717      }
82718      zOld = zOut;
82719      zOut = sqlite3_realloc(zOut, (int)nOut);
82720      if( zOut==0 ){
82721        sqlite3_result_error_nomem(context);
82722        sqlite3_free(zOld);
82723        return;
82724      }
82725      memcpy(&zOut[j], zRep, nRep);
82726      j += nRep;
82727      i += nPattern-1;
82728    }
82729  }
82730  assert( j+nStr-i+1==nOut );
82731  memcpy(&zOut[j], &zStr[i], nStr-i);
82732  j += nStr - i;
82733  assert( j<=nOut );
82734  zOut[j] = 0;
82735  sqlite3_result_text(context, (char*)zOut, j, sqlite3_free);
82736}
82737
82738/*
82739** Implementation of the TRIM(), LTRIM(), and RTRIM() functions.
82740** The userdata is 0x1 for left trim, 0x2 for right trim, 0x3 for both.
82741*/
82742static void trimFunc(
82743  sqlite3_context *context,
82744  int argc,
82745  sqlite3_value **argv
82746){
82747  const unsigned char *zIn;         /* Input string */
82748  const unsigned char *zCharSet;    /* Set of characters to trim */
82749  int nIn;                          /* Number of bytes in input */
82750  int flags;                        /* 1: trimleft  2: trimright  3: trim */
82751  int i;                            /* Loop counter */
82752  unsigned char *aLen = 0;          /* Length of each character in zCharSet */
82753  unsigned char **azChar = 0;       /* Individual characters in zCharSet */
82754  int nChar;                        /* Number of characters in zCharSet */
82755
82756  if( sqlite3_value_type(argv[0])==SQLITE_NULL ){
82757    return;
82758  }
82759  zIn = sqlite3_value_text(argv[0]);
82760  if( zIn==0 ) return;
82761  nIn = sqlite3_value_bytes(argv[0]);
82762  assert( zIn==sqlite3_value_text(argv[0]) );
82763  if( argc==1 ){
82764    static const unsigned char lenOne[] = { 1 };
82765    static unsigned char * const azOne[] = { (u8*)" " };
82766    nChar = 1;
82767    aLen = (u8*)lenOne;
82768    azChar = (unsigned char **)azOne;
82769    zCharSet = 0;
82770  }else if( (zCharSet = sqlite3_value_text(argv[1]))==0 ){
82771    return;
82772  }else{
82773    const unsigned char *z;
82774    for(z=zCharSet, nChar=0; *z; nChar++){
82775      SQLITE_SKIP_UTF8(z);
82776    }
82777    if( nChar>0 ){
82778      azChar = contextMalloc(context, ((i64)nChar)*(sizeof(char*)+1));
82779      if( azChar==0 ){
82780        return;
82781      }
82782      aLen = (unsigned char*)&azChar[nChar];
82783      for(z=zCharSet, nChar=0; *z; nChar++){
82784        azChar[nChar] = (unsigned char *)z;
82785        SQLITE_SKIP_UTF8(z);
82786        aLen[nChar] = (u8)(z - azChar[nChar]);
82787      }
82788    }
82789  }
82790  if( nChar>0 ){
82791    flags = SQLITE_PTR_TO_INT(sqlite3_user_data(context));
82792    if( flags & 1 ){
82793      while( nIn>0 ){
82794        int len = 0;
82795        for(i=0; i<nChar; i++){
82796          len = aLen[i];
82797          if( len<=nIn && memcmp(zIn, azChar[i], len)==0 ) break;
82798        }
82799        if( i>=nChar ) break;
82800        zIn += len;
82801        nIn -= len;
82802      }
82803    }
82804    if( flags & 2 ){
82805      while( nIn>0 ){
82806        int len = 0;
82807        for(i=0; i<nChar; i++){
82808          len = aLen[i];
82809          if( len<=nIn && memcmp(&zIn[nIn-len],azChar[i],len)==0 ) break;
82810        }
82811        if( i>=nChar ) break;
82812        nIn -= len;
82813      }
82814    }
82815    if( zCharSet ){
82816      sqlite3_free((void*)azChar);
82817    }
82818  }
82819  sqlite3_result_text(context, (char*)zIn, nIn, SQLITE_TRANSIENT);
82820}
82821
82822
82823/* IMP: R-25361-16150 This function is omitted from SQLite by default. It
82824** is only available if the SQLITE_SOUNDEX compile-time option is used
82825** when SQLite is built.
82826*/
82827#ifdef SQLITE_SOUNDEX
82828/*
82829** Compute the soundex encoding of a word.
82830**
82831** IMP: R-59782-00072 The soundex(X) function returns a string that is the
82832** soundex encoding of the string X.
82833*/
82834static void soundexFunc(
82835  sqlite3_context *context,
82836  int argc,
82837  sqlite3_value **argv
82838){
82839  char zResult[8];
82840  const u8 *zIn;
82841  int i, j;
82842  static const unsigned char iCode[] = {
82843    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
82844    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
82845    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
82846    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
82847    0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
82848    1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
82849    0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
82850    1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
82851  };
82852  assert( argc==1 );
82853  zIn = (u8*)sqlite3_value_text(argv[0]);
82854  if( zIn==0 ) zIn = (u8*)"";
82855  for(i=0; zIn[i] && !sqlite3Isalpha(zIn[i]); i++){}
82856  if( zIn[i] ){
82857    u8 prevcode = iCode[zIn[i]&0x7f];
82858    zResult[0] = sqlite3Toupper(zIn[i]);
82859    for(j=1; j<4 && zIn[i]; i++){
82860      int code = iCode[zIn[i]&0x7f];
82861      if( code>0 ){
82862        if( code!=prevcode ){
82863          prevcode = code;
82864          zResult[j++] = code + '0';
82865        }
82866      }else{
82867        prevcode = 0;
82868      }
82869    }
82870    while( j<4 ){
82871      zResult[j++] = '0';
82872    }
82873    zResult[j] = 0;
82874    sqlite3_result_text(context, zResult, 4, SQLITE_TRANSIENT);
82875  }else{
82876    /* IMP: R-64894-50321 The string "?000" is returned if the argument
82877    ** is NULL or contains no ASCII alphabetic characters. */
82878    sqlite3_result_text(context, "?000", 4, SQLITE_STATIC);
82879  }
82880}
82881#endif /* SQLITE_SOUNDEX */
82882
82883#ifndef SQLITE_OMIT_LOAD_EXTENSION
82884/*
82885** A function that loads a shared-library extension then returns NULL.
82886*/
82887static void loadExt(sqlite3_context *context, int argc, sqlite3_value **argv){
82888  const char *zFile = (const char *)sqlite3_value_text(argv[0]);
82889  const char *zProc;
82890  sqlite3 *db = sqlite3_context_db_handle(context);
82891  char *zErrMsg = 0;
82892
82893  if( argc==2 ){
82894    zProc = (const char *)sqlite3_value_text(argv[1]);
82895  }else{
82896    zProc = 0;
82897  }
82898  if( zFile && sqlite3_load_extension(db, zFile, zProc, &zErrMsg) ){
82899    sqlite3_result_error(context, zErrMsg, -1);
82900    sqlite3_free(zErrMsg);
82901  }
82902}
82903#endif
82904
82905
82906/*
82907** An instance of the following structure holds the context of a
82908** sum() or avg() aggregate computation.
82909*/
82910typedef struct SumCtx SumCtx;
82911struct SumCtx {
82912  double rSum;      /* Floating point sum */
82913  i64 iSum;         /* Integer sum */
82914  i64 cnt;          /* Number of elements summed */
82915  u8 overflow;      /* True if integer overflow seen */
82916  u8 approx;        /* True if non-integer value was input to the sum */
82917};
82918
82919/*
82920** Routines used to compute the sum, average, and total.
82921**
82922** The SUM() function follows the (broken) SQL standard which means
82923** that it returns NULL if it sums over no inputs.  TOTAL returns
82924** 0.0 in that case.  In addition, TOTAL always returns a float where
82925** SUM might return an integer if it never encounters a floating point
82926** value.  TOTAL never fails, but SUM might through an exception if
82927** it overflows an integer.
82928*/
82929static void sumStep(sqlite3_context *context, int argc, sqlite3_value **argv){
82930  SumCtx *p;
82931  int type;
82932  assert( argc==1 );
82933  UNUSED_PARAMETER(argc);
82934  p = sqlite3_aggregate_context(context, sizeof(*p));
82935  type = sqlite3_value_numeric_type(argv[0]);
82936  if( p && type!=SQLITE_NULL ){
82937    p->cnt++;
82938    if( type==SQLITE_INTEGER ){
82939      i64 v = sqlite3_value_int64(argv[0]);
82940      p->rSum += v;
82941      if( (p->approx|p->overflow)==0 && sqlite3AddInt64(&p->iSum, v) ){
82942        p->overflow = 1;
82943      }
82944    }else{
82945      p->rSum += sqlite3_value_double(argv[0]);
82946      p->approx = 1;
82947    }
82948  }
82949}
82950static void sumFinalize(sqlite3_context *context){
82951  SumCtx *p;
82952  p = sqlite3_aggregate_context(context, 0);
82953  if( p && p->cnt>0 ){
82954    if( p->overflow ){
82955      sqlite3_result_error(context,"integer overflow",-1);
82956    }else if( p->approx ){
82957      sqlite3_result_double(context, p->rSum);
82958    }else{
82959      sqlite3_result_int64(context, p->iSum);
82960    }
82961  }
82962}
82963static void avgFinalize(sqlite3_context *context){
82964  SumCtx *p;
82965  p = sqlite3_aggregate_context(context, 0);
82966  if( p && p->cnt>0 ){
82967    sqlite3_result_double(context, p->rSum/(double)p->cnt);
82968  }
82969}
82970static void totalFinalize(sqlite3_context *context){
82971  SumCtx *p;
82972  p = sqlite3_aggregate_context(context, 0);
82973  /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
82974  sqlite3_result_double(context, p ? p->rSum : (double)0);
82975}
82976
82977/*
82978** The following structure keeps track of state information for the
82979** count() aggregate function.
82980*/
82981typedef struct CountCtx CountCtx;
82982struct CountCtx {
82983  i64 n;
82984};
82985
82986/*
82987** Routines to implement the count() aggregate function.
82988*/
82989static void countStep(sqlite3_context *context, int argc, sqlite3_value **argv){
82990  CountCtx *p;
82991  p = sqlite3_aggregate_context(context, sizeof(*p));
82992  if( (argc==0 || SQLITE_NULL!=sqlite3_value_type(argv[0])) && p ){
82993    p->n++;
82994  }
82995
82996#ifndef SQLITE_OMIT_DEPRECATED
82997  /* The sqlite3_aggregate_count() function is deprecated.  But just to make
82998  ** sure it still operates correctly, verify that its count agrees with our
82999  ** internal count when using count(*) and when the total count can be
83000  ** expressed as a 32-bit integer. */
83001  assert( argc==1 || p==0 || p->n>0x7fffffff
83002          || p->n==sqlite3_aggregate_count(context) );
83003#endif
83004}
83005static void countFinalize(sqlite3_context *context){
83006  CountCtx *p;
83007  p = sqlite3_aggregate_context(context, 0);
83008  sqlite3_result_int64(context, p ? p->n : 0);
83009}
83010
83011/*
83012** Routines to implement min() and max() aggregate functions.
83013*/
83014static void minmaxStep(
83015  sqlite3_context *context,
83016  int NotUsed,
83017  sqlite3_value **argv
83018){
83019  Mem *pArg  = (Mem *)argv[0];
83020  Mem *pBest;
83021  UNUSED_PARAMETER(NotUsed);
83022
83023  if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
83024  pBest = (Mem *)sqlite3_aggregate_context(context, sizeof(*pBest));
83025  if( !pBest ) return;
83026
83027  if( pBest->flags ){
83028    int max;
83029    int cmp;
83030    CollSeq *pColl = sqlite3GetFuncCollSeq(context);
83031    /* This step function is used for both the min() and max() aggregates,
83032    ** the only difference between the two being that the sense of the
83033    ** comparison is inverted. For the max() aggregate, the
83034    ** sqlite3_user_data() function returns (void *)-1. For min() it
83035    ** returns (void *)db, where db is the sqlite3* database pointer.
83036    ** Therefore the next statement sets variable 'max' to 1 for the max()
83037    ** aggregate, or 0 for min().
83038    */
83039    max = sqlite3_user_data(context)!=0;
83040    cmp = sqlite3MemCompare(pBest, pArg, pColl);
83041    if( (max && cmp<0) || (!max && cmp>0) ){
83042      sqlite3VdbeMemCopy(pBest, pArg);
83043    }
83044  }else{
83045    sqlite3VdbeMemCopy(pBest, pArg);
83046  }
83047}
83048static void minMaxFinalize(sqlite3_context *context){
83049  sqlite3_value *pRes;
83050  pRes = (sqlite3_value *)sqlite3_aggregate_context(context, 0);
83051  if( pRes ){
83052    if( ALWAYS(pRes->flags) ){
83053      sqlite3_result_value(context, pRes);
83054    }
83055    sqlite3VdbeMemRelease(pRes);
83056  }
83057}
83058
83059/*
83060** group_concat(EXPR, ?SEPARATOR?)
83061*/
83062static void groupConcatStep(
83063  sqlite3_context *context,
83064  int argc,
83065  sqlite3_value **argv
83066){
83067  const char *zVal;
83068  StrAccum *pAccum;
83069  const char *zSep;
83070  int nVal, nSep;
83071  assert( argc==1 || argc==2 );
83072  if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
83073  pAccum = (StrAccum*)sqlite3_aggregate_context(context, sizeof(*pAccum));
83074
83075  if( pAccum ){
83076    sqlite3 *db = sqlite3_context_db_handle(context);
83077    int firstTerm = pAccum->useMalloc==0;
83078    pAccum->useMalloc = 2;
83079    pAccum->mxAlloc = db->aLimit[SQLITE_LIMIT_LENGTH];
83080    if( !firstTerm ){
83081      if( argc==2 ){
83082        zSep = (char*)sqlite3_value_text(argv[1]);
83083        nSep = sqlite3_value_bytes(argv[1]);
83084      }else{
83085        zSep = ",";
83086        nSep = 1;
83087      }
83088      sqlite3StrAccumAppend(pAccum, zSep, nSep);
83089    }
83090    zVal = (char*)sqlite3_value_text(argv[0]);
83091    nVal = sqlite3_value_bytes(argv[0]);
83092    sqlite3StrAccumAppend(pAccum, zVal, nVal);
83093  }
83094}
83095static void groupConcatFinalize(sqlite3_context *context){
83096  StrAccum *pAccum;
83097  pAccum = sqlite3_aggregate_context(context, 0);
83098  if( pAccum ){
83099    if( pAccum->tooBig ){
83100      sqlite3_result_error_toobig(context);
83101    }else if( pAccum->mallocFailed ){
83102      sqlite3_result_error_nomem(context);
83103    }else{
83104      sqlite3_result_text(context, sqlite3StrAccumFinish(pAccum), -1,
83105                          sqlite3_free);
83106    }
83107  }
83108}
83109
83110/*
83111** This routine does per-connection function registration.  Most
83112** of the built-in functions above are part of the global function set.
83113** This routine only deals with those that are not global.
83114*/
83115SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(sqlite3 *db){
83116  int rc = sqlite3_overload_function(db, "MATCH", 2);
83117  assert( rc==SQLITE_NOMEM || rc==SQLITE_OK );
83118  if( rc==SQLITE_NOMEM ){
83119    db->mallocFailed = 1;
83120  }
83121}
83122
83123/*
83124** Set the LIKEOPT flag on the 2-argument function with the given name.
83125*/
83126static void setLikeOptFlag(sqlite3 *db, const char *zName, u8 flagVal){
83127  FuncDef *pDef;
83128  pDef = sqlite3FindFunction(db, zName, sqlite3Strlen30(zName),
83129                             2, SQLITE_UTF8, 0);
83130  if( ALWAYS(pDef) ){
83131    pDef->flags = flagVal;
83132  }
83133}
83134
83135/*
83136** Register the built-in LIKE and GLOB functions.  The caseSensitive
83137** parameter determines whether or not the LIKE operator is case
83138** sensitive.  GLOB is always case sensitive.
83139*/
83140SQLITE_PRIVATE void sqlite3RegisterLikeFunctions(sqlite3 *db, int caseSensitive){
83141  struct compareInfo *pInfo;
83142  if( caseSensitive ){
83143    pInfo = (struct compareInfo*)&likeInfoAlt;
83144  }else{
83145    pInfo = (struct compareInfo*)&likeInfoNorm;
83146  }
83147  sqlite3CreateFunc(db, "like", 2, SQLITE_UTF8, pInfo, likeFunc, 0, 0, 0);
83148  sqlite3CreateFunc(db, "like", 3, SQLITE_UTF8, pInfo, likeFunc, 0, 0, 0);
83149  sqlite3CreateFunc(db, "glob", 2, SQLITE_UTF8,
83150      (struct compareInfo*)&globInfo, likeFunc, 0, 0, 0);
83151  setLikeOptFlag(db, "glob", SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE);
83152  setLikeOptFlag(db, "like",
83153      caseSensitive ? (SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE) : SQLITE_FUNC_LIKE);
83154}
83155
83156/*
83157** pExpr points to an expression which implements a function.  If
83158** it is appropriate to apply the LIKE optimization to that function
83159** then set aWc[0] through aWc[2] to the wildcard characters and
83160** return TRUE.  If the function is not a LIKE-style function then
83161** return FALSE.
83162*/
83163SQLITE_PRIVATE int sqlite3IsLikeFunction(sqlite3 *db, Expr *pExpr, int *pIsNocase, char *aWc){
83164  FuncDef *pDef;
83165  if( pExpr->op!=TK_FUNCTION
83166   || !pExpr->x.pList
83167   || pExpr->x.pList->nExpr!=2
83168  ){
83169    return 0;
83170  }
83171  assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
83172  pDef = sqlite3FindFunction(db, pExpr->u.zToken,
83173                             sqlite3Strlen30(pExpr->u.zToken),
83174                             2, SQLITE_UTF8, 0);
83175  if( NEVER(pDef==0) || (pDef->flags & SQLITE_FUNC_LIKE)==0 ){
83176    return 0;
83177  }
83178
83179  /* The memcpy() statement assumes that the wildcard characters are
83180  ** the first three statements in the compareInfo structure.  The
83181  ** asserts() that follow verify that assumption
83182  */
83183  memcpy(aWc, pDef->pUserData, 3);
83184  assert( (char*)&likeInfoAlt == (char*)&likeInfoAlt.matchAll );
83185  assert( &((char*)&likeInfoAlt)[1] == (char*)&likeInfoAlt.matchOne );
83186  assert( &((char*)&likeInfoAlt)[2] == (char*)&likeInfoAlt.matchSet );
83187  *pIsNocase = (pDef->flags & SQLITE_FUNC_CASE)==0;
83188  return 1;
83189}
83190
83191/*
83192** All all of the FuncDef structures in the aBuiltinFunc[] array above
83193** to the global function hash table.  This occurs at start-time (as
83194** a consequence of calling sqlite3_initialize()).
83195**
83196** After this routine runs
83197*/
83198SQLITE_PRIVATE void sqlite3RegisterGlobalFunctions(void){
83199  /*
83200  ** The following array holds FuncDef structures for all of the functions
83201  ** defined in this file.
83202  **
83203  ** The array cannot be constant since changes are made to the
83204  ** FuncDef.pHash elements at start-time.  The elements of this array
83205  ** are read-only after initialization is complete.
83206  */
83207  static SQLITE_WSD FuncDef aBuiltinFunc[] = {
83208    FUNCTION(ltrim,              1, 1, 0, trimFunc         ),
83209    FUNCTION(ltrim,              2, 1, 0, trimFunc         ),
83210    FUNCTION(rtrim,              1, 2, 0, trimFunc         ),
83211    FUNCTION(rtrim,              2, 2, 0, trimFunc         ),
83212    FUNCTION(trim,               1, 3, 0, trimFunc         ),
83213    FUNCTION(trim,               2, 3, 0, trimFunc         ),
83214    FUNCTION(min,               -1, 0, 1, minmaxFunc       ),
83215    FUNCTION(min,                0, 0, 1, 0                ),
83216    AGGREGATE(min,               1, 0, 1, minmaxStep,      minMaxFinalize ),
83217    FUNCTION(max,               -1, 1, 1, minmaxFunc       ),
83218    FUNCTION(max,                0, 1, 1, 0                ),
83219    AGGREGATE(max,               1, 1, 1, minmaxStep,      minMaxFinalize ),
83220    FUNCTION(typeof,             1, 0, 0, typeofFunc       ),
83221    FUNCTION(length,             1, 0, 0, lengthFunc       ),
83222    FUNCTION(substr,             2, 0, 0, substrFunc       ),
83223    FUNCTION(substr,             3, 0, 0, substrFunc       ),
83224    FUNCTION(abs,                1, 0, 0, absFunc          ),
83225#ifndef SQLITE_OMIT_FLOATING_POINT
83226    FUNCTION(round,              1, 0, 0, roundFunc        ),
83227    FUNCTION(round,              2, 0, 0, roundFunc        ),
83228#endif
83229    FUNCTION(upper,              1, 0, 0, upperFunc        ),
83230    FUNCTION(lower,              1, 0, 0, lowerFunc        ),
83231    FUNCTION(coalesce,           1, 0, 0, 0                ),
83232    FUNCTION(coalesce,           0, 0, 0, 0                ),
83233/*  FUNCTION(coalesce,          -1, 0, 0, ifnullFunc       ), */
83234    {-1,SQLITE_UTF8,SQLITE_FUNC_COALESCE,0,0,ifnullFunc,0,0,"coalesce",0,0},
83235    FUNCTION(hex,                1, 0, 0, hexFunc          ),
83236/*  FUNCTION(ifnull,             2, 0, 0, ifnullFunc       ), */
83237    {2,SQLITE_UTF8,SQLITE_FUNC_COALESCE,0,0,ifnullFunc,0,0,"ifnull",0,0},
83238    FUNCTION(random,             0, 0, 0, randomFunc       ),
83239    FUNCTION(randomblob,         1, 0, 0, randomBlob       ),
83240    FUNCTION(nullif,             2, 0, 1, nullifFunc       ),
83241    FUNCTION(sqlite_version,     0, 0, 0, versionFunc      ),
83242    FUNCTION(sqlite_source_id,   0, 0, 0, sourceidFunc     ),
83243#ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
83244    FUNCTION(sqlite_compileoption_used,1, 0, 0, compileoptionusedFunc  ),
83245    FUNCTION(sqlite_compileoption_get, 1, 0, 0, compileoptiongetFunc  ),
83246#endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
83247    FUNCTION(quote,              1, 0, 0, quoteFunc        ),
83248    FUNCTION(last_insert_rowid,  0, 0, 0, last_insert_rowid),
83249    FUNCTION(changes,            0, 0, 0, changes          ),
83250    FUNCTION(total_changes,      0, 0, 0, total_changes    ),
83251    FUNCTION(replace,            3, 0, 0, replaceFunc      ),
83252    FUNCTION(zeroblob,           1, 0, 0, zeroblobFunc     ),
83253  #ifdef SQLITE_SOUNDEX
83254    FUNCTION(soundex,            1, 0, 0, soundexFunc      ),
83255  #endif
83256  #ifndef SQLITE_OMIT_LOAD_EXTENSION
83257    FUNCTION(load_extension,     1, 0, 0, loadExt          ),
83258    FUNCTION(load_extension,     2, 0, 0, loadExt          ),
83259  #endif
83260    AGGREGATE(sum,               1, 0, 0, sumStep,         sumFinalize    ),
83261    AGGREGATE(total,             1, 0, 0, sumStep,         totalFinalize    ),
83262    AGGREGATE(avg,               1, 0, 0, sumStep,         avgFinalize    ),
83263 /* AGGREGATE(count,             0, 0, 0, countStep,       countFinalize  ), */
83264    {0,SQLITE_UTF8,SQLITE_FUNC_COUNT,0,0,0,countStep,countFinalize,"count",0,0},
83265    AGGREGATE(count,             1, 0, 0, countStep,       countFinalize  ),
83266    AGGREGATE(group_concat,      1, 0, 0, groupConcatStep, groupConcatFinalize),
83267    AGGREGATE(group_concat,      2, 0, 0, groupConcatStep, groupConcatFinalize),
83268
83269    LIKEFUNC(glob, 2, &globInfo, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
83270  #ifdef SQLITE_CASE_SENSITIVE_LIKE
83271    LIKEFUNC(like, 2, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
83272    LIKEFUNC(like, 3, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
83273  #else
83274    LIKEFUNC(like, 2, &likeInfoNorm, SQLITE_FUNC_LIKE),
83275    LIKEFUNC(like, 3, &likeInfoNorm, SQLITE_FUNC_LIKE),
83276  #endif
83277  };
83278
83279  int i;
83280  FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
83281  FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aBuiltinFunc);
83282
83283  for(i=0; i<ArraySize(aBuiltinFunc); i++){
83284    sqlite3FuncDefInsert(pHash, &aFunc[i]);
83285  }
83286  sqlite3RegisterDateTimeFunctions();
83287#ifndef SQLITE_OMIT_ALTERTABLE
83288  sqlite3AlterFunctions();
83289#endif
83290}
83291
83292/************** End of func.c ************************************************/
83293/************** Begin file fkey.c ********************************************/
83294/*
83295**
83296** The author disclaims copyright to this source code.  In place of
83297** a legal notice, here is a blessing:
83298**
83299**    May you do good and not evil.
83300**    May you find forgiveness for yourself and forgive others.
83301**    May you share freely, never taking more than you give.
83302**
83303*************************************************************************
83304** This file contains code used by the compiler to add foreign key
83305** support to compiled SQL statements.
83306*/
83307
83308#ifndef SQLITE_OMIT_FOREIGN_KEY
83309#ifndef SQLITE_OMIT_TRIGGER
83310
83311/*
83312** Deferred and Immediate FKs
83313** --------------------------
83314**
83315** Foreign keys in SQLite come in two flavours: deferred and immediate.
83316** If an immediate foreign key constraint is violated, SQLITE_CONSTRAINT
83317** is returned and the current statement transaction rolled back. If a
83318** deferred foreign key constraint is violated, no action is taken
83319** immediately. However if the application attempts to commit the
83320** transaction before fixing the constraint violation, the attempt fails.
83321**
83322** Deferred constraints are implemented using a simple counter associated
83323** with the database handle. The counter is set to zero each time a
83324** database transaction is opened. Each time a statement is executed
83325** that causes a foreign key violation, the counter is incremented. Each
83326** time a statement is executed that removes an existing violation from
83327** the database, the counter is decremented. When the transaction is
83328** committed, the commit fails if the current value of the counter is
83329** greater than zero. This scheme has two big drawbacks:
83330**
83331**   * When a commit fails due to a deferred foreign key constraint,
83332**     there is no way to tell which foreign constraint is not satisfied,
83333**     or which row it is not satisfied for.
83334**
83335**   * If the database contains foreign key violations when the
83336**     transaction is opened, this may cause the mechanism to malfunction.
83337**
83338** Despite these problems, this approach is adopted as it seems simpler
83339** than the alternatives.
83340**
83341** INSERT operations:
83342**
83343**   I.1) For each FK for which the table is the child table, search
83344**        the parent table for a match. If none is found increment the
83345**        constraint counter.
83346**
83347**   I.2) For each FK for which the table is the parent table,
83348**        search the child table for rows that correspond to the new
83349**        row in the parent table. Decrement the counter for each row
83350**        found (as the constraint is now satisfied).
83351**
83352** DELETE operations:
83353**
83354**   D.1) For each FK for which the table is the child table,
83355**        search the parent table for a row that corresponds to the
83356**        deleted row in the child table. If such a row is not found,
83357**        decrement the counter.
83358**
83359**   D.2) For each FK for which the table is the parent table, search
83360**        the child table for rows that correspond to the deleted row
83361**        in the parent table. For each found increment the counter.
83362**
83363** UPDATE operations:
83364**
83365**   An UPDATE command requires that all 4 steps above are taken, but only
83366**   for FK constraints for which the affected columns are actually
83367**   modified (values must be compared at runtime).
83368**
83369** Note that I.1 and D.1 are very similar operations, as are I.2 and D.2.
83370** This simplifies the implementation a bit.
83371**
83372** For the purposes of immediate FK constraints, the OR REPLACE conflict
83373** resolution is considered to delete rows before the new row is inserted.
83374** If a delete caused by OR REPLACE violates an FK constraint, an exception
83375** is thrown, even if the FK constraint would be satisfied after the new
83376** row is inserted.
83377**
83378** Immediate constraints are usually handled similarly. The only difference
83379** is that the counter used is stored as part of each individual statement
83380** object (struct Vdbe). If, after the statement has run, its immediate
83381** constraint counter is greater than zero, it returns SQLITE_CONSTRAINT
83382** and the statement transaction is rolled back. An exception is an INSERT
83383** statement that inserts a single row only (no triggers). In this case,
83384** instead of using a counter, an exception is thrown immediately if the
83385** INSERT violates a foreign key constraint. This is necessary as such
83386** an INSERT does not open a statement transaction.
83387**
83388** TODO: How should dropping a table be handled? How should renaming a
83389** table be handled?
83390**
83391**
83392** Query API Notes
83393** ---------------
83394**
83395** Before coding an UPDATE or DELETE row operation, the code-generator
83396** for those two operations needs to know whether or not the operation
83397** requires any FK processing and, if so, which columns of the original
83398** row are required by the FK processing VDBE code (i.e. if FKs were
83399** implemented using triggers, which of the old.* columns would be
83400** accessed). No information is required by the code-generator before
83401** coding an INSERT operation. The functions used by the UPDATE/DELETE
83402** generation code to query for this information are:
83403**
83404**   sqlite3FkRequired() - Test to see if FK processing is required.
83405**   sqlite3FkOldmask()  - Query for the set of required old.* columns.
83406**
83407**
83408** Externally accessible module functions
83409** --------------------------------------
83410**
83411**   sqlite3FkCheck()    - Check for foreign key violations.
83412**   sqlite3FkActions()  - Code triggers for ON UPDATE/ON DELETE actions.
83413**   sqlite3FkDelete()   - Delete an FKey structure.
83414*/
83415
83416/*
83417** VDBE Calling Convention
83418** -----------------------
83419**
83420** Example:
83421**
83422**   For the following INSERT statement:
83423**
83424**     CREATE TABLE t1(a, b INTEGER PRIMARY KEY, c);
83425**     INSERT INTO t1 VALUES(1, 2, 3.1);
83426**
83427**   Register (x):        2    (type integer)
83428**   Register (x+1):      1    (type integer)
83429**   Register (x+2):      NULL (type NULL)
83430**   Register (x+3):      3.1  (type real)
83431*/
83432
83433/*
83434** A foreign key constraint requires that the key columns in the parent
83435** table are collectively subject to a UNIQUE or PRIMARY KEY constraint.
83436** Given that pParent is the parent table for foreign key constraint pFKey,
83437** search the schema a unique index on the parent key columns.
83438**
83439** If successful, zero is returned. If the parent key is an INTEGER PRIMARY
83440** KEY column, then output variable *ppIdx is set to NULL. Otherwise, *ppIdx
83441** is set to point to the unique index.
83442**
83443** If the parent key consists of a single column (the foreign key constraint
83444** is not a composite foreign key), output variable *paiCol is set to NULL.
83445** Otherwise, it is set to point to an allocated array of size N, where
83446** N is the number of columns in the parent key. The first element of the
83447** array is the index of the child table column that is mapped by the FK
83448** constraint to the parent table column stored in the left-most column
83449** of index *ppIdx. The second element of the array is the index of the
83450** child table column that corresponds to the second left-most column of
83451** *ppIdx, and so on.
83452**
83453** If the required index cannot be found, either because:
83454**
83455**   1) The named parent key columns do not exist, or
83456**
83457**   2) The named parent key columns do exist, but are not subject to a
83458**      UNIQUE or PRIMARY KEY constraint, or
83459**
83460**   3) No parent key columns were provided explicitly as part of the
83461**      foreign key definition, and the parent table does not have a
83462**      PRIMARY KEY, or
83463**
83464**   4) No parent key columns were provided explicitly as part of the
83465**      foreign key definition, and the PRIMARY KEY of the parent table
83466**      consists of a a different number of columns to the child key in
83467**      the child table.
83468**
83469** then non-zero is returned, and a "foreign key mismatch" error loaded
83470** into pParse. If an OOM error occurs, non-zero is returned and the
83471** pParse->db->mallocFailed flag is set.
83472*/
83473static int locateFkeyIndex(
83474  Parse *pParse,                  /* Parse context to store any error in */
83475  Table *pParent,                 /* Parent table of FK constraint pFKey */
83476  FKey *pFKey,                    /* Foreign key to find index for */
83477  Index **ppIdx,                  /* OUT: Unique index on parent table */
83478  int **paiCol                    /* OUT: Map of index columns in pFKey */
83479){
83480  Index *pIdx = 0;                    /* Value to return via *ppIdx */
83481  int *aiCol = 0;                     /* Value to return via *paiCol */
83482  int nCol = pFKey->nCol;             /* Number of columns in parent key */
83483  char *zKey = pFKey->aCol[0].zCol;   /* Name of left-most parent key column */
83484
83485  /* The caller is responsible for zeroing output parameters. */
83486  assert( ppIdx && *ppIdx==0 );
83487  assert( !paiCol || *paiCol==0 );
83488  assert( pParse );
83489
83490  /* If this is a non-composite (single column) foreign key, check if it
83491  ** maps to the INTEGER PRIMARY KEY of table pParent. If so, leave *ppIdx
83492  ** and *paiCol set to zero and return early.
83493  **
83494  ** Otherwise, for a composite foreign key (more than one column), allocate
83495  ** space for the aiCol array (returned via output parameter *paiCol).
83496  ** Non-composite foreign keys do not require the aiCol array.
83497  */
83498  if( nCol==1 ){
83499    /* The FK maps to the IPK if any of the following are true:
83500    **
83501    **   1) There is an INTEGER PRIMARY KEY column and the FK is implicitly
83502    **      mapped to the primary key of table pParent, or
83503    **   2) The FK is explicitly mapped to a column declared as INTEGER
83504    **      PRIMARY KEY.
83505    */
83506    if( pParent->iPKey>=0 ){
83507      if( !zKey ) return 0;
83508      if( !sqlite3StrICmp(pParent->aCol[pParent->iPKey].zName, zKey) ) return 0;
83509    }
83510  }else if( paiCol ){
83511    assert( nCol>1 );
83512    aiCol = (int *)sqlite3DbMallocRaw(pParse->db, nCol*sizeof(int));
83513    if( !aiCol ) return 1;
83514    *paiCol = aiCol;
83515  }
83516
83517  for(pIdx=pParent->pIndex; pIdx; pIdx=pIdx->pNext){
83518    if( pIdx->nColumn==nCol && pIdx->onError!=OE_None ){
83519      /* pIdx is a UNIQUE index (or a PRIMARY KEY) and has the right number
83520      ** of columns. If each indexed column corresponds to a foreign key
83521      ** column of pFKey, then this index is a winner.  */
83522
83523      if( zKey==0 ){
83524        /* If zKey is NULL, then this foreign key is implicitly mapped to
83525        ** the PRIMARY KEY of table pParent. The PRIMARY KEY index may be
83526        ** identified by the test (Index.autoIndex==2).  */
83527        if( pIdx->autoIndex==2 ){
83528          if( aiCol ){
83529            int i;
83530            for(i=0; i<nCol; i++) aiCol[i] = pFKey->aCol[i].iFrom;
83531          }
83532          break;
83533        }
83534      }else{
83535        /* If zKey is non-NULL, then this foreign key was declared to
83536        ** map to an explicit list of columns in table pParent. Check if this
83537        ** index matches those columns. Also, check that the index uses
83538        ** the default collation sequences for each column. */
83539        int i, j;
83540        for(i=0; i<nCol; i++){
83541          int iCol = pIdx->aiColumn[i];     /* Index of column in parent tbl */
83542          char *zDfltColl;                  /* Def. collation for column */
83543          char *zIdxCol;                    /* Name of indexed column */
83544
83545          /* If the index uses a collation sequence that is different from
83546          ** the default collation sequence for the column, this index is
83547          ** unusable. Bail out early in this case.  */
83548          zDfltColl = pParent->aCol[iCol].zColl;
83549          if( !zDfltColl ){
83550            zDfltColl = "BINARY";
83551          }
83552          if( sqlite3StrICmp(pIdx->azColl[i], zDfltColl) ) break;
83553
83554          zIdxCol = pParent->aCol[iCol].zName;
83555          for(j=0; j<nCol; j++){
83556            if( sqlite3StrICmp(pFKey->aCol[j].zCol, zIdxCol)==0 ){
83557              if( aiCol ) aiCol[i] = pFKey->aCol[j].iFrom;
83558              break;
83559            }
83560          }
83561          if( j==nCol ) break;
83562        }
83563        if( i==nCol ) break;      /* pIdx is usable */
83564      }
83565    }
83566  }
83567
83568  if( !pIdx ){
83569    if( !pParse->disableTriggers ){
83570      sqlite3ErrorMsg(pParse, "foreign key mismatch");
83571    }
83572    sqlite3DbFree(pParse->db, aiCol);
83573    return 1;
83574  }
83575
83576  *ppIdx = pIdx;
83577  return 0;
83578}
83579
83580/*
83581** This function is called when a row is inserted into or deleted from the
83582** child table of foreign key constraint pFKey. If an SQL UPDATE is executed
83583** on the child table of pFKey, this function is invoked twice for each row
83584** affected - once to "delete" the old row, and then again to "insert" the
83585** new row.
83586**
83587** Each time it is called, this function generates VDBE code to locate the
83588** row in the parent table that corresponds to the row being inserted into
83589** or deleted from the child table. If the parent row can be found, no
83590** special action is taken. Otherwise, if the parent row can *not* be
83591** found in the parent table:
83592**
83593**   Operation | FK type   | Action taken
83594**   --------------------------------------------------------------------------
83595**   INSERT      immediate   Increment the "immediate constraint counter".
83596**
83597**   DELETE      immediate   Decrement the "immediate constraint counter".
83598**
83599**   INSERT      deferred    Increment the "deferred constraint counter".
83600**
83601**   DELETE      deferred    Decrement the "deferred constraint counter".
83602**
83603** These operations are identified in the comment at the top of this file
83604** (fkey.c) as "I.1" and "D.1".
83605*/
83606static void fkLookupParent(
83607  Parse *pParse,        /* Parse context */
83608  int iDb,              /* Index of database housing pTab */
83609  Table *pTab,          /* Parent table of FK pFKey */
83610  Index *pIdx,          /* Unique index on parent key columns in pTab */
83611  FKey *pFKey,          /* Foreign key constraint */
83612  int *aiCol,           /* Map from parent key columns to child table columns */
83613  int regData,          /* Address of array containing child table row */
83614  int nIncr,            /* Increment constraint counter by this */
83615  int isIgnore          /* If true, pretend pTab contains all NULL values */
83616){
83617  int i;                                    /* Iterator variable */
83618  Vdbe *v = sqlite3GetVdbe(pParse);         /* Vdbe to add code to */
83619  int iCur = pParse->nTab - 1;              /* Cursor number to use */
83620  int iOk = sqlite3VdbeMakeLabel(v);        /* jump here if parent key found */
83621
83622  /* If nIncr is less than zero, then check at runtime if there are any
83623  ** outstanding constraints to resolve. If there are not, there is no need
83624  ** to check if deleting this row resolves any outstanding violations.
83625  **
83626  ** Check if any of the key columns in the child table row are NULL. If
83627  ** any are, then the constraint is considered satisfied. No need to
83628  ** search for a matching row in the parent table.  */
83629  if( nIncr<0 ){
83630    sqlite3VdbeAddOp2(v, OP_FkIfZero, pFKey->isDeferred, iOk);
83631  }
83632  for(i=0; i<pFKey->nCol; i++){
83633    int iReg = aiCol[i] + regData + 1;
83634    sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iOk);
83635  }
83636
83637  if( isIgnore==0 ){
83638    if( pIdx==0 ){
83639      /* If pIdx is NULL, then the parent key is the INTEGER PRIMARY KEY
83640      ** column of the parent table (table pTab).  */
83641      int iMustBeInt;               /* Address of MustBeInt instruction */
83642      int regTemp = sqlite3GetTempReg(pParse);
83643
83644      /* Invoke MustBeInt to coerce the child key value to an integer (i.e.
83645      ** apply the affinity of the parent key). If this fails, then there
83646      ** is no matching parent key. Before using MustBeInt, make a copy of
83647      ** the value. Otherwise, the value inserted into the child key column
83648      ** will have INTEGER affinity applied to it, which may not be correct.  */
83649      sqlite3VdbeAddOp2(v, OP_SCopy, aiCol[0]+1+regData, regTemp);
83650      iMustBeInt = sqlite3VdbeAddOp2(v, OP_MustBeInt, regTemp, 0);
83651
83652      /* If the parent table is the same as the child table, and we are about
83653      ** to increment the constraint-counter (i.e. this is an INSERT operation),
83654      ** then check if the row being inserted matches itself. If so, do not
83655      ** increment the constraint-counter.  */
83656      if( pTab==pFKey->pFrom && nIncr==1 ){
83657        sqlite3VdbeAddOp3(v, OP_Eq, regData, iOk, regTemp);
83658      }
83659
83660      sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenRead);
83661      sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, regTemp);
83662      sqlite3VdbeAddOp2(v, OP_Goto, 0, iOk);
83663      sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-2);
83664      sqlite3VdbeJumpHere(v, iMustBeInt);
83665      sqlite3ReleaseTempReg(pParse, regTemp);
83666    }else{
83667      int nCol = pFKey->nCol;
83668      int regTemp = sqlite3GetTempRange(pParse, nCol);
83669      int regRec = sqlite3GetTempReg(pParse);
83670      KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
83671
83672      sqlite3VdbeAddOp3(v, OP_OpenRead, iCur, pIdx->tnum, iDb);
83673      sqlite3VdbeChangeP4(v, -1, (char*)pKey, P4_KEYINFO_HANDOFF);
83674      for(i=0; i<nCol; i++){
83675        sqlite3VdbeAddOp2(v, OP_Copy, aiCol[i]+1+regData, regTemp+i);
83676      }
83677
83678      /* If the parent table is the same as the child table, and we are about
83679      ** to increment the constraint-counter (i.e. this is an INSERT operation),
83680      ** then check if the row being inserted matches itself. If so, do not
83681      ** increment the constraint-counter.  */
83682      if( pTab==pFKey->pFrom && nIncr==1 ){
83683        int iJump = sqlite3VdbeCurrentAddr(v) + nCol + 1;
83684        for(i=0; i<nCol; i++){
83685          int iChild = aiCol[i]+1+regData;
83686          int iParent = pIdx->aiColumn[i]+1+regData;
83687          sqlite3VdbeAddOp3(v, OP_Ne, iChild, iJump, iParent);
83688        }
83689        sqlite3VdbeAddOp2(v, OP_Goto, 0, iOk);
83690      }
83691
83692      sqlite3VdbeAddOp3(v, OP_MakeRecord, regTemp, nCol, regRec);
83693      sqlite3VdbeChangeP4(v, -1, sqlite3IndexAffinityStr(v,pIdx), P4_TRANSIENT);
83694      sqlite3VdbeAddOp4Int(v, OP_Found, iCur, iOk, regRec, 0);
83695
83696      sqlite3ReleaseTempReg(pParse, regRec);
83697      sqlite3ReleaseTempRange(pParse, regTemp, nCol);
83698    }
83699  }
83700
83701  if( !pFKey->isDeferred && !pParse->pToplevel && !pParse->isMultiWrite ){
83702    /* Special case: If this is an INSERT statement that will insert exactly
83703    ** one row into the table, raise a constraint immediately instead of
83704    ** incrementing a counter. This is necessary as the VM code is being
83705    ** generated for will not open a statement transaction.  */
83706    assert( nIncr==1 );
83707    sqlite3HaltConstraint(
83708        pParse, OE_Abort, "foreign key constraint failed", P4_STATIC
83709    );
83710  }else{
83711    if( nIncr>0 && pFKey->isDeferred==0 ){
83712      sqlite3ParseToplevel(pParse)->mayAbort = 1;
83713    }
83714    sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, nIncr);
83715  }
83716
83717  sqlite3VdbeResolveLabel(v, iOk);
83718  sqlite3VdbeAddOp1(v, OP_Close, iCur);
83719}
83720
83721/*
83722** This function is called to generate code executed when a row is deleted
83723** from the parent table of foreign key constraint pFKey and, if pFKey is
83724** deferred, when a row is inserted into the same table. When generating
83725** code for an SQL UPDATE operation, this function may be called twice -
83726** once to "delete" the old row and once to "insert" the new row.
83727**
83728** The code generated by this function scans through the rows in the child
83729** table that correspond to the parent table row being deleted or inserted.
83730** For each child row found, one of the following actions is taken:
83731**
83732**   Operation | FK type   | Action taken
83733**   --------------------------------------------------------------------------
83734**   DELETE      immediate   Increment the "immediate constraint counter".
83735**                           Or, if the ON (UPDATE|DELETE) action is RESTRICT,
83736**                           throw a "foreign key constraint failed" exception.
83737**
83738**   INSERT      immediate   Decrement the "immediate constraint counter".
83739**
83740**   DELETE      deferred    Increment the "deferred constraint counter".
83741**                           Or, if the ON (UPDATE|DELETE) action is RESTRICT,
83742**                           throw a "foreign key constraint failed" exception.
83743**
83744**   INSERT      deferred    Decrement the "deferred constraint counter".
83745**
83746** These operations are identified in the comment at the top of this file
83747** (fkey.c) as "I.2" and "D.2".
83748*/
83749static void fkScanChildren(
83750  Parse *pParse,                  /* Parse context */
83751  SrcList *pSrc,                  /* SrcList containing the table to scan */
83752  Table *pTab,
83753  Index *pIdx,                    /* Foreign key index */
83754  FKey *pFKey,                    /* Foreign key relationship */
83755  int *aiCol,                     /* Map from pIdx cols to child table cols */
83756  int regData,                    /* Referenced table data starts here */
83757  int nIncr                       /* Amount to increment deferred counter by */
83758){
83759  sqlite3 *db = pParse->db;       /* Database handle */
83760  int i;                          /* Iterator variable */
83761  Expr *pWhere = 0;               /* WHERE clause to scan with */
83762  NameContext sNameContext;       /* Context used to resolve WHERE clause */
83763  WhereInfo *pWInfo;              /* Context used by sqlite3WhereXXX() */
83764  int iFkIfZero = 0;              /* Address of OP_FkIfZero */
83765  Vdbe *v = sqlite3GetVdbe(pParse);
83766
83767  assert( !pIdx || pIdx->pTable==pTab );
83768
83769  if( nIncr<0 ){
83770    iFkIfZero = sqlite3VdbeAddOp2(v, OP_FkIfZero, pFKey->isDeferred, 0);
83771  }
83772
83773  /* Create an Expr object representing an SQL expression like:
83774  **
83775  **   <parent-key1> = <child-key1> AND <parent-key2> = <child-key2> ...
83776  **
83777  ** The collation sequence used for the comparison should be that of
83778  ** the parent key columns. The affinity of the parent key column should
83779  ** be applied to each child key value before the comparison takes place.
83780  */
83781  for(i=0; i<pFKey->nCol; i++){
83782    Expr *pLeft;                  /* Value from parent table row */
83783    Expr *pRight;                 /* Column ref to child table */
83784    Expr *pEq;                    /* Expression (pLeft = pRight) */
83785    int iCol;                     /* Index of column in child table */
83786    const char *zCol;             /* Name of column in child table */
83787
83788    pLeft = sqlite3Expr(db, TK_REGISTER, 0);
83789    if( pLeft ){
83790      /* Set the collation sequence and affinity of the LHS of each TK_EQ
83791      ** expression to the parent key column defaults.  */
83792      if( pIdx ){
83793        Column *pCol;
83794        iCol = pIdx->aiColumn[i];
83795        pCol = &pTab->aCol[iCol];
83796        if( pTab->iPKey==iCol ) iCol = -1;
83797        pLeft->iTable = regData+iCol+1;
83798        pLeft->affinity = pCol->affinity;
83799        pLeft->pColl = sqlite3LocateCollSeq(pParse, pCol->zColl);
83800      }else{
83801        pLeft->iTable = regData;
83802        pLeft->affinity = SQLITE_AFF_INTEGER;
83803      }
83804    }
83805    iCol = aiCol ? aiCol[i] : pFKey->aCol[0].iFrom;
83806    assert( iCol>=0 );
83807    zCol = pFKey->pFrom->aCol[iCol].zName;
83808    pRight = sqlite3Expr(db, TK_ID, zCol);
83809    pEq = sqlite3PExpr(pParse, TK_EQ, pLeft, pRight, 0);
83810    pWhere = sqlite3ExprAnd(db, pWhere, pEq);
83811  }
83812
83813  /* If the child table is the same as the parent table, and this scan
83814  ** is taking place as part of a DELETE operation (operation D.2), omit the
83815  ** row being deleted from the scan by adding ($rowid != rowid) to the WHERE
83816  ** clause, where $rowid is the rowid of the row being deleted.  */
83817  if( pTab==pFKey->pFrom && nIncr>0 ){
83818    Expr *pEq;                    /* Expression (pLeft = pRight) */
83819    Expr *pLeft;                  /* Value from parent table row */
83820    Expr *pRight;                 /* Column ref to child table */
83821    pLeft = sqlite3Expr(db, TK_REGISTER, 0);
83822    pRight = sqlite3Expr(db, TK_COLUMN, 0);
83823    if( pLeft && pRight ){
83824      pLeft->iTable = regData;
83825      pLeft->affinity = SQLITE_AFF_INTEGER;
83826      pRight->iTable = pSrc->a[0].iCursor;
83827      pRight->iColumn = -1;
83828    }
83829    pEq = sqlite3PExpr(pParse, TK_NE, pLeft, pRight, 0);
83830    pWhere = sqlite3ExprAnd(db, pWhere, pEq);
83831  }
83832
83833  /* Resolve the references in the WHERE clause. */
83834  memset(&sNameContext, 0, sizeof(NameContext));
83835  sNameContext.pSrcList = pSrc;
83836  sNameContext.pParse = pParse;
83837  sqlite3ResolveExprNames(&sNameContext, pWhere);
83838
83839  /* Create VDBE to loop through the entries in pSrc that match the WHERE
83840  ** clause. If the constraint is not deferred, throw an exception for
83841  ** each row found. Otherwise, for deferred constraints, increment the
83842  ** deferred constraint counter by nIncr for each row selected.  */
83843  pWInfo = sqlite3WhereBegin(pParse, pSrc, pWhere, 0, 0);
83844  if( nIncr>0 && pFKey->isDeferred==0 ){
83845    sqlite3ParseToplevel(pParse)->mayAbort = 1;
83846  }
83847  sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, nIncr);
83848  if( pWInfo ){
83849    sqlite3WhereEnd(pWInfo);
83850  }
83851
83852  /* Clean up the WHERE clause constructed above. */
83853  sqlite3ExprDelete(db, pWhere);
83854  if( iFkIfZero ){
83855    sqlite3VdbeJumpHere(v, iFkIfZero);
83856  }
83857}
83858
83859/*
83860** This function returns a pointer to the head of a linked list of FK
83861** constraints for which table pTab is the parent table. For example,
83862** given the following schema:
83863**
83864**   CREATE TABLE t1(a PRIMARY KEY);
83865**   CREATE TABLE t2(b REFERENCES t1(a);
83866**
83867** Calling this function with table "t1" as an argument returns a pointer
83868** to the FKey structure representing the foreign key constraint on table
83869** "t2". Calling this function with "t2" as the argument would return a
83870** NULL pointer (as there are no FK constraints for which t2 is the parent
83871** table).
83872*/
83873SQLITE_PRIVATE FKey *sqlite3FkReferences(Table *pTab){
83874  int nName = sqlite3Strlen30(pTab->zName);
83875  return (FKey *)sqlite3HashFind(&pTab->pSchema->fkeyHash, pTab->zName, nName);
83876}
83877
83878/*
83879** The second argument is a Trigger structure allocated by the
83880** fkActionTrigger() routine. This function deletes the Trigger structure
83881** and all of its sub-components.
83882**
83883** The Trigger structure or any of its sub-components may be allocated from
83884** the lookaside buffer belonging to database handle dbMem.
83885*/
83886static void fkTriggerDelete(sqlite3 *dbMem, Trigger *p){
83887  if( p ){
83888    TriggerStep *pStep = p->step_list;
83889    sqlite3ExprDelete(dbMem, pStep->pWhere);
83890    sqlite3ExprListDelete(dbMem, pStep->pExprList);
83891    sqlite3SelectDelete(dbMem, pStep->pSelect);
83892    sqlite3ExprDelete(dbMem, p->pWhen);
83893    sqlite3DbFree(dbMem, p);
83894  }
83895}
83896
83897/*
83898** This function is called to generate code that runs when table pTab is
83899** being dropped from the database. The SrcList passed as the second argument
83900** to this function contains a single entry guaranteed to resolve to
83901** table pTab.
83902**
83903** Normally, no code is required. However, if either
83904**
83905**   (a) The table is the parent table of a FK constraint, or
83906**   (b) The table is the child table of a deferred FK constraint and it is
83907**       determined at runtime that there are outstanding deferred FK
83908**       constraint violations in the database,
83909**
83910** then the equivalent of "DELETE FROM <tbl>" is executed before dropping
83911** the table from the database. Triggers are disabled while running this
83912** DELETE, but foreign key actions are not.
83913*/
83914SQLITE_PRIVATE void sqlite3FkDropTable(Parse *pParse, SrcList *pName, Table *pTab){
83915  sqlite3 *db = pParse->db;
83916  if( (db->flags&SQLITE_ForeignKeys) && !IsVirtual(pTab) && !pTab->pSelect ){
83917    int iSkip = 0;
83918    Vdbe *v = sqlite3GetVdbe(pParse);
83919
83920    assert( v );                  /* VDBE has already been allocated */
83921    if( sqlite3FkReferences(pTab)==0 ){
83922      /* Search for a deferred foreign key constraint for which this table
83923      ** is the child table. If one cannot be found, return without
83924      ** generating any VDBE code. If one can be found, then jump over
83925      ** the entire DELETE if there are no outstanding deferred constraints
83926      ** when this statement is run.  */
83927      FKey *p;
83928      for(p=pTab->pFKey; p; p=p->pNextFrom){
83929        if( p->isDeferred ) break;
83930      }
83931      if( !p ) return;
83932      iSkip = sqlite3VdbeMakeLabel(v);
83933      sqlite3VdbeAddOp2(v, OP_FkIfZero, 1, iSkip);
83934    }
83935
83936    pParse->disableTriggers = 1;
83937    sqlite3DeleteFrom(pParse, sqlite3SrcListDup(db, pName, 0), 0);
83938    pParse->disableTriggers = 0;
83939
83940    /* If the DELETE has generated immediate foreign key constraint
83941    ** violations, halt the VDBE and return an error at this point, before
83942    ** any modifications to the schema are made. This is because statement
83943    ** transactions are not able to rollback schema changes.  */
83944    sqlite3VdbeAddOp2(v, OP_FkIfZero, 0, sqlite3VdbeCurrentAddr(v)+2);
83945    sqlite3HaltConstraint(
83946        pParse, OE_Abort, "foreign key constraint failed", P4_STATIC
83947    );
83948
83949    if( iSkip ){
83950      sqlite3VdbeResolveLabel(v, iSkip);
83951    }
83952  }
83953}
83954
83955/*
83956** This function is called when inserting, deleting or updating a row of
83957** table pTab to generate VDBE code to perform foreign key constraint
83958** processing for the operation.
83959**
83960** For a DELETE operation, parameter regOld is passed the index of the
83961** first register in an array of (pTab->nCol+1) registers containing the
83962** rowid of the row being deleted, followed by each of the column values
83963** of the row being deleted, from left to right. Parameter regNew is passed
83964** zero in this case.
83965**
83966** For an INSERT operation, regOld is passed zero and regNew is passed the
83967** first register of an array of (pTab->nCol+1) registers containing the new
83968** row data.
83969**
83970** For an UPDATE operation, this function is called twice. Once before
83971** the original record is deleted from the table using the calling convention
83972** described for DELETE. Then again after the original record is deleted
83973** but before the new record is inserted using the INSERT convention.
83974*/
83975SQLITE_PRIVATE void sqlite3FkCheck(
83976  Parse *pParse,                  /* Parse context */
83977  Table *pTab,                    /* Row is being deleted from this table */
83978  int regOld,                     /* Previous row data is stored here */
83979  int regNew                      /* New row data is stored here */
83980){
83981  sqlite3 *db = pParse->db;       /* Database handle */
83982  FKey *pFKey;                    /* Used to iterate through FKs */
83983  int iDb;                        /* Index of database containing pTab */
83984  const char *zDb;                /* Name of database containing pTab */
83985  int isIgnoreErrors = pParse->disableTriggers;
83986
83987  /* Exactly one of regOld and regNew should be non-zero. */
83988  assert( (regOld==0)!=(regNew==0) );
83989
83990  /* If foreign-keys are disabled, this function is a no-op. */
83991  if( (db->flags&SQLITE_ForeignKeys)==0 ) return;
83992
83993  iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
83994  zDb = db->aDb[iDb].zName;
83995
83996  /* Loop through all the foreign key constraints for which pTab is the
83997  ** child table (the table that the foreign key definition is part of).  */
83998  for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
83999    Table *pTo;                   /* Parent table of foreign key pFKey */
84000    Index *pIdx = 0;              /* Index on key columns in pTo */
84001    int *aiFree = 0;
84002    int *aiCol;
84003    int iCol;
84004    int i;
84005    int isIgnore = 0;
84006
84007    /* Find the parent table of this foreign key. Also find a unique index
84008    ** on the parent key columns in the parent table. If either of these
84009    ** schema items cannot be located, set an error in pParse and return
84010    ** early.  */
84011    if( pParse->disableTriggers ){
84012      pTo = sqlite3FindTable(db, pFKey->zTo, zDb);
84013    }else{
84014      pTo = sqlite3LocateTable(pParse, 0, pFKey->zTo, zDb);
84015    }
84016    if( !pTo || locateFkeyIndex(pParse, pTo, pFKey, &pIdx, &aiFree) ){
84017      if( !isIgnoreErrors || db->mallocFailed ) return;
84018      continue;
84019    }
84020    assert( pFKey->nCol==1 || (aiFree && pIdx) );
84021
84022    if( aiFree ){
84023      aiCol = aiFree;
84024    }else{
84025      iCol = pFKey->aCol[0].iFrom;
84026      aiCol = &iCol;
84027    }
84028    for(i=0; i<pFKey->nCol; i++){
84029      if( aiCol[i]==pTab->iPKey ){
84030        aiCol[i] = -1;
84031      }
84032#ifndef SQLITE_OMIT_AUTHORIZATION
84033      /* Request permission to read the parent key columns. If the
84034      ** authorization callback returns SQLITE_IGNORE, behave as if any
84035      ** values read from the parent table are NULL. */
84036      if( db->xAuth ){
84037        int rcauth;
84038        char *zCol = pTo->aCol[pIdx ? pIdx->aiColumn[i] : pTo->iPKey].zName;
84039        rcauth = sqlite3AuthReadCol(pParse, pTo->zName, zCol, iDb);
84040        isIgnore = (rcauth==SQLITE_IGNORE);
84041      }
84042#endif
84043    }
84044
84045    /* Take a shared-cache advisory read-lock on the parent table. Allocate
84046    ** a cursor to use to search the unique index on the parent key columns
84047    ** in the parent table.  */
84048    sqlite3TableLock(pParse, iDb, pTo->tnum, 0, pTo->zName);
84049    pParse->nTab++;
84050
84051    if( regOld!=0 ){
84052      /* A row is being removed from the child table. Search for the parent.
84053      ** If the parent does not exist, removing the child row resolves an
84054      ** outstanding foreign key constraint violation. */
84055      fkLookupParent(pParse, iDb, pTo, pIdx, pFKey, aiCol, regOld, -1,isIgnore);
84056    }
84057    if( regNew!=0 ){
84058      /* A row is being added to the child table. If a parent row cannot
84059      ** be found, adding the child row has violated the FK constraint. */
84060      fkLookupParent(pParse, iDb, pTo, pIdx, pFKey, aiCol, regNew, +1,isIgnore);
84061    }
84062
84063    sqlite3DbFree(db, aiFree);
84064  }
84065
84066  /* Loop through all the foreign key constraints that refer to this table */
84067  for(pFKey = sqlite3FkReferences(pTab); pFKey; pFKey=pFKey->pNextTo){
84068    Index *pIdx = 0;              /* Foreign key index for pFKey */
84069    SrcList *pSrc;
84070    int *aiCol = 0;
84071
84072    if( !pFKey->isDeferred && !pParse->pToplevel && !pParse->isMultiWrite ){
84073      assert( regOld==0 && regNew!=0 );
84074      /* Inserting a single row into a parent table cannot cause an immediate
84075      ** foreign key violation. So do nothing in this case.  */
84076      continue;
84077    }
84078
84079    if( locateFkeyIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ){
84080      if( !isIgnoreErrors || db->mallocFailed ) return;
84081      continue;
84082    }
84083    assert( aiCol || pFKey->nCol==1 );
84084
84085    /* Create a SrcList structure containing a single table (the table
84086    ** the foreign key that refers to this table is attached to). This
84087    ** is required for the sqlite3WhereXXX() interface.  */
84088    pSrc = sqlite3SrcListAppend(db, 0, 0, 0);
84089    if( pSrc ){
84090      struct SrcList_item *pItem = pSrc->a;
84091      pItem->pTab = pFKey->pFrom;
84092      pItem->zName = pFKey->pFrom->zName;
84093      pItem->pTab->nRef++;
84094      pItem->iCursor = pParse->nTab++;
84095
84096      if( regNew!=0 ){
84097        fkScanChildren(pParse, pSrc, pTab, pIdx, pFKey, aiCol, regNew, -1);
84098      }
84099      if( regOld!=0 ){
84100        /* If there is a RESTRICT action configured for the current operation
84101        ** on the parent table of this FK, then throw an exception
84102        ** immediately if the FK constraint is violated, even if this is a
84103        ** deferred trigger. That's what RESTRICT means. To defer checking
84104        ** the constraint, the FK should specify NO ACTION (represented
84105        ** using OE_None). NO ACTION is the default.  */
84106        fkScanChildren(pParse, pSrc, pTab, pIdx, pFKey, aiCol, regOld, 1);
84107      }
84108      pItem->zName = 0;
84109      sqlite3SrcListDelete(db, pSrc);
84110    }
84111    sqlite3DbFree(db, aiCol);
84112  }
84113}
84114
84115#define COLUMN_MASK(x) (((x)>31) ? 0xffffffff : ((u32)1<<(x)))
84116
84117/*
84118** This function is called before generating code to update or delete a
84119** row contained in table pTab.
84120*/
84121SQLITE_PRIVATE u32 sqlite3FkOldmask(
84122  Parse *pParse,                  /* Parse context */
84123  Table *pTab                     /* Table being modified */
84124){
84125  u32 mask = 0;
84126  if( pParse->db->flags&SQLITE_ForeignKeys ){
84127    FKey *p;
84128    int i;
84129    for(p=pTab->pFKey; p; p=p->pNextFrom){
84130      for(i=0; i<p->nCol; i++) mask |= COLUMN_MASK(p->aCol[i].iFrom);
84131    }
84132    for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
84133      Index *pIdx = 0;
84134      locateFkeyIndex(pParse, pTab, p, &pIdx, 0);
84135      if( pIdx ){
84136        for(i=0; i<pIdx->nColumn; i++) mask |= COLUMN_MASK(pIdx->aiColumn[i]);
84137      }
84138    }
84139  }
84140  return mask;
84141}
84142
84143/*
84144** This function is called before generating code to update or delete a
84145** row contained in table pTab. If the operation is a DELETE, then
84146** parameter aChange is passed a NULL value. For an UPDATE, aChange points
84147** to an array of size N, where N is the number of columns in table pTab.
84148** If the i'th column is not modified by the UPDATE, then the corresponding
84149** entry in the aChange[] array is set to -1. If the column is modified,
84150** the value is 0 or greater. Parameter chngRowid is set to true if the
84151** UPDATE statement modifies the rowid fields of the table.
84152**
84153** If any foreign key processing will be required, this function returns
84154** true. If there is no foreign key related processing, this function
84155** returns false.
84156*/
84157SQLITE_PRIVATE int sqlite3FkRequired(
84158  Parse *pParse,                  /* Parse context */
84159  Table *pTab,                    /* Table being modified */
84160  int *aChange,                   /* Non-NULL for UPDATE operations */
84161  int chngRowid                   /* True for UPDATE that affects rowid */
84162){
84163  if( pParse->db->flags&SQLITE_ForeignKeys ){
84164    if( !aChange ){
84165      /* A DELETE operation. Foreign key processing is required if the
84166      ** table in question is either the child or parent table for any
84167      ** foreign key constraint.  */
84168      return (sqlite3FkReferences(pTab) || pTab->pFKey);
84169    }else{
84170      /* This is an UPDATE. Foreign key processing is only required if the
84171      ** operation modifies one or more child or parent key columns. */
84172      int i;
84173      FKey *p;
84174
84175      /* Check if any child key columns are being modified. */
84176      for(p=pTab->pFKey; p; p=p->pNextFrom){
84177        for(i=0; i<p->nCol; i++){
84178          int iChildKey = p->aCol[i].iFrom;
84179          if( aChange[iChildKey]>=0 ) return 1;
84180          if( iChildKey==pTab->iPKey && chngRowid ) return 1;
84181        }
84182      }
84183
84184      /* Check if any parent key columns are being modified. */
84185      for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
84186        for(i=0; i<p->nCol; i++){
84187          char *zKey = p->aCol[i].zCol;
84188          int iKey;
84189          for(iKey=0; iKey<pTab->nCol; iKey++){
84190            Column *pCol = &pTab->aCol[iKey];
84191            if( (zKey ? !sqlite3StrICmp(pCol->zName, zKey) : pCol->isPrimKey) ){
84192              if( aChange[iKey]>=0 ) return 1;
84193              if( iKey==pTab->iPKey && chngRowid ) return 1;
84194            }
84195          }
84196        }
84197      }
84198    }
84199  }
84200  return 0;
84201}
84202
84203/*
84204** This function is called when an UPDATE or DELETE operation is being
84205** compiled on table pTab, which is the parent table of foreign-key pFKey.
84206** If the current operation is an UPDATE, then the pChanges parameter is
84207** passed a pointer to the list of columns being modified. If it is a
84208** DELETE, pChanges is passed a NULL pointer.
84209**
84210** It returns a pointer to a Trigger structure containing a trigger
84211** equivalent to the ON UPDATE or ON DELETE action specified by pFKey.
84212** If the action is "NO ACTION" or "RESTRICT", then a NULL pointer is
84213** returned (these actions require no special handling by the triggers
84214** sub-system, code for them is created by fkScanChildren()).
84215**
84216** For example, if pFKey is the foreign key and pTab is table "p" in
84217** the following schema:
84218**
84219**   CREATE TABLE p(pk PRIMARY KEY);
84220**   CREATE TABLE c(ck REFERENCES p ON DELETE CASCADE);
84221**
84222** then the returned trigger structure is equivalent to:
84223**
84224**   CREATE TRIGGER ... DELETE ON p BEGIN
84225**     DELETE FROM c WHERE ck = old.pk;
84226**   END;
84227**
84228** The returned pointer is cached as part of the foreign key object. It
84229** is eventually freed along with the rest of the foreign key object by
84230** sqlite3FkDelete().
84231*/
84232static Trigger *fkActionTrigger(
84233  Parse *pParse,                  /* Parse context */
84234  Table *pTab,                    /* Table being updated or deleted from */
84235  FKey *pFKey,                    /* Foreign key to get action for */
84236  ExprList *pChanges              /* Change-list for UPDATE, NULL for DELETE */
84237){
84238  sqlite3 *db = pParse->db;       /* Database handle */
84239  int action;                     /* One of OE_None, OE_Cascade etc. */
84240  Trigger *pTrigger;              /* Trigger definition to return */
84241  int iAction = (pChanges!=0);    /* 1 for UPDATE, 0 for DELETE */
84242
84243  action = pFKey->aAction[iAction];
84244  pTrigger = pFKey->apTrigger[iAction];
84245
84246  if( action!=OE_None && !pTrigger ){
84247    u8 enableLookaside;           /* Copy of db->lookaside.bEnabled */
84248    char const *zFrom;            /* Name of child table */
84249    int nFrom;                    /* Length in bytes of zFrom */
84250    Index *pIdx = 0;              /* Parent key index for this FK */
84251    int *aiCol = 0;               /* child table cols -> parent key cols */
84252    TriggerStep *pStep = 0;        /* First (only) step of trigger program */
84253    Expr *pWhere = 0;             /* WHERE clause of trigger step */
84254    ExprList *pList = 0;          /* Changes list if ON UPDATE CASCADE */
84255    Select *pSelect = 0;          /* If RESTRICT, "SELECT RAISE(...)" */
84256    int i;                        /* Iterator variable */
84257    Expr *pWhen = 0;              /* WHEN clause for the trigger */
84258
84259    if( locateFkeyIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ) return 0;
84260    assert( aiCol || pFKey->nCol==1 );
84261
84262    for(i=0; i<pFKey->nCol; i++){
84263      Token tOld = { "old", 3 };  /* Literal "old" token */
84264      Token tNew = { "new", 3 };  /* Literal "new" token */
84265      Token tFromCol;             /* Name of column in child table */
84266      Token tToCol;               /* Name of column in parent table */
84267      int iFromCol;               /* Idx of column in child table */
84268      Expr *pEq;                  /* tFromCol = OLD.tToCol */
84269
84270      iFromCol = aiCol ? aiCol[i] : pFKey->aCol[0].iFrom;
84271      assert( iFromCol>=0 );
84272      tToCol.z = pIdx ? pTab->aCol[pIdx->aiColumn[i]].zName : "oid";
84273      tFromCol.z = pFKey->pFrom->aCol[iFromCol].zName;
84274
84275      tToCol.n = sqlite3Strlen30(tToCol.z);
84276      tFromCol.n = sqlite3Strlen30(tFromCol.z);
84277
84278      /* Create the expression "OLD.zToCol = zFromCol". It is important
84279      ** that the "OLD.zToCol" term is on the LHS of the = operator, so
84280      ** that the affinity and collation sequence associated with the
84281      ** parent table are used for the comparison. */
84282      pEq = sqlite3PExpr(pParse, TK_EQ,
84283          sqlite3PExpr(pParse, TK_DOT,
84284            sqlite3PExpr(pParse, TK_ID, 0, 0, &tOld),
84285            sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol)
84286          , 0),
84287          sqlite3PExpr(pParse, TK_ID, 0, 0, &tFromCol)
84288      , 0);
84289      pWhere = sqlite3ExprAnd(db, pWhere, pEq);
84290
84291      /* For ON UPDATE, construct the next term of the WHEN clause.
84292      ** The final WHEN clause will be like this:
84293      **
84294      **    WHEN NOT(old.col1 IS new.col1 AND ... AND old.colN IS new.colN)
84295      */
84296      if( pChanges ){
84297        pEq = sqlite3PExpr(pParse, TK_IS,
84298            sqlite3PExpr(pParse, TK_DOT,
84299              sqlite3PExpr(pParse, TK_ID, 0, 0, &tOld),
84300              sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol),
84301              0),
84302            sqlite3PExpr(pParse, TK_DOT,
84303              sqlite3PExpr(pParse, TK_ID, 0, 0, &tNew),
84304              sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol),
84305              0),
84306            0);
84307        pWhen = sqlite3ExprAnd(db, pWhen, pEq);
84308      }
84309
84310      if( action!=OE_Restrict && (action!=OE_Cascade || pChanges) ){
84311        Expr *pNew;
84312        if( action==OE_Cascade ){
84313          pNew = sqlite3PExpr(pParse, TK_DOT,
84314            sqlite3PExpr(pParse, TK_ID, 0, 0, &tNew),
84315            sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol)
84316          , 0);
84317        }else if( action==OE_SetDflt ){
84318          Expr *pDflt = pFKey->pFrom->aCol[iFromCol].pDflt;
84319          if( pDflt ){
84320            pNew = sqlite3ExprDup(db, pDflt, 0);
84321          }else{
84322            pNew = sqlite3PExpr(pParse, TK_NULL, 0, 0, 0);
84323          }
84324        }else{
84325          pNew = sqlite3PExpr(pParse, TK_NULL, 0, 0, 0);
84326        }
84327        pList = sqlite3ExprListAppend(pParse, pList, pNew);
84328        sqlite3ExprListSetName(pParse, pList, &tFromCol, 0);
84329      }
84330    }
84331    sqlite3DbFree(db, aiCol);
84332
84333    zFrom = pFKey->pFrom->zName;
84334    nFrom = sqlite3Strlen30(zFrom);
84335
84336    if( action==OE_Restrict ){
84337      Token tFrom;
84338      Expr *pRaise;
84339
84340      tFrom.z = zFrom;
84341      tFrom.n = nFrom;
84342      pRaise = sqlite3Expr(db, TK_RAISE, "foreign key constraint failed");
84343      if( pRaise ){
84344        pRaise->affinity = OE_Abort;
84345      }
84346      pSelect = sqlite3SelectNew(pParse,
84347          sqlite3ExprListAppend(pParse, 0, pRaise),
84348          sqlite3SrcListAppend(db, 0, &tFrom, 0),
84349          pWhere,
84350          0, 0, 0, 0, 0, 0
84351      );
84352      pWhere = 0;
84353    }
84354
84355    /* Disable lookaside memory allocation */
84356    enableLookaside = db->lookaside.bEnabled;
84357    db->lookaside.bEnabled = 0;
84358
84359    pTrigger = (Trigger *)sqlite3DbMallocZero(db,
84360        sizeof(Trigger) +         /* struct Trigger */
84361        sizeof(TriggerStep) +     /* Single step in trigger program */
84362        nFrom + 1                 /* Space for pStep->target.z */
84363    );
84364    if( pTrigger ){
84365      pStep = pTrigger->step_list = (TriggerStep *)&pTrigger[1];
84366      pStep->target.z = (char *)&pStep[1];
84367      pStep->target.n = nFrom;
84368      memcpy((char *)pStep->target.z, zFrom, nFrom);
84369
84370      pStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
84371      pStep->pExprList = sqlite3ExprListDup(db, pList, EXPRDUP_REDUCE);
84372      pStep->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
84373      if( pWhen ){
84374        pWhen = sqlite3PExpr(pParse, TK_NOT, pWhen, 0, 0);
84375        pTrigger->pWhen = sqlite3ExprDup(db, pWhen, EXPRDUP_REDUCE);
84376      }
84377    }
84378
84379    /* Re-enable the lookaside buffer, if it was disabled earlier. */
84380    db->lookaside.bEnabled = enableLookaside;
84381
84382    sqlite3ExprDelete(db, pWhere);
84383    sqlite3ExprDelete(db, pWhen);
84384    sqlite3ExprListDelete(db, pList);
84385    sqlite3SelectDelete(db, pSelect);
84386    if( db->mallocFailed==1 ){
84387      fkTriggerDelete(db, pTrigger);
84388      return 0;
84389    }
84390
84391    switch( action ){
84392      case OE_Restrict:
84393        pStep->op = TK_SELECT;
84394        break;
84395      case OE_Cascade:
84396        if( !pChanges ){
84397          pStep->op = TK_DELETE;
84398          break;
84399        }
84400      default:
84401        pStep->op = TK_UPDATE;
84402    }
84403    pStep->pTrig = pTrigger;
84404    pTrigger->pSchema = pTab->pSchema;
84405    pTrigger->pTabSchema = pTab->pSchema;
84406    pFKey->apTrigger[iAction] = pTrigger;
84407    pTrigger->op = (pChanges ? TK_UPDATE : TK_DELETE);
84408  }
84409
84410  return pTrigger;
84411}
84412
84413/*
84414** This function is called when deleting or updating a row to implement
84415** any required CASCADE, SET NULL or SET DEFAULT actions.
84416*/
84417SQLITE_PRIVATE void sqlite3FkActions(
84418  Parse *pParse,                  /* Parse context */
84419  Table *pTab,                    /* Table being updated or deleted from */
84420  ExprList *pChanges,             /* Change-list for UPDATE, NULL for DELETE */
84421  int regOld                      /* Address of array containing old row */
84422){
84423  /* If foreign-key support is enabled, iterate through all FKs that
84424  ** refer to table pTab. If there is an action associated with the FK
84425  ** for this operation (either update or delete), invoke the associated
84426  ** trigger sub-program.  */
84427  if( pParse->db->flags&SQLITE_ForeignKeys ){
84428    FKey *pFKey;                  /* Iterator variable */
84429    for(pFKey = sqlite3FkReferences(pTab); pFKey; pFKey=pFKey->pNextTo){
84430      Trigger *pAction = fkActionTrigger(pParse, pTab, pFKey, pChanges);
84431      if( pAction ){
84432        sqlite3CodeRowTriggerDirect(pParse, pAction, pTab, regOld, OE_Abort, 0);
84433      }
84434    }
84435  }
84436}
84437
84438#endif /* ifndef SQLITE_OMIT_TRIGGER */
84439
84440/*
84441** Free all memory associated with foreign key definitions attached to
84442** table pTab. Remove the deleted foreign keys from the Schema.fkeyHash
84443** hash table.
84444*/
84445SQLITE_PRIVATE void sqlite3FkDelete(sqlite3 *db, Table *pTab){
84446  FKey *pFKey;                    /* Iterator variable */
84447  FKey *pNext;                    /* Copy of pFKey->pNextFrom */
84448
84449  assert( db==0 || sqlite3SchemaMutexHeld(db, 0, pTab->pSchema) );
84450  for(pFKey=pTab->pFKey; pFKey; pFKey=pNext){
84451
84452    /* Remove the FK from the fkeyHash hash table. */
84453    if( !db || db->pnBytesFreed==0 ){
84454      if( pFKey->pPrevTo ){
84455        pFKey->pPrevTo->pNextTo = pFKey->pNextTo;
84456      }else{
84457        void *p = (void *)pFKey->pNextTo;
84458        const char *z = (p ? pFKey->pNextTo->zTo : pFKey->zTo);
84459        sqlite3HashInsert(&pTab->pSchema->fkeyHash, z, sqlite3Strlen30(z), p);
84460      }
84461      if( pFKey->pNextTo ){
84462        pFKey->pNextTo->pPrevTo = pFKey->pPrevTo;
84463      }
84464    }
84465
84466    /* EV: R-30323-21917 Each foreign key constraint in SQLite is
84467    ** classified as either immediate or deferred.
84468    */
84469    assert( pFKey->isDeferred==0 || pFKey->isDeferred==1 );
84470
84471    /* Delete any triggers created to implement actions for this FK. */
84472#ifndef SQLITE_OMIT_TRIGGER
84473    fkTriggerDelete(db, pFKey->apTrigger[0]);
84474    fkTriggerDelete(db, pFKey->apTrigger[1]);
84475#endif
84476
84477    pNext = pFKey->pNextFrom;
84478    sqlite3DbFree(db, pFKey);
84479  }
84480}
84481#endif /* ifndef SQLITE_OMIT_FOREIGN_KEY */
84482
84483/************** End of fkey.c ************************************************/
84484/************** Begin file insert.c ******************************************/
84485/*
84486** 2001 September 15
84487**
84488** The author disclaims copyright to this source code.  In place of
84489** a legal notice, here is a blessing:
84490**
84491**    May you do good and not evil.
84492**    May you find forgiveness for yourself and forgive others.
84493**    May you share freely, never taking more than you give.
84494**
84495*************************************************************************
84496** This file contains C code routines that are called by the parser
84497** to handle INSERT statements in SQLite.
84498*/
84499
84500/*
84501** Generate code that will open a table for reading.
84502*/
84503SQLITE_PRIVATE void sqlite3OpenTable(
84504  Parse *p,       /* Generate code into this VDBE */
84505  int iCur,       /* The cursor number of the table */
84506  int iDb,        /* The database index in sqlite3.aDb[] */
84507  Table *pTab,    /* The table to be opened */
84508  int opcode      /* OP_OpenRead or OP_OpenWrite */
84509){
84510  Vdbe *v;
84511  if( IsVirtual(pTab) ) return;
84512  v = sqlite3GetVdbe(p);
84513  assert( opcode==OP_OpenWrite || opcode==OP_OpenRead );
84514  sqlite3TableLock(p, iDb, pTab->tnum, (opcode==OP_OpenWrite)?1:0, pTab->zName);
84515  sqlite3VdbeAddOp3(v, opcode, iCur, pTab->tnum, iDb);
84516  sqlite3VdbeChangeP4(v, -1, SQLITE_INT_TO_PTR(pTab->nCol), P4_INT32);
84517  VdbeComment((v, "%s", pTab->zName));
84518}
84519
84520/*
84521** Return a pointer to the column affinity string associated with index
84522** pIdx. A column affinity string has one character for each column in
84523** the table, according to the affinity of the column:
84524**
84525**  Character      Column affinity
84526**  ------------------------------
84527**  'a'            TEXT
84528**  'b'            NONE
84529**  'c'            NUMERIC
84530**  'd'            INTEGER
84531**  'e'            REAL
84532**
84533** An extra 'b' is appended to the end of the string to cover the
84534** rowid that appears as the last column in every index.
84535**
84536** Memory for the buffer containing the column index affinity string
84537** is managed along with the rest of the Index structure. It will be
84538** released when sqlite3DeleteIndex() is called.
84539*/
84540SQLITE_PRIVATE const char *sqlite3IndexAffinityStr(Vdbe *v, Index *pIdx){
84541  if( !pIdx->zColAff ){
84542    /* The first time a column affinity string for a particular index is
84543    ** required, it is allocated and populated here. It is then stored as
84544    ** a member of the Index structure for subsequent use.
84545    **
84546    ** The column affinity string will eventually be deleted by
84547    ** sqliteDeleteIndex() when the Index structure itself is cleaned
84548    ** up.
84549    */
84550    int n;
84551    Table *pTab = pIdx->pTable;
84552    sqlite3 *db = sqlite3VdbeDb(v);
84553    pIdx->zColAff = (char *)sqlite3DbMallocRaw(0, pIdx->nColumn+2);
84554    if( !pIdx->zColAff ){
84555      db->mallocFailed = 1;
84556      return 0;
84557    }
84558    for(n=0; n<pIdx->nColumn; n++){
84559      pIdx->zColAff[n] = pTab->aCol[pIdx->aiColumn[n]].affinity;
84560    }
84561    pIdx->zColAff[n++] = SQLITE_AFF_NONE;
84562    pIdx->zColAff[n] = 0;
84563  }
84564
84565  return pIdx->zColAff;
84566}
84567
84568/*
84569** Set P4 of the most recently inserted opcode to a column affinity
84570** string for table pTab. A column affinity string has one character
84571** for each column indexed by the index, according to the affinity of the
84572** column:
84573**
84574**  Character      Column affinity
84575**  ------------------------------
84576**  'a'            TEXT
84577**  'b'            NONE
84578**  'c'            NUMERIC
84579**  'd'            INTEGER
84580**  'e'            REAL
84581*/
84582SQLITE_PRIVATE void sqlite3TableAffinityStr(Vdbe *v, Table *pTab){
84583  /* The first time a column affinity string for a particular table
84584  ** is required, it is allocated and populated here. It is then
84585  ** stored as a member of the Table structure for subsequent use.
84586  **
84587  ** The column affinity string will eventually be deleted by
84588  ** sqlite3DeleteTable() when the Table structure itself is cleaned up.
84589  */
84590  if( !pTab->zColAff ){
84591    char *zColAff;
84592    int i;
84593    sqlite3 *db = sqlite3VdbeDb(v);
84594
84595    zColAff = (char *)sqlite3DbMallocRaw(0, pTab->nCol+1);
84596    if( !zColAff ){
84597      db->mallocFailed = 1;
84598      return;
84599    }
84600
84601    for(i=0; i<pTab->nCol; i++){
84602      zColAff[i] = pTab->aCol[i].affinity;
84603    }
84604    zColAff[pTab->nCol] = '\0';
84605
84606    pTab->zColAff = zColAff;
84607  }
84608
84609  sqlite3VdbeChangeP4(v, -1, pTab->zColAff, P4_TRANSIENT);
84610}
84611
84612/*
84613** Return non-zero if the table pTab in database iDb or any of its indices
84614** have been opened at any point in the VDBE program beginning at location
84615** iStartAddr throught the end of the program.  This is used to see if
84616** a statement of the form  "INSERT INTO <iDb, pTab> SELECT ..." can
84617** run without using temporary table for the results of the SELECT.
84618*/
84619static int readsTable(Parse *p, int iStartAddr, int iDb, Table *pTab){
84620  Vdbe *v = sqlite3GetVdbe(p);
84621  int i;
84622  int iEnd = sqlite3VdbeCurrentAddr(v);
84623#ifndef SQLITE_OMIT_VIRTUALTABLE
84624  VTable *pVTab = IsVirtual(pTab) ? sqlite3GetVTable(p->db, pTab) : 0;
84625#endif
84626
84627  for(i=iStartAddr; i<iEnd; i++){
84628    VdbeOp *pOp = sqlite3VdbeGetOp(v, i);
84629    assert( pOp!=0 );
84630    if( pOp->opcode==OP_OpenRead && pOp->p3==iDb ){
84631      Index *pIndex;
84632      int tnum = pOp->p2;
84633      if( tnum==pTab->tnum ){
84634        return 1;
84635      }
84636      for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
84637        if( tnum==pIndex->tnum ){
84638          return 1;
84639        }
84640      }
84641    }
84642#ifndef SQLITE_OMIT_VIRTUALTABLE
84643    if( pOp->opcode==OP_VOpen && pOp->p4.pVtab==pVTab ){
84644      assert( pOp->p4.pVtab!=0 );
84645      assert( pOp->p4type==P4_VTAB );
84646      return 1;
84647    }
84648#endif
84649  }
84650  return 0;
84651}
84652
84653#ifndef SQLITE_OMIT_AUTOINCREMENT
84654/*
84655** Locate or create an AutoincInfo structure associated with table pTab
84656** which is in database iDb.  Return the register number for the register
84657** that holds the maximum rowid.
84658**
84659** There is at most one AutoincInfo structure per table even if the
84660** same table is autoincremented multiple times due to inserts within
84661** triggers.  A new AutoincInfo structure is created if this is the
84662** first use of table pTab.  On 2nd and subsequent uses, the original
84663** AutoincInfo structure is used.
84664**
84665** Three memory locations are allocated:
84666**
84667**   (1)  Register to hold the name of the pTab table.
84668**   (2)  Register to hold the maximum ROWID of pTab.
84669**   (3)  Register to hold the rowid in sqlite_sequence of pTab
84670**
84671** The 2nd register is the one that is returned.  That is all the
84672** insert routine needs to know about.
84673*/
84674static int autoIncBegin(
84675  Parse *pParse,      /* Parsing context */
84676  int iDb,            /* Index of the database holding pTab */
84677  Table *pTab         /* The table we are writing to */
84678){
84679  int memId = 0;      /* Register holding maximum rowid */
84680  if( pTab->tabFlags & TF_Autoincrement ){
84681    Parse *pToplevel = sqlite3ParseToplevel(pParse);
84682    AutoincInfo *pInfo;
84683
84684    pInfo = pToplevel->pAinc;
84685    while( pInfo && pInfo->pTab!=pTab ){ pInfo = pInfo->pNext; }
84686    if( pInfo==0 ){
84687      pInfo = sqlite3DbMallocRaw(pParse->db, sizeof(*pInfo));
84688      if( pInfo==0 ) return 0;
84689      pInfo->pNext = pToplevel->pAinc;
84690      pToplevel->pAinc = pInfo;
84691      pInfo->pTab = pTab;
84692      pInfo->iDb = iDb;
84693      pToplevel->nMem++;                  /* Register to hold name of table */
84694      pInfo->regCtr = ++pToplevel->nMem;  /* Max rowid register */
84695      pToplevel->nMem++;                  /* Rowid in sqlite_sequence */
84696    }
84697    memId = pInfo->regCtr;
84698  }
84699  return memId;
84700}
84701
84702/*
84703** This routine generates code that will initialize all of the
84704** register used by the autoincrement tracker.
84705*/
84706SQLITE_PRIVATE void sqlite3AutoincrementBegin(Parse *pParse){
84707  AutoincInfo *p;            /* Information about an AUTOINCREMENT */
84708  sqlite3 *db = pParse->db;  /* The database connection */
84709  Db *pDb;                   /* Database only autoinc table */
84710  int memId;                 /* Register holding max rowid */
84711  int addr;                  /* A VDBE address */
84712  Vdbe *v = pParse->pVdbe;   /* VDBE under construction */
84713
84714  /* This routine is never called during trigger-generation.  It is
84715  ** only called from the top-level */
84716  assert( pParse->pTriggerTab==0 );
84717  assert( pParse==sqlite3ParseToplevel(pParse) );
84718
84719  assert( v );   /* We failed long ago if this is not so */
84720  for(p = pParse->pAinc; p; p = p->pNext){
84721    pDb = &db->aDb[p->iDb];
84722    memId = p->regCtr;
84723    assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) );
84724    sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenRead);
84725    addr = sqlite3VdbeCurrentAddr(v);
84726    sqlite3VdbeAddOp4(v, OP_String8, 0, memId-1, 0, p->pTab->zName, 0);
84727    sqlite3VdbeAddOp2(v, OP_Rewind, 0, addr+9);
84728    sqlite3VdbeAddOp3(v, OP_Column, 0, 0, memId);
84729    sqlite3VdbeAddOp3(v, OP_Ne, memId-1, addr+7, memId);
84730    sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);
84731    sqlite3VdbeAddOp2(v, OP_Rowid, 0, memId+1);
84732    sqlite3VdbeAddOp3(v, OP_Column, 0, 1, memId);
84733    sqlite3VdbeAddOp2(v, OP_Goto, 0, addr+9);
84734    sqlite3VdbeAddOp2(v, OP_Next, 0, addr+2);
84735    sqlite3VdbeAddOp2(v, OP_Integer, 0, memId);
84736    sqlite3VdbeAddOp0(v, OP_Close);
84737  }
84738}
84739
84740/*
84741** Update the maximum rowid for an autoincrement calculation.
84742**
84743** This routine should be called when the top of the stack holds a
84744** new rowid that is about to be inserted.  If that new rowid is
84745** larger than the maximum rowid in the memId memory cell, then the
84746** memory cell is updated.  The stack is unchanged.
84747*/
84748static void autoIncStep(Parse *pParse, int memId, int regRowid){
84749  if( memId>0 ){
84750    sqlite3VdbeAddOp2(pParse->pVdbe, OP_MemMax, memId, regRowid);
84751  }
84752}
84753
84754/*
84755** This routine generates the code needed to write autoincrement
84756** maximum rowid values back into the sqlite_sequence register.
84757** Every statement that might do an INSERT into an autoincrement
84758** table (either directly or through triggers) needs to call this
84759** routine just before the "exit" code.
84760*/
84761SQLITE_PRIVATE void sqlite3AutoincrementEnd(Parse *pParse){
84762  AutoincInfo *p;
84763  Vdbe *v = pParse->pVdbe;
84764  sqlite3 *db = pParse->db;
84765
84766  assert( v );
84767  for(p = pParse->pAinc; p; p = p->pNext){
84768    Db *pDb = &db->aDb[p->iDb];
84769    int j1, j2, j3, j4, j5;
84770    int iRec;
84771    int memId = p->regCtr;
84772
84773    iRec = sqlite3GetTempReg(pParse);
84774    assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) );
84775    sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenWrite);
84776    j1 = sqlite3VdbeAddOp1(v, OP_NotNull, memId+1);
84777    j2 = sqlite3VdbeAddOp0(v, OP_Rewind);
84778    j3 = sqlite3VdbeAddOp3(v, OP_Column, 0, 0, iRec);
84779    j4 = sqlite3VdbeAddOp3(v, OP_Eq, memId-1, 0, iRec);
84780    sqlite3VdbeAddOp2(v, OP_Next, 0, j3);
84781    sqlite3VdbeJumpHere(v, j2);
84782    sqlite3VdbeAddOp2(v, OP_NewRowid, 0, memId+1);
84783    j5 = sqlite3VdbeAddOp0(v, OP_Goto);
84784    sqlite3VdbeJumpHere(v, j4);
84785    sqlite3VdbeAddOp2(v, OP_Rowid, 0, memId+1);
84786    sqlite3VdbeJumpHere(v, j1);
84787    sqlite3VdbeJumpHere(v, j5);
84788    sqlite3VdbeAddOp3(v, OP_MakeRecord, memId-1, 2, iRec);
84789    sqlite3VdbeAddOp3(v, OP_Insert, 0, iRec, memId+1);
84790    sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
84791    sqlite3VdbeAddOp0(v, OP_Close);
84792    sqlite3ReleaseTempReg(pParse, iRec);
84793  }
84794}
84795#else
84796/*
84797** If SQLITE_OMIT_AUTOINCREMENT is defined, then the three routines
84798** above are all no-ops
84799*/
84800# define autoIncBegin(A,B,C) (0)
84801# define autoIncStep(A,B,C)
84802#endif /* SQLITE_OMIT_AUTOINCREMENT */
84803
84804
84805/* Forward declaration */
84806static int xferOptimization(
84807  Parse *pParse,        /* Parser context */
84808  Table *pDest,         /* The table we are inserting into */
84809  Select *pSelect,      /* A SELECT statement to use as the data source */
84810  int onError,          /* How to handle constraint errors */
84811  int iDbDest           /* The database of pDest */
84812);
84813
84814/*
84815** This routine is call to handle SQL of the following forms:
84816**
84817**    insert into TABLE (IDLIST) values(EXPRLIST)
84818**    insert into TABLE (IDLIST) select
84819**
84820** The IDLIST following the table name is always optional.  If omitted,
84821** then a list of all columns for the table is substituted.  The IDLIST
84822** appears in the pColumn parameter.  pColumn is NULL if IDLIST is omitted.
84823**
84824** The pList parameter holds EXPRLIST in the first form of the INSERT
84825** statement above, and pSelect is NULL.  For the second form, pList is
84826** NULL and pSelect is a pointer to the select statement used to generate
84827** data for the insert.
84828**
84829** The code generated follows one of four templates.  For a simple
84830** select with data coming from a VALUES clause, the code executes
84831** once straight down through.  Pseudo-code follows (we call this
84832** the "1st template"):
84833**
84834**         open write cursor to <table> and its indices
84835**         puts VALUES clause expressions onto the stack
84836**         write the resulting record into <table>
84837**         cleanup
84838**
84839** The three remaining templates assume the statement is of the form
84840**
84841**   INSERT INTO <table> SELECT ...
84842**
84843** If the SELECT clause is of the restricted form "SELECT * FROM <table2>" -
84844** in other words if the SELECT pulls all columns from a single table
84845** and there is no WHERE or LIMIT or GROUP BY or ORDER BY clauses, and
84846** if <table2> and <table1> are distinct tables but have identical
84847** schemas, including all the same indices, then a special optimization
84848** is invoked that copies raw records from <table2> over to <table1>.
84849** See the xferOptimization() function for the implementation of this
84850** template.  This is the 2nd template.
84851**
84852**         open a write cursor to <table>
84853**         open read cursor on <table2>
84854**         transfer all records in <table2> over to <table>
84855**         close cursors
84856**         foreach index on <table>
84857**           open a write cursor on the <table> index
84858**           open a read cursor on the corresponding <table2> index
84859**           transfer all records from the read to the write cursors
84860**           close cursors
84861**         end foreach
84862**
84863** The 3rd template is for when the second template does not apply
84864** and the SELECT clause does not read from <table> at any time.
84865** The generated code follows this template:
84866**
84867**         EOF <- 0
84868**         X <- A
84869**         goto B
84870**      A: setup for the SELECT
84871**         loop over the rows in the SELECT
84872**           load values into registers R..R+n
84873**           yield X
84874**         end loop
84875**         cleanup after the SELECT
84876**         EOF <- 1
84877**         yield X
84878**         goto A
84879**      B: open write cursor to <table> and its indices
84880**      C: yield X
84881**         if EOF goto D
84882**         insert the select result into <table> from R..R+n
84883**         goto C
84884**      D: cleanup
84885**
84886** The 4th template is used if the insert statement takes its
84887** values from a SELECT but the data is being inserted into a table
84888** that is also read as part of the SELECT.  In the third form,
84889** we have to use a intermediate table to store the results of
84890** the select.  The template is like this:
84891**
84892**         EOF <- 0
84893**         X <- A
84894**         goto B
84895**      A: setup for the SELECT
84896**         loop over the tables in the SELECT
84897**           load value into register R..R+n
84898**           yield X
84899**         end loop
84900**         cleanup after the SELECT
84901**         EOF <- 1
84902**         yield X
84903**         halt-error
84904**      B: open temp table
84905**      L: yield X
84906**         if EOF goto M
84907**         insert row from R..R+n into temp table
84908**         goto L
84909**      M: open write cursor to <table> and its indices
84910**         rewind temp table
84911**      C: loop over rows of intermediate table
84912**           transfer values form intermediate table into <table>
84913**         end loop
84914**      D: cleanup
84915*/
84916SQLITE_PRIVATE void sqlite3Insert(
84917  Parse *pParse,        /* Parser context */
84918  SrcList *pTabList,    /* Name of table into which we are inserting */
84919  ExprList *pList,      /* List of values to be inserted */
84920  Select *pSelect,      /* A SELECT statement to use as the data source */
84921  IdList *pColumn,      /* Column names corresponding to IDLIST. */
84922  int onError           /* How to handle constraint errors */
84923){
84924  sqlite3 *db;          /* The main database structure */
84925  Table *pTab;          /* The table to insert into.  aka TABLE */
84926  char *zTab;           /* Name of the table into which we are inserting */
84927  const char *zDb;      /* Name of the database holding this table */
84928  int i, j, idx;        /* Loop counters */
84929  Vdbe *v;              /* Generate code into this virtual machine */
84930  Index *pIdx;          /* For looping over indices of the table */
84931  int nColumn;          /* Number of columns in the data */
84932  int nHidden = 0;      /* Number of hidden columns if TABLE is virtual */
84933  int baseCur = 0;      /* VDBE Cursor number for pTab */
84934  int keyColumn = -1;   /* Column that is the INTEGER PRIMARY KEY */
84935  int endOfLoop;        /* Label for the end of the insertion loop */
84936  int useTempTable = 0; /* Store SELECT results in intermediate table */
84937  int srcTab = 0;       /* Data comes from this temporary cursor if >=0 */
84938  int addrInsTop = 0;   /* Jump to label "D" */
84939  int addrCont = 0;     /* Top of insert loop. Label "C" in templates 3 and 4 */
84940  int addrSelect = 0;   /* Address of coroutine that implements the SELECT */
84941  SelectDest dest;      /* Destination for SELECT on rhs of INSERT */
84942  int iDb;              /* Index of database holding TABLE */
84943  Db *pDb;              /* The database containing table being inserted into */
84944  int appendFlag = 0;   /* True if the insert is likely to be an append */
84945
84946  /* Register allocations */
84947  int regFromSelect = 0;/* Base register for data coming from SELECT */
84948  int regAutoinc = 0;   /* Register holding the AUTOINCREMENT counter */
84949  int regRowCount = 0;  /* Memory cell used for the row counter */
84950  int regIns;           /* Block of regs holding rowid+data being inserted */
84951  int regRowid;         /* registers holding insert rowid */
84952  int regData;          /* register holding first column to insert */
84953  int regEof = 0;       /* Register recording end of SELECT data */
84954  int *aRegIdx = 0;     /* One register allocated to each index */
84955
84956#ifndef SQLITE_OMIT_TRIGGER
84957  int isView;                 /* True if attempting to insert into a view */
84958  Trigger *pTrigger;          /* List of triggers on pTab, if required */
84959  int tmask;                  /* Mask of trigger times */
84960#endif
84961
84962  db = pParse->db;
84963  memset(&dest, 0, sizeof(dest));
84964  if( pParse->nErr || db->mallocFailed ){
84965    goto insert_cleanup;
84966  }
84967
84968  /* Locate the table into which we will be inserting new information.
84969  */
84970  assert( pTabList->nSrc==1 );
84971  zTab = pTabList->a[0].zName;
84972  if( NEVER(zTab==0) ) goto insert_cleanup;
84973  pTab = sqlite3SrcListLookup(pParse, pTabList);
84974  if( pTab==0 ){
84975    goto insert_cleanup;
84976  }
84977  iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
84978  assert( iDb<db->nDb );
84979  pDb = &db->aDb[iDb];
84980  zDb = pDb->zName;
84981  if( sqlite3AuthCheck(pParse, SQLITE_INSERT, pTab->zName, 0, zDb) ){
84982    goto insert_cleanup;
84983  }
84984
84985  /* Figure out if we have any triggers and if the table being
84986  ** inserted into is a view
84987  */
84988#ifndef SQLITE_OMIT_TRIGGER
84989  pTrigger = sqlite3TriggersExist(pParse, pTab, TK_INSERT, 0, &tmask);
84990  isView = pTab->pSelect!=0;
84991#else
84992# define pTrigger 0
84993# define tmask 0
84994# define isView 0
84995#endif
84996#ifdef SQLITE_OMIT_VIEW
84997# undef isView
84998# define isView 0
84999#endif
85000  assert( (pTrigger && tmask) || (pTrigger==0 && tmask==0) );
85001
85002  /* If pTab is really a view, make sure it has been initialized.
85003  ** ViewGetColumnNames() is a no-op if pTab is not a view (or virtual
85004  ** module table).
85005  */
85006  if( sqlite3ViewGetColumnNames(pParse, pTab) ){
85007    goto insert_cleanup;
85008  }
85009
85010  /* Ensure that:
85011  *  (a) the table is not read-only,
85012  *  (b) that if it is a view then ON INSERT triggers exist
85013  */
85014  if( sqlite3IsReadOnly(pParse, pTab, tmask) ){
85015    goto insert_cleanup;
85016  }
85017
85018  /* Allocate a VDBE
85019  */
85020  v = sqlite3GetVdbe(pParse);
85021  if( v==0 ) goto insert_cleanup;
85022  if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
85023  sqlite3BeginWriteOperation(pParse, pSelect || pTrigger, iDb);
85024
85025#ifndef SQLITE_OMIT_XFER_OPT
85026  /* If the statement is of the form
85027  **
85028  **       INSERT INTO <table1> SELECT * FROM <table2>;
85029  **
85030  ** Then special optimizations can be applied that make the transfer
85031  ** very fast and which reduce fragmentation of indices.
85032  **
85033  ** This is the 2nd template.
85034  */
85035  if( pColumn==0 && xferOptimization(pParse, pTab, pSelect, onError, iDb) ){
85036    assert( !pTrigger );
85037    assert( pList==0 );
85038    goto insert_end;
85039  }
85040#endif /* SQLITE_OMIT_XFER_OPT */
85041
85042  /* If this is an AUTOINCREMENT table, look up the sequence number in the
85043  ** sqlite_sequence table and store it in memory cell regAutoinc.
85044  */
85045  regAutoinc = autoIncBegin(pParse, iDb, pTab);
85046
85047  /* Figure out how many columns of data are supplied.  If the data
85048  ** is coming from a SELECT statement, then generate a co-routine that
85049  ** produces a single row of the SELECT on each invocation.  The
85050  ** co-routine is the common header to the 3rd and 4th templates.
85051  */
85052  if( pSelect ){
85053    /* Data is coming from a SELECT.  Generate code to implement that SELECT
85054    ** as a co-routine.  The code is common to both the 3rd and 4th
85055    ** templates:
85056    **
85057    **         EOF <- 0
85058    **         X <- A
85059    **         goto B
85060    **      A: setup for the SELECT
85061    **         loop over the tables in the SELECT
85062    **           load value into register R..R+n
85063    **           yield X
85064    **         end loop
85065    **         cleanup after the SELECT
85066    **         EOF <- 1
85067    **         yield X
85068    **         halt-error
85069    **
85070    ** On each invocation of the co-routine, it puts a single row of the
85071    ** SELECT result into registers dest.iMem...dest.iMem+dest.nMem-1.
85072    ** (These output registers are allocated by sqlite3Select().)  When
85073    ** the SELECT completes, it sets the EOF flag stored in regEof.
85074    */
85075    int rc, j1;
85076
85077    regEof = ++pParse->nMem;
85078    sqlite3VdbeAddOp2(v, OP_Integer, 0, regEof);      /* EOF <- 0 */
85079    VdbeComment((v, "SELECT eof flag"));
85080    sqlite3SelectDestInit(&dest, SRT_Coroutine, ++pParse->nMem);
85081    addrSelect = sqlite3VdbeCurrentAddr(v)+2;
85082    sqlite3VdbeAddOp2(v, OP_Integer, addrSelect-1, dest.iParm);
85083    j1 = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
85084    VdbeComment((v, "Jump over SELECT coroutine"));
85085
85086    /* Resolve the expressions in the SELECT statement and execute it. */
85087    rc = sqlite3Select(pParse, pSelect, &dest);
85088    assert( pParse->nErr==0 || rc );
85089    if( rc || NEVER(pParse->nErr) || db->mallocFailed ){
85090      goto insert_cleanup;
85091    }
85092    sqlite3VdbeAddOp2(v, OP_Integer, 1, regEof);         /* EOF <- 1 */
85093    sqlite3VdbeAddOp1(v, OP_Yield, dest.iParm);   /* yield X */
85094    sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_INTERNAL, OE_Abort);
85095    VdbeComment((v, "End of SELECT coroutine"));
85096    sqlite3VdbeJumpHere(v, j1);                          /* label B: */
85097
85098    regFromSelect = dest.iMem;
85099    assert( pSelect->pEList );
85100    nColumn = pSelect->pEList->nExpr;
85101    assert( dest.nMem==nColumn );
85102
85103    /* Set useTempTable to TRUE if the result of the SELECT statement
85104    ** should be written into a temporary table (template 4).  Set to
85105    ** FALSE if each* row of the SELECT can be written directly into
85106    ** the destination table (template 3).
85107    **
85108    ** A temp table must be used if the table being updated is also one
85109    ** of the tables being read by the SELECT statement.  Also use a
85110    ** temp table in the case of row triggers.
85111    */
85112    if( pTrigger || readsTable(pParse, addrSelect, iDb, pTab) ){
85113      useTempTable = 1;
85114    }
85115
85116    if( useTempTable ){
85117      /* Invoke the coroutine to extract information from the SELECT
85118      ** and add it to a transient table srcTab.  The code generated
85119      ** here is from the 4th template:
85120      **
85121      **      B: open temp table
85122      **      L: yield X
85123      **         if EOF goto M
85124      **         insert row from R..R+n into temp table
85125      **         goto L
85126      **      M: ...
85127      */
85128      int regRec;          /* Register to hold packed record */
85129      int regTempRowid;    /* Register to hold temp table ROWID */
85130      int addrTop;         /* Label "L" */
85131      int addrIf;          /* Address of jump to M */
85132
85133      srcTab = pParse->nTab++;
85134      regRec = sqlite3GetTempReg(pParse);
85135      regTempRowid = sqlite3GetTempReg(pParse);
85136      sqlite3VdbeAddOp2(v, OP_OpenEphemeral, srcTab, nColumn);
85137      addrTop = sqlite3VdbeAddOp1(v, OP_Yield, dest.iParm);
85138      addrIf = sqlite3VdbeAddOp1(v, OP_If, regEof);
85139      sqlite3VdbeAddOp3(v, OP_MakeRecord, regFromSelect, nColumn, regRec);
85140      sqlite3VdbeAddOp2(v, OP_NewRowid, srcTab, regTempRowid);
85141      sqlite3VdbeAddOp3(v, OP_Insert, srcTab, regRec, regTempRowid);
85142      sqlite3VdbeAddOp2(v, OP_Goto, 0, addrTop);
85143      sqlite3VdbeJumpHere(v, addrIf);
85144      sqlite3ReleaseTempReg(pParse, regRec);
85145      sqlite3ReleaseTempReg(pParse, regTempRowid);
85146    }
85147  }else{
85148    /* This is the case if the data for the INSERT is coming from a VALUES
85149    ** clause
85150    */
85151    NameContext sNC;
85152    memset(&sNC, 0, sizeof(sNC));
85153    sNC.pParse = pParse;
85154    srcTab = -1;
85155    assert( useTempTable==0 );
85156    nColumn = pList ? pList->nExpr : 0;
85157    for(i=0; i<nColumn; i++){
85158      if( sqlite3ResolveExprNames(&sNC, pList->a[i].pExpr) ){
85159        goto insert_cleanup;
85160      }
85161    }
85162  }
85163
85164  /* Make sure the number of columns in the source data matches the number
85165  ** of columns to be inserted into the table.
85166  */
85167  if( IsVirtual(pTab) ){
85168    for(i=0; i<pTab->nCol; i++){
85169      nHidden += (IsHiddenColumn(&pTab->aCol[i]) ? 1 : 0);
85170    }
85171  }
85172  if( pColumn==0 && nColumn && nColumn!=(pTab->nCol-nHidden) ){
85173    sqlite3ErrorMsg(pParse,
85174       "table %S has %d columns but %d values were supplied",
85175       pTabList, 0, pTab->nCol-nHidden, nColumn);
85176    goto insert_cleanup;
85177  }
85178  if( pColumn!=0 && nColumn!=pColumn->nId ){
85179    sqlite3ErrorMsg(pParse, "%d values for %d columns", nColumn, pColumn->nId);
85180    goto insert_cleanup;
85181  }
85182
85183  /* If the INSERT statement included an IDLIST term, then make sure
85184  ** all elements of the IDLIST really are columns of the table and
85185  ** remember the column indices.
85186  **
85187  ** If the table has an INTEGER PRIMARY KEY column and that column
85188  ** is named in the IDLIST, then record in the keyColumn variable
85189  ** the index into IDLIST of the primary key column.  keyColumn is
85190  ** the index of the primary key as it appears in IDLIST, not as
85191  ** is appears in the original table.  (The index of the primary
85192  ** key in the original table is pTab->iPKey.)
85193  */
85194  if( pColumn ){
85195    for(i=0; i<pColumn->nId; i++){
85196      pColumn->a[i].idx = -1;
85197    }
85198    for(i=0; i<pColumn->nId; i++){
85199      for(j=0; j<pTab->nCol; j++){
85200        if( sqlite3StrICmp(pColumn->a[i].zName, pTab->aCol[j].zName)==0 ){
85201          pColumn->a[i].idx = j;
85202          if( j==pTab->iPKey ){
85203            keyColumn = i;
85204          }
85205          break;
85206        }
85207      }
85208      if( j>=pTab->nCol ){
85209        if( sqlite3IsRowid(pColumn->a[i].zName) ){
85210          keyColumn = i;
85211        }else{
85212          sqlite3ErrorMsg(pParse, "table %S has no column named %s",
85213              pTabList, 0, pColumn->a[i].zName);
85214          pParse->checkSchema = 1;
85215          goto insert_cleanup;
85216        }
85217      }
85218    }
85219  }
85220
85221  /* If there is no IDLIST term but the table has an integer primary
85222  ** key, the set the keyColumn variable to the primary key column index
85223  ** in the original table definition.
85224  */
85225  if( pColumn==0 && nColumn>0 ){
85226    keyColumn = pTab->iPKey;
85227  }
85228
85229  /* Initialize the count of rows to be inserted
85230  */
85231  if( db->flags & SQLITE_CountRows ){
85232    regRowCount = ++pParse->nMem;
85233    sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
85234  }
85235
85236  /* If this is not a view, open the table and and all indices */
85237  if( !isView ){
85238    int nIdx;
85239
85240    baseCur = pParse->nTab;
85241    nIdx = sqlite3OpenTableAndIndices(pParse, pTab, baseCur, OP_OpenWrite);
85242    aRegIdx = sqlite3DbMallocRaw(db, sizeof(int)*(nIdx+1));
85243    if( aRegIdx==0 ){
85244      goto insert_cleanup;
85245    }
85246    for(i=0; i<nIdx; i++){
85247      aRegIdx[i] = ++pParse->nMem;
85248    }
85249  }
85250
85251  /* This is the top of the main insertion loop */
85252  if( useTempTable ){
85253    /* This block codes the top of loop only.  The complete loop is the
85254    ** following pseudocode (template 4):
85255    **
85256    **         rewind temp table
85257    **      C: loop over rows of intermediate table
85258    **           transfer values form intermediate table into <table>
85259    **         end loop
85260    **      D: ...
85261    */
85262    addrInsTop = sqlite3VdbeAddOp1(v, OP_Rewind, srcTab);
85263    addrCont = sqlite3VdbeCurrentAddr(v);
85264  }else if( pSelect ){
85265    /* This block codes the top of loop only.  The complete loop is the
85266    ** following pseudocode (template 3):
85267    **
85268    **      C: yield X
85269    **         if EOF goto D
85270    **         insert the select result into <table> from R..R+n
85271    **         goto C
85272    **      D: ...
85273    */
85274    addrCont = sqlite3VdbeAddOp1(v, OP_Yield, dest.iParm);
85275    addrInsTop = sqlite3VdbeAddOp1(v, OP_If, regEof);
85276  }
85277
85278  /* Allocate registers for holding the rowid of the new row,
85279  ** the content of the new row, and the assemblied row record.
85280  */
85281  regRowid = regIns = pParse->nMem+1;
85282  pParse->nMem += pTab->nCol + 1;
85283  if( IsVirtual(pTab) ){
85284    regRowid++;
85285    pParse->nMem++;
85286  }
85287  regData = regRowid+1;
85288
85289  /* Run the BEFORE and INSTEAD OF triggers, if there are any
85290  */
85291  endOfLoop = sqlite3VdbeMakeLabel(v);
85292  if( tmask & TRIGGER_BEFORE ){
85293    int regCols = sqlite3GetTempRange(pParse, pTab->nCol+1);
85294
85295    /* build the NEW.* reference row.  Note that if there is an INTEGER
85296    ** PRIMARY KEY into which a NULL is being inserted, that NULL will be
85297    ** translated into a unique ID for the row.  But on a BEFORE trigger,
85298    ** we do not know what the unique ID will be (because the insert has
85299    ** not happened yet) so we substitute a rowid of -1
85300    */
85301    if( keyColumn<0 ){
85302      sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
85303    }else{
85304      int j1;
85305      if( useTempTable ){
85306        sqlite3VdbeAddOp3(v, OP_Column, srcTab, keyColumn, regCols);
85307      }else{
85308        assert( pSelect==0 );  /* Otherwise useTempTable is true */
85309        sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr, regCols);
85310      }
85311      j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regCols);
85312      sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
85313      sqlite3VdbeJumpHere(v, j1);
85314      sqlite3VdbeAddOp1(v, OP_MustBeInt, regCols);
85315    }
85316
85317    /* Cannot have triggers on a virtual table. If it were possible,
85318    ** this block would have to account for hidden column.
85319    */
85320    assert( !IsVirtual(pTab) );
85321
85322    /* Create the new column data
85323    */
85324    for(i=0; i<pTab->nCol; i++){
85325      if( pColumn==0 ){
85326        j = i;
85327      }else{
85328        for(j=0; j<pColumn->nId; j++){
85329          if( pColumn->a[j].idx==i ) break;
85330        }
85331      }
85332      if( (!useTempTable && !pList) || (pColumn && j>=pColumn->nId) ){
85333        sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regCols+i+1);
85334      }else if( useTempTable ){
85335        sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, regCols+i+1);
85336      }else{
85337        assert( pSelect==0 ); /* Otherwise useTempTable is true */
85338        sqlite3ExprCodeAndCache(pParse, pList->a[j].pExpr, regCols+i+1);
85339      }
85340    }
85341
85342    /* If this is an INSERT on a view with an INSTEAD OF INSERT trigger,
85343    ** do not attempt any conversions before assembling the record.
85344    ** If this is a real table, attempt conversions as required by the
85345    ** table column affinities.
85346    */
85347    if( !isView ){
85348      sqlite3VdbeAddOp2(v, OP_Affinity, regCols+1, pTab->nCol);
85349      sqlite3TableAffinityStr(v, pTab);
85350    }
85351
85352    /* Fire BEFORE or INSTEAD OF triggers */
85353    sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_BEFORE,
85354        pTab, regCols-pTab->nCol-1, onError, endOfLoop);
85355
85356    sqlite3ReleaseTempRange(pParse, regCols, pTab->nCol+1);
85357  }
85358
85359  /* Push the record number for the new entry onto the stack.  The
85360  ** record number is a randomly generate integer created by NewRowid
85361  ** except when the table has an INTEGER PRIMARY KEY column, in which
85362  ** case the record number is the same as that column.
85363  */
85364  if( !isView ){
85365    if( IsVirtual(pTab) ){
85366      /* The row that the VUpdate opcode will delete: none */
85367      sqlite3VdbeAddOp2(v, OP_Null, 0, regIns);
85368    }
85369    if( keyColumn>=0 ){
85370      if( useTempTable ){
85371        sqlite3VdbeAddOp3(v, OP_Column, srcTab, keyColumn, regRowid);
85372      }else if( pSelect ){
85373        sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+keyColumn, regRowid);
85374      }else{
85375        VdbeOp *pOp;
85376        sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr, regRowid);
85377        pOp = sqlite3VdbeGetOp(v, -1);
85378        if( ALWAYS(pOp) && pOp->opcode==OP_Null && !IsVirtual(pTab) ){
85379          appendFlag = 1;
85380          pOp->opcode = OP_NewRowid;
85381          pOp->p1 = baseCur;
85382          pOp->p2 = regRowid;
85383          pOp->p3 = regAutoinc;
85384        }
85385      }
85386      /* If the PRIMARY KEY expression is NULL, then use OP_NewRowid
85387      ** to generate a unique primary key value.
85388      */
85389      if( !appendFlag ){
85390        int j1;
85391        if( !IsVirtual(pTab) ){
85392          j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regRowid);
85393          sqlite3VdbeAddOp3(v, OP_NewRowid, baseCur, regRowid, regAutoinc);
85394          sqlite3VdbeJumpHere(v, j1);
85395        }else{
85396          j1 = sqlite3VdbeCurrentAddr(v);
85397          sqlite3VdbeAddOp2(v, OP_IsNull, regRowid, j1+2);
85398        }
85399        sqlite3VdbeAddOp1(v, OP_MustBeInt, regRowid);
85400      }
85401    }else if( IsVirtual(pTab) ){
85402      sqlite3VdbeAddOp2(v, OP_Null, 0, regRowid);
85403    }else{
85404      sqlite3VdbeAddOp3(v, OP_NewRowid, baseCur, regRowid, regAutoinc);
85405      appendFlag = 1;
85406    }
85407    autoIncStep(pParse, regAutoinc, regRowid);
85408
85409    /* Push onto the stack, data for all columns of the new entry, beginning
85410    ** with the first column.
85411    */
85412    nHidden = 0;
85413    for(i=0; i<pTab->nCol; i++){
85414      int iRegStore = regRowid+1+i;
85415      if( i==pTab->iPKey ){
85416        /* The value of the INTEGER PRIMARY KEY column is always a NULL.
85417        ** Whenever this column is read, the record number will be substituted
85418        ** in its place.  So will fill this column with a NULL to avoid
85419        ** taking up data space with information that will never be used. */
85420        sqlite3VdbeAddOp2(v, OP_Null, 0, iRegStore);
85421        continue;
85422      }
85423      if( pColumn==0 ){
85424        if( IsHiddenColumn(&pTab->aCol[i]) ){
85425          assert( IsVirtual(pTab) );
85426          j = -1;
85427          nHidden++;
85428        }else{
85429          j = i - nHidden;
85430        }
85431      }else{
85432        for(j=0; j<pColumn->nId; j++){
85433          if( pColumn->a[j].idx==i ) break;
85434        }
85435      }
85436      if( j<0 || nColumn==0 || (pColumn && j>=pColumn->nId) ){
85437        sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, iRegStore);
85438      }else if( useTempTable ){
85439        sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, iRegStore);
85440      }else if( pSelect ){
85441        sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+j, iRegStore);
85442      }else{
85443        sqlite3ExprCode(pParse, pList->a[j].pExpr, iRegStore);
85444      }
85445    }
85446
85447    /* Generate code to check constraints and generate index keys and
85448    ** do the insertion.
85449    */
85450#ifndef SQLITE_OMIT_VIRTUALTABLE
85451    if( IsVirtual(pTab) ){
85452      const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
85453      sqlite3VtabMakeWritable(pParse, pTab);
85454      sqlite3VdbeAddOp4(v, OP_VUpdate, 1, pTab->nCol+2, regIns, pVTab, P4_VTAB);
85455      sqlite3MayAbort(pParse);
85456    }else
85457#endif
85458    {
85459      int isReplace;    /* Set to true if constraints may cause a replace */
85460      sqlite3GenerateConstraintChecks(pParse, pTab, baseCur, regIns, aRegIdx,
85461          keyColumn>=0, 0, onError, endOfLoop, &isReplace
85462      );
85463      sqlite3FkCheck(pParse, pTab, 0, regIns);
85464      sqlite3CompleteInsertion(
85465          pParse, pTab, baseCur, regIns, aRegIdx, 0, appendFlag, isReplace==0
85466      );
85467    }
85468  }
85469
85470  /* Update the count of rows that are inserted
85471  */
85472  if( (db->flags & SQLITE_CountRows)!=0 ){
85473    sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
85474  }
85475
85476  if( pTrigger ){
85477    /* Code AFTER triggers */
85478    sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_AFTER,
85479        pTab, regData-2-pTab->nCol, onError, endOfLoop);
85480  }
85481
85482  /* The bottom of the main insertion loop, if the data source
85483  ** is a SELECT statement.
85484  */
85485  sqlite3VdbeResolveLabel(v, endOfLoop);
85486  if( useTempTable ){
85487    sqlite3VdbeAddOp2(v, OP_Next, srcTab, addrCont);
85488    sqlite3VdbeJumpHere(v, addrInsTop);
85489    sqlite3VdbeAddOp1(v, OP_Close, srcTab);
85490  }else if( pSelect ){
85491    sqlite3VdbeAddOp2(v, OP_Goto, 0, addrCont);
85492    sqlite3VdbeJumpHere(v, addrInsTop);
85493  }
85494
85495  if( !IsVirtual(pTab) && !isView ){
85496    /* Close all tables opened */
85497    sqlite3VdbeAddOp1(v, OP_Close, baseCur);
85498    for(idx=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, idx++){
85499      sqlite3VdbeAddOp1(v, OP_Close, idx+baseCur);
85500    }
85501  }
85502
85503insert_end:
85504  /* Update the sqlite_sequence table by storing the content of the
85505  ** maximum rowid counter values recorded while inserting into
85506  ** autoincrement tables.
85507  */
85508  if( pParse->nested==0 && pParse->pTriggerTab==0 ){
85509    sqlite3AutoincrementEnd(pParse);
85510  }
85511
85512  /*
85513  ** Return the number of rows inserted. If this routine is
85514  ** generating code because of a call to sqlite3NestedParse(), do not
85515  ** invoke the callback function.
85516  */
85517  if( (db->flags&SQLITE_CountRows) && !pParse->nested && !pParse->pTriggerTab ){
85518    sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
85519    sqlite3VdbeSetNumCols(v, 1);
85520    sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows inserted", SQLITE_STATIC);
85521  }
85522
85523insert_cleanup:
85524  sqlite3SrcListDelete(db, pTabList);
85525  sqlite3ExprListDelete(db, pList);
85526  sqlite3SelectDelete(db, pSelect);
85527  sqlite3IdListDelete(db, pColumn);
85528  sqlite3DbFree(db, aRegIdx);
85529}
85530
85531/* Make sure "isView" and other macros defined above are undefined. Otherwise
85532** thely may interfere with compilation of other functions in this file
85533** (or in another file, if this file becomes part of the amalgamation).  */
85534#ifdef isView
85535 #undef isView
85536#endif
85537#ifdef pTrigger
85538 #undef pTrigger
85539#endif
85540#ifdef tmask
85541 #undef tmask
85542#endif
85543
85544
85545/*
85546** Generate code to do constraint checks prior to an INSERT or an UPDATE.
85547**
85548** The input is a range of consecutive registers as follows:
85549**
85550**    1.  The rowid of the row after the update.
85551**
85552**    2.  The data in the first column of the entry after the update.
85553**
85554**    i.  Data from middle columns...
85555**
85556**    N.  The data in the last column of the entry after the update.
85557**
85558** The regRowid parameter is the index of the register containing (1).
85559**
85560** If isUpdate is true and rowidChng is non-zero, then rowidChng contains
85561** the address of a register containing the rowid before the update takes
85562** place. isUpdate is true for UPDATEs and false for INSERTs. If isUpdate
85563** is false, indicating an INSERT statement, then a non-zero rowidChng
85564** indicates that the rowid was explicitly specified as part of the
85565** INSERT statement. If rowidChng is false, it means that  the rowid is
85566** computed automatically in an insert or that the rowid value is not
85567** modified by an update.
85568**
85569** The code generated by this routine store new index entries into
85570** registers identified by aRegIdx[].  No index entry is created for
85571** indices where aRegIdx[i]==0.  The order of indices in aRegIdx[] is
85572** the same as the order of indices on the linked list of indices
85573** attached to the table.
85574**
85575** This routine also generates code to check constraints.  NOT NULL,
85576** CHECK, and UNIQUE constraints are all checked.  If a constraint fails,
85577** then the appropriate action is performed.  There are five possible
85578** actions: ROLLBACK, ABORT, FAIL, REPLACE, and IGNORE.
85579**
85580**  Constraint type  Action       What Happens
85581**  ---------------  ----------   ----------------------------------------
85582**  any              ROLLBACK     The current transaction is rolled back and
85583**                                sqlite3_exec() returns immediately with a
85584**                                return code of SQLITE_CONSTRAINT.
85585**
85586**  any              ABORT        Back out changes from the current command
85587**                                only (do not do a complete rollback) then
85588**                                cause sqlite3_exec() to return immediately
85589**                                with SQLITE_CONSTRAINT.
85590**
85591**  any              FAIL         Sqlite_exec() returns immediately with a
85592**                                return code of SQLITE_CONSTRAINT.  The
85593**                                transaction is not rolled back and any
85594**                                prior changes are retained.
85595**
85596**  any              IGNORE       The record number and data is popped from
85597**                                the stack and there is an immediate jump
85598**                                to label ignoreDest.
85599**
85600**  NOT NULL         REPLACE      The NULL value is replace by the default
85601**                                value for that column.  If the default value
85602**                                is NULL, the action is the same as ABORT.
85603**
85604**  UNIQUE           REPLACE      The other row that conflicts with the row
85605**                                being inserted is removed.
85606**
85607**  CHECK            REPLACE      Illegal.  The results in an exception.
85608**
85609** Which action to take is determined by the overrideError parameter.
85610** Or if overrideError==OE_Default, then the pParse->onError parameter
85611** is used.  Or if pParse->onError==OE_Default then the onError value
85612** for the constraint is used.
85613**
85614** The calling routine must open a read/write cursor for pTab with
85615** cursor number "baseCur".  All indices of pTab must also have open
85616** read/write cursors with cursor number baseCur+i for the i-th cursor.
85617** Except, if there is no possibility of a REPLACE action then
85618** cursors do not need to be open for indices where aRegIdx[i]==0.
85619*/
85620SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(
85621  Parse *pParse,      /* The parser context */
85622  Table *pTab,        /* the table into which we are inserting */
85623  int baseCur,        /* Index of a read/write cursor pointing at pTab */
85624  int regRowid,       /* Index of the range of input registers */
85625  int *aRegIdx,       /* Register used by each index.  0 for unused indices */
85626  int rowidChng,      /* True if the rowid might collide with existing entry */
85627  int isUpdate,       /* True for UPDATE, False for INSERT */
85628  int overrideError,  /* Override onError to this if not OE_Default */
85629  int ignoreDest,     /* Jump to this label on an OE_Ignore resolution */
85630  int *pbMayReplace   /* OUT: Set to true if constraint may cause a replace */
85631){
85632  int i;              /* loop counter */
85633  Vdbe *v;            /* VDBE under constrution */
85634  int nCol;           /* Number of columns */
85635  int onError;        /* Conflict resolution strategy */
85636  int j1;             /* Addresss of jump instruction */
85637  int j2 = 0, j3;     /* Addresses of jump instructions */
85638  int regData;        /* Register containing first data column */
85639  int iCur;           /* Table cursor number */
85640  Index *pIdx;         /* Pointer to one of the indices */
85641  int seenReplace = 0; /* True if REPLACE is used to resolve INT PK conflict */
85642  int regOldRowid = (rowidChng && isUpdate) ? rowidChng : regRowid;
85643
85644  v = sqlite3GetVdbe(pParse);
85645  assert( v!=0 );
85646  assert( pTab->pSelect==0 );  /* This table is not a VIEW */
85647  nCol = pTab->nCol;
85648  regData = regRowid + 1;
85649
85650  /* Test all NOT NULL constraints.
85651  */
85652  for(i=0; i<nCol; i++){
85653    if( i==pTab->iPKey ){
85654      continue;
85655    }
85656    onError = pTab->aCol[i].notNull;
85657    if( onError==OE_None ) continue;
85658    if( overrideError!=OE_Default ){
85659      onError = overrideError;
85660    }else if( onError==OE_Default ){
85661      onError = OE_Abort;
85662    }
85663    if( onError==OE_Replace && pTab->aCol[i].pDflt==0 ){
85664      onError = OE_Abort;
85665    }
85666    assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
85667        || onError==OE_Ignore || onError==OE_Replace );
85668    switch( onError ){
85669      case OE_Abort:
85670        sqlite3MayAbort(pParse);
85671      case OE_Rollback:
85672      case OE_Fail: {
85673        char *zMsg;
85674        sqlite3VdbeAddOp3(v, OP_HaltIfNull,
85675                                  SQLITE_CONSTRAINT, onError, regData+i);
85676        zMsg = sqlite3MPrintf(pParse->db, "%s.%s may not be NULL",
85677                              pTab->zName, pTab->aCol[i].zName);
85678        sqlite3VdbeChangeP4(v, -1, zMsg, P4_DYNAMIC);
85679        break;
85680      }
85681      case OE_Ignore: {
85682        sqlite3VdbeAddOp2(v, OP_IsNull, regData+i, ignoreDest);
85683        break;
85684      }
85685      default: {
85686        assert( onError==OE_Replace );
85687        j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regData+i);
85688        sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regData+i);
85689        sqlite3VdbeJumpHere(v, j1);
85690        break;
85691      }
85692    }
85693  }
85694
85695  /* Test all CHECK constraints
85696  */
85697#ifndef SQLITE_OMIT_CHECK
85698  if( pTab->pCheck && (pParse->db->flags & SQLITE_IgnoreChecks)==0 ){
85699    int allOk = sqlite3VdbeMakeLabel(v);
85700    pParse->ckBase = regData;
85701    sqlite3ExprIfTrue(pParse, pTab->pCheck, allOk, SQLITE_JUMPIFNULL);
85702    onError = overrideError!=OE_Default ? overrideError : OE_Abort;
85703    if( onError==OE_Ignore ){
85704      sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
85705    }else{
85706      if( onError==OE_Replace ) onError = OE_Abort; /* IMP: R-15569-63625 */
85707      sqlite3HaltConstraint(pParse, onError, 0, 0);
85708    }
85709    sqlite3VdbeResolveLabel(v, allOk);
85710  }
85711#endif /* !defined(SQLITE_OMIT_CHECK) */
85712
85713  /* If we have an INTEGER PRIMARY KEY, make sure the primary key
85714  ** of the new record does not previously exist.  Except, if this
85715  ** is an UPDATE and the primary key is not changing, that is OK.
85716  */
85717  if( rowidChng ){
85718    onError = pTab->keyConf;
85719    if( overrideError!=OE_Default ){
85720      onError = overrideError;
85721    }else if( onError==OE_Default ){
85722      onError = OE_Abort;
85723    }
85724
85725    if( isUpdate ){
85726      j2 = sqlite3VdbeAddOp3(v, OP_Eq, regRowid, 0, rowidChng);
85727    }
85728    j3 = sqlite3VdbeAddOp3(v, OP_NotExists, baseCur, 0, regRowid);
85729    switch( onError ){
85730      default: {
85731        onError = OE_Abort;
85732        /* Fall thru into the next case */
85733      }
85734      case OE_Rollback:
85735      case OE_Abort:
85736      case OE_Fail: {
85737        sqlite3HaltConstraint(
85738          pParse, onError, "PRIMARY KEY must be unique", P4_STATIC);
85739        break;
85740      }
85741      case OE_Replace: {
85742        /* If there are DELETE triggers on this table and the
85743        ** recursive-triggers flag is set, call GenerateRowDelete() to
85744        ** remove the conflicting row from the the table. This will fire
85745        ** the triggers and remove both the table and index b-tree entries.
85746        **
85747        ** Otherwise, if there are no triggers or the recursive-triggers
85748        ** flag is not set, but the table has one or more indexes, call
85749        ** GenerateRowIndexDelete(). This removes the index b-tree entries
85750        ** only. The table b-tree entry will be replaced by the new entry
85751        ** when it is inserted.
85752        **
85753        ** If either GenerateRowDelete() or GenerateRowIndexDelete() is called,
85754        ** also invoke MultiWrite() to indicate that this VDBE may require
85755        ** statement rollback (if the statement is aborted after the delete
85756        ** takes place). Earlier versions called sqlite3MultiWrite() regardless,
85757        ** but being more selective here allows statements like:
85758        **
85759        **   REPLACE INTO t(rowid) VALUES($newrowid)
85760        **
85761        ** to run without a statement journal if there are no indexes on the
85762        ** table.
85763        */
85764        Trigger *pTrigger = 0;
85765        if( pParse->db->flags&SQLITE_RecTriggers ){
85766          pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
85767        }
85768        if( pTrigger || sqlite3FkRequired(pParse, pTab, 0, 0) ){
85769          sqlite3MultiWrite(pParse);
85770          sqlite3GenerateRowDelete(
85771              pParse, pTab, baseCur, regRowid, 0, pTrigger, OE_Replace
85772          );
85773        }else if( pTab->pIndex ){
85774          sqlite3MultiWrite(pParse);
85775          sqlite3GenerateRowIndexDelete(pParse, pTab, baseCur, 0);
85776        }
85777        seenReplace = 1;
85778        break;
85779      }
85780      case OE_Ignore: {
85781        assert( seenReplace==0 );
85782        sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
85783        break;
85784      }
85785    }
85786    sqlite3VdbeJumpHere(v, j3);
85787    if( isUpdate ){
85788      sqlite3VdbeJumpHere(v, j2);
85789    }
85790  }
85791
85792  /* Test all UNIQUE constraints by creating entries for each UNIQUE
85793  ** index and making sure that duplicate entries do not already exist.
85794  ** Add the new records to the indices as we go.
85795  */
85796  for(iCur=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, iCur++){
85797    int regIdx;
85798    int regR;
85799
85800    if( aRegIdx[iCur]==0 ) continue;  /* Skip unused indices */
85801
85802    /* Create a key for accessing the index entry */
85803    regIdx = sqlite3GetTempRange(pParse, pIdx->nColumn+1);
85804    for(i=0; i<pIdx->nColumn; i++){
85805      int idx = pIdx->aiColumn[i];
85806      if( idx==pTab->iPKey ){
85807        sqlite3VdbeAddOp2(v, OP_SCopy, regRowid, regIdx+i);
85808      }else{
85809        sqlite3VdbeAddOp2(v, OP_SCopy, regData+idx, regIdx+i);
85810      }
85811    }
85812    sqlite3VdbeAddOp2(v, OP_SCopy, regRowid, regIdx+i);
85813    sqlite3VdbeAddOp3(v, OP_MakeRecord, regIdx, pIdx->nColumn+1, aRegIdx[iCur]);
85814    sqlite3VdbeChangeP4(v, -1, sqlite3IndexAffinityStr(v, pIdx), P4_TRANSIENT);
85815    sqlite3ExprCacheAffinityChange(pParse, regIdx, pIdx->nColumn+1);
85816
85817    /* Find out what action to take in case there is an indexing conflict */
85818    onError = pIdx->onError;
85819    if( onError==OE_None ){
85820      sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn+1);
85821      continue;  /* pIdx is not a UNIQUE index */
85822    }
85823    if( overrideError!=OE_Default ){
85824      onError = overrideError;
85825    }else if( onError==OE_Default ){
85826      onError = OE_Abort;
85827    }
85828    if( seenReplace ){
85829      if( onError==OE_Ignore ) onError = OE_Replace;
85830      else if( onError==OE_Fail ) onError = OE_Abort;
85831    }
85832
85833    /* Check to see if the new index entry will be unique */
85834    regR = sqlite3GetTempReg(pParse);
85835    sqlite3VdbeAddOp2(v, OP_SCopy, regOldRowid, regR);
85836    j3 = sqlite3VdbeAddOp4(v, OP_IsUnique, baseCur+iCur+1, 0,
85837                           regR, SQLITE_INT_TO_PTR(regIdx),
85838                           P4_INT32);
85839    sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn+1);
85840
85841    /* Generate code that executes if the new index entry is not unique */
85842    assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
85843        || onError==OE_Ignore || onError==OE_Replace );
85844    switch( onError ){
85845      case OE_Rollback:
85846      case OE_Abort:
85847      case OE_Fail: {
85848        int j;
85849        StrAccum errMsg;
85850        const char *zSep;
85851        char *zErr;
85852
85853        sqlite3StrAccumInit(&errMsg, 0, 0, 200);
85854        errMsg.db = pParse->db;
85855        zSep = pIdx->nColumn>1 ? "columns " : "column ";
85856        for(j=0; j<pIdx->nColumn; j++){
85857          char *zCol = pTab->aCol[pIdx->aiColumn[j]].zName;
85858          sqlite3StrAccumAppend(&errMsg, zSep, -1);
85859          zSep = ", ";
85860          sqlite3StrAccumAppend(&errMsg, zCol, -1);
85861        }
85862        sqlite3StrAccumAppend(&errMsg,
85863            pIdx->nColumn>1 ? " are not unique" : " is not unique", -1);
85864        zErr = sqlite3StrAccumFinish(&errMsg);
85865        sqlite3HaltConstraint(pParse, onError, zErr, 0);
85866        sqlite3DbFree(errMsg.db, zErr);
85867        break;
85868      }
85869      case OE_Ignore: {
85870        assert( seenReplace==0 );
85871        sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
85872        break;
85873      }
85874      default: {
85875        Trigger *pTrigger = 0;
85876        assert( onError==OE_Replace );
85877        sqlite3MultiWrite(pParse);
85878        if( pParse->db->flags&SQLITE_RecTriggers ){
85879          pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
85880        }
85881        sqlite3GenerateRowDelete(
85882            pParse, pTab, baseCur, regR, 0, pTrigger, OE_Replace
85883        );
85884        seenReplace = 1;
85885        break;
85886      }
85887    }
85888    sqlite3VdbeJumpHere(v, j3);
85889    sqlite3ReleaseTempReg(pParse, regR);
85890  }
85891
85892  if( pbMayReplace ){
85893    *pbMayReplace = seenReplace;
85894  }
85895}
85896
85897/*
85898** This routine generates code to finish the INSERT or UPDATE operation
85899** that was started by a prior call to sqlite3GenerateConstraintChecks.
85900** A consecutive range of registers starting at regRowid contains the
85901** rowid and the content to be inserted.
85902**
85903** The arguments to this routine should be the same as the first six
85904** arguments to sqlite3GenerateConstraintChecks.
85905*/
85906SQLITE_PRIVATE void sqlite3CompleteInsertion(
85907  Parse *pParse,      /* The parser context */
85908  Table *pTab,        /* the table into which we are inserting */
85909  int baseCur,        /* Index of a read/write cursor pointing at pTab */
85910  int regRowid,       /* Range of content */
85911  int *aRegIdx,       /* Register used by each index.  0 for unused indices */
85912  int isUpdate,       /* True for UPDATE, False for INSERT */
85913  int appendBias,     /* True if this is likely to be an append */
85914  int useSeekResult   /* True to set the USESEEKRESULT flag on OP_[Idx]Insert */
85915){
85916  int i;
85917  Vdbe *v;
85918  int nIdx;
85919  Index *pIdx;
85920  u8 pik_flags;
85921  int regData;
85922  int regRec;
85923
85924  v = sqlite3GetVdbe(pParse);
85925  assert( v!=0 );
85926  assert( pTab->pSelect==0 );  /* This table is not a VIEW */
85927  for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){}
85928  for(i=nIdx-1; i>=0; i--){
85929    if( aRegIdx[i]==0 ) continue;
85930    sqlite3VdbeAddOp2(v, OP_IdxInsert, baseCur+i+1, aRegIdx[i]);
85931    if( useSeekResult ){
85932      sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
85933    }
85934  }
85935  regData = regRowid + 1;
85936  regRec = sqlite3GetTempReg(pParse);
85937  sqlite3VdbeAddOp3(v, OP_MakeRecord, regData, pTab->nCol, regRec);
85938  sqlite3TableAffinityStr(v, pTab);
85939  sqlite3ExprCacheAffinityChange(pParse, regData, pTab->nCol);
85940  if( pParse->nested ){
85941    pik_flags = 0;
85942  }else{
85943    pik_flags = OPFLAG_NCHANGE;
85944    pik_flags |= (isUpdate?OPFLAG_ISUPDATE:OPFLAG_LASTROWID);
85945  }
85946  if( appendBias ){
85947    pik_flags |= OPFLAG_APPEND;
85948  }
85949  if( useSeekResult ){
85950    pik_flags |= OPFLAG_USESEEKRESULT;
85951  }
85952  sqlite3VdbeAddOp3(v, OP_Insert, baseCur, regRec, regRowid);
85953  if( !pParse->nested ){
85954    sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_TRANSIENT);
85955  }
85956  sqlite3VdbeChangeP5(v, pik_flags);
85957}
85958
85959/*
85960** Generate code that will open cursors for a table and for all
85961** indices of that table.  The "baseCur" parameter is the cursor number used
85962** for the table.  Indices are opened on subsequent cursors.
85963**
85964** Return the number of indices on the table.
85965*/
85966SQLITE_PRIVATE int sqlite3OpenTableAndIndices(
85967  Parse *pParse,   /* Parsing context */
85968  Table *pTab,     /* Table to be opened */
85969  int baseCur,     /* Cursor number assigned to the table */
85970  int op           /* OP_OpenRead or OP_OpenWrite */
85971){
85972  int i;
85973  int iDb;
85974  Index *pIdx;
85975  Vdbe *v;
85976
85977  if( IsVirtual(pTab) ) return 0;
85978  iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
85979  v = sqlite3GetVdbe(pParse);
85980  assert( v!=0 );
85981  sqlite3OpenTable(pParse, baseCur, iDb, pTab, op);
85982  for(i=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
85983    KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
85984    assert( pIdx->pSchema==pTab->pSchema );
85985    sqlite3VdbeAddOp4(v, op, i+baseCur, pIdx->tnum, iDb,
85986                      (char*)pKey, P4_KEYINFO_HANDOFF);
85987    VdbeComment((v, "%s", pIdx->zName));
85988  }
85989  if( pParse->nTab<baseCur+i ){
85990    pParse->nTab = baseCur+i;
85991  }
85992  return i-1;
85993}
85994
85995
85996#ifdef SQLITE_TEST
85997/*
85998** The following global variable is incremented whenever the
85999** transfer optimization is used.  This is used for testing
86000** purposes only - to make sure the transfer optimization really
86001** is happening when it is suppose to.
86002*/
86003SQLITE_API int sqlite3_xferopt_count;
86004#endif /* SQLITE_TEST */
86005
86006
86007#ifndef SQLITE_OMIT_XFER_OPT
86008/*
86009** Check to collation names to see if they are compatible.
86010*/
86011static int xferCompatibleCollation(const char *z1, const char *z2){
86012  if( z1==0 ){
86013    return z2==0;
86014  }
86015  if( z2==0 ){
86016    return 0;
86017  }
86018  return sqlite3StrICmp(z1, z2)==0;
86019}
86020
86021
86022/*
86023** Check to see if index pSrc is compatible as a source of data
86024** for index pDest in an insert transfer optimization.  The rules
86025** for a compatible index:
86026**
86027**    *   The index is over the same set of columns
86028**    *   The same DESC and ASC markings occurs on all columns
86029**    *   The same onError processing (OE_Abort, OE_Ignore, etc)
86030**    *   The same collating sequence on each column
86031*/
86032static int xferCompatibleIndex(Index *pDest, Index *pSrc){
86033  int i;
86034  assert( pDest && pSrc );
86035  assert( pDest->pTable!=pSrc->pTable );
86036  if( pDest->nColumn!=pSrc->nColumn ){
86037    return 0;   /* Different number of columns */
86038  }
86039  if( pDest->onError!=pSrc->onError ){
86040    return 0;   /* Different conflict resolution strategies */
86041  }
86042  for(i=0; i<pSrc->nColumn; i++){
86043    if( pSrc->aiColumn[i]!=pDest->aiColumn[i] ){
86044      return 0;   /* Different columns indexed */
86045    }
86046    if( pSrc->aSortOrder[i]!=pDest->aSortOrder[i] ){
86047      return 0;   /* Different sort orders */
86048    }
86049    if( !xferCompatibleCollation(pSrc->azColl[i],pDest->azColl[i]) ){
86050      return 0;   /* Different collating sequences */
86051    }
86052  }
86053
86054  /* If no test above fails then the indices must be compatible */
86055  return 1;
86056}
86057
86058/*
86059** Attempt the transfer optimization on INSERTs of the form
86060**
86061**     INSERT INTO tab1 SELECT * FROM tab2;
86062**
86063** This optimization is only attempted if
86064**
86065**    (1)  tab1 and tab2 have identical schemas including all the
86066**         same indices and constraints
86067**
86068**    (2)  tab1 and tab2 are different tables
86069**
86070**    (3)  There must be no triggers on tab1
86071**
86072**    (4)  The result set of the SELECT statement is "*"
86073**
86074**    (5)  The SELECT statement has no WHERE, HAVING, ORDER BY, GROUP BY,
86075**         or LIMIT clause.
86076**
86077**    (6)  The SELECT statement is a simple (not a compound) select that
86078**         contains only tab2 in its FROM clause
86079**
86080** This method for implementing the INSERT transfers raw records from
86081** tab2 over to tab1.  The columns are not decoded.  Raw records from
86082** the indices of tab2 are transfered to tab1 as well.  In so doing,
86083** the resulting tab1 has much less fragmentation.
86084**
86085** This routine returns TRUE if the optimization is attempted.  If any
86086** of the conditions above fail so that the optimization should not
86087** be attempted, then this routine returns FALSE.
86088*/
86089static int xferOptimization(
86090  Parse *pParse,        /* Parser context */
86091  Table *pDest,         /* The table we are inserting into */
86092  Select *pSelect,      /* A SELECT statement to use as the data source */
86093  int onError,          /* How to handle constraint errors */
86094  int iDbDest           /* The database of pDest */
86095){
86096  ExprList *pEList;                /* The result set of the SELECT */
86097  Table *pSrc;                     /* The table in the FROM clause of SELECT */
86098  Index *pSrcIdx, *pDestIdx;       /* Source and destination indices */
86099  struct SrcList_item *pItem;      /* An element of pSelect->pSrc */
86100  int i;                           /* Loop counter */
86101  int iDbSrc;                      /* The database of pSrc */
86102  int iSrc, iDest;                 /* Cursors from source and destination */
86103  int addr1, addr2;                /* Loop addresses */
86104  int emptyDestTest;               /* Address of test for empty pDest */
86105  int emptySrcTest;                /* Address of test for empty pSrc */
86106  Vdbe *v;                         /* The VDBE we are building */
86107  KeyInfo *pKey;                   /* Key information for an index */
86108  int regAutoinc;                  /* Memory register used by AUTOINC */
86109  int destHasUniqueIdx = 0;        /* True if pDest has a UNIQUE index */
86110  int regData, regRowid;           /* Registers holding data and rowid */
86111
86112  if( pSelect==0 ){
86113    return 0;   /* Must be of the form  INSERT INTO ... SELECT ... */
86114  }
86115  if( sqlite3TriggerList(pParse, pDest) ){
86116    return 0;   /* tab1 must not have triggers */
86117  }
86118#ifndef SQLITE_OMIT_VIRTUALTABLE
86119  if( pDest->tabFlags & TF_Virtual ){
86120    return 0;   /* tab1 must not be a virtual table */
86121  }
86122#endif
86123  if( onError==OE_Default ){
86124    onError = OE_Abort;
86125  }
86126  if( onError!=OE_Abort && onError!=OE_Rollback ){
86127    return 0;   /* Cannot do OR REPLACE or OR IGNORE or OR FAIL */
86128  }
86129  assert(pSelect->pSrc);   /* allocated even if there is no FROM clause */
86130  if( pSelect->pSrc->nSrc!=1 ){
86131    return 0;   /* FROM clause must have exactly one term */
86132  }
86133  if( pSelect->pSrc->a[0].pSelect ){
86134    return 0;   /* FROM clause cannot contain a subquery */
86135  }
86136  if( pSelect->pWhere ){
86137    return 0;   /* SELECT may not have a WHERE clause */
86138  }
86139  if( pSelect->pOrderBy ){
86140    return 0;   /* SELECT may not have an ORDER BY clause */
86141  }
86142  /* Do not need to test for a HAVING clause.  If HAVING is present but
86143  ** there is no ORDER BY, we will get an error. */
86144  if( pSelect->pGroupBy ){
86145    return 0;   /* SELECT may not have a GROUP BY clause */
86146  }
86147  if( pSelect->pLimit ){
86148    return 0;   /* SELECT may not have a LIMIT clause */
86149  }
86150  assert( pSelect->pOffset==0 );  /* Must be so if pLimit==0 */
86151  if( pSelect->pPrior ){
86152    return 0;   /* SELECT may not be a compound query */
86153  }
86154  if( pSelect->selFlags & SF_Distinct ){
86155    return 0;   /* SELECT may not be DISTINCT */
86156  }
86157  pEList = pSelect->pEList;
86158  assert( pEList!=0 );
86159  if( pEList->nExpr!=1 ){
86160    return 0;   /* The result set must have exactly one column */
86161  }
86162  assert( pEList->a[0].pExpr );
86163  if( pEList->a[0].pExpr->op!=TK_ALL ){
86164    return 0;   /* The result set must be the special operator "*" */
86165  }
86166
86167  /* At this point we have established that the statement is of the
86168  ** correct syntactic form to participate in this optimization.  Now
86169  ** we have to check the semantics.
86170  */
86171  pItem = pSelect->pSrc->a;
86172  pSrc = sqlite3LocateTable(pParse, 0, pItem->zName, pItem->zDatabase);
86173  if( pSrc==0 ){
86174    return 0;   /* FROM clause does not contain a real table */
86175  }
86176  if( pSrc==pDest ){
86177    return 0;   /* tab1 and tab2 may not be the same table */
86178  }
86179#ifndef SQLITE_OMIT_VIRTUALTABLE
86180  if( pSrc->tabFlags & TF_Virtual ){
86181    return 0;   /* tab2 must not be a virtual table */
86182  }
86183#endif
86184  if( pSrc->pSelect ){
86185    return 0;   /* tab2 may not be a view */
86186  }
86187  if( pDest->nCol!=pSrc->nCol ){
86188    return 0;   /* Number of columns must be the same in tab1 and tab2 */
86189  }
86190  if( pDest->iPKey!=pSrc->iPKey ){
86191    return 0;   /* Both tables must have the same INTEGER PRIMARY KEY */
86192  }
86193  for(i=0; i<pDest->nCol; i++){
86194    if( pDest->aCol[i].affinity!=pSrc->aCol[i].affinity ){
86195      return 0;    /* Affinity must be the same on all columns */
86196    }
86197    if( !xferCompatibleCollation(pDest->aCol[i].zColl, pSrc->aCol[i].zColl) ){
86198      return 0;    /* Collating sequence must be the same on all columns */
86199    }
86200    if( pDest->aCol[i].notNull && !pSrc->aCol[i].notNull ){
86201      return 0;    /* tab2 must be NOT NULL if tab1 is */
86202    }
86203  }
86204  for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
86205    if( pDestIdx->onError!=OE_None ){
86206      destHasUniqueIdx = 1;
86207    }
86208    for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){
86209      if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
86210    }
86211    if( pSrcIdx==0 ){
86212      return 0;    /* pDestIdx has no corresponding index in pSrc */
86213    }
86214  }
86215#ifndef SQLITE_OMIT_CHECK
86216  if( pDest->pCheck && sqlite3ExprCompare(pSrc->pCheck, pDest->pCheck) ){
86217    return 0;   /* Tables have different CHECK constraints.  Ticket #2252 */
86218  }
86219#endif
86220
86221  /* If we get this far, it means either:
86222  **
86223  **    *   We can always do the transfer if the table contains an
86224  **        an integer primary key
86225  **
86226  **    *   We can conditionally do the transfer if the destination
86227  **        table is empty.
86228  */
86229#ifdef SQLITE_TEST
86230  sqlite3_xferopt_count++;
86231#endif
86232  iDbSrc = sqlite3SchemaToIndex(pParse->db, pSrc->pSchema);
86233  v = sqlite3GetVdbe(pParse);
86234  sqlite3CodeVerifySchema(pParse, iDbSrc);
86235  iSrc = pParse->nTab++;
86236  iDest = pParse->nTab++;
86237  regAutoinc = autoIncBegin(pParse, iDbDest, pDest);
86238  sqlite3OpenTable(pParse, iDest, iDbDest, pDest, OP_OpenWrite);
86239  if( (pDest->iPKey<0 && pDest->pIndex!=0) || destHasUniqueIdx ){
86240    /* If tables do not have an INTEGER PRIMARY KEY and there
86241    ** are indices to be copied and the destination is not empty,
86242    ** we have to disallow the transfer optimization because the
86243    ** the rowids might change which will mess up indexing.
86244    **
86245    ** Or if the destination has a UNIQUE index and is not empty,
86246    ** we also disallow the transfer optimization because we cannot
86247    ** insure that all entries in the union of DEST and SRC will be
86248    ** unique.
86249    */
86250    addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iDest, 0);
86251    emptyDestTest = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
86252    sqlite3VdbeJumpHere(v, addr1);
86253  }else{
86254    emptyDestTest = 0;
86255  }
86256  sqlite3OpenTable(pParse, iSrc, iDbSrc, pSrc, OP_OpenRead);
86257  emptySrcTest = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0);
86258  regData = sqlite3GetTempReg(pParse);
86259  regRowid = sqlite3GetTempReg(pParse);
86260  if( pDest->iPKey>=0 ){
86261    addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
86262    addr2 = sqlite3VdbeAddOp3(v, OP_NotExists, iDest, 0, regRowid);
86263    sqlite3HaltConstraint(
86264        pParse, onError, "PRIMARY KEY must be unique", P4_STATIC);
86265    sqlite3VdbeJumpHere(v, addr2);
86266    autoIncStep(pParse, regAutoinc, regRowid);
86267  }else if( pDest->pIndex==0 ){
86268    addr1 = sqlite3VdbeAddOp2(v, OP_NewRowid, iDest, regRowid);
86269  }else{
86270    addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
86271    assert( (pDest->tabFlags & TF_Autoincrement)==0 );
86272  }
86273  sqlite3VdbeAddOp2(v, OP_RowData, iSrc, regData);
86274  sqlite3VdbeAddOp3(v, OP_Insert, iDest, regData, regRowid);
86275  sqlite3VdbeChangeP5(v, OPFLAG_NCHANGE|OPFLAG_LASTROWID|OPFLAG_APPEND);
86276  sqlite3VdbeChangeP4(v, -1, pDest->zName, 0);
86277  sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1);
86278  for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
86279    for(pSrcIdx=pSrc->pIndex; ALWAYS(pSrcIdx); pSrcIdx=pSrcIdx->pNext){
86280      if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
86281    }
86282    assert( pSrcIdx );
86283    sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
86284    sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
86285    pKey = sqlite3IndexKeyinfo(pParse, pSrcIdx);
86286    sqlite3VdbeAddOp4(v, OP_OpenRead, iSrc, pSrcIdx->tnum, iDbSrc,
86287                      (char*)pKey, P4_KEYINFO_HANDOFF);
86288    VdbeComment((v, "%s", pSrcIdx->zName));
86289    pKey = sqlite3IndexKeyinfo(pParse, pDestIdx);
86290    sqlite3VdbeAddOp4(v, OP_OpenWrite, iDest, pDestIdx->tnum, iDbDest,
86291                      (char*)pKey, P4_KEYINFO_HANDOFF);
86292    VdbeComment((v, "%s", pDestIdx->zName));
86293    addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0);
86294    sqlite3VdbeAddOp2(v, OP_RowKey, iSrc, regData);
86295    sqlite3VdbeAddOp3(v, OP_IdxInsert, iDest, regData, 1);
86296    sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1+1);
86297    sqlite3VdbeJumpHere(v, addr1);
86298  }
86299  sqlite3VdbeJumpHere(v, emptySrcTest);
86300  sqlite3ReleaseTempReg(pParse, regRowid);
86301  sqlite3ReleaseTempReg(pParse, regData);
86302  sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
86303  sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
86304  if( emptyDestTest ){
86305    sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_OK, 0);
86306    sqlite3VdbeJumpHere(v, emptyDestTest);
86307    sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
86308    return 0;
86309  }else{
86310    return 1;
86311  }
86312}
86313#endif /* SQLITE_OMIT_XFER_OPT */
86314
86315/************** End of insert.c **********************************************/
86316/************** Begin file legacy.c ******************************************/
86317/*
86318** 2001 September 15
86319**
86320** The author disclaims copyright to this source code.  In place of
86321** a legal notice, here is a blessing:
86322**
86323**    May you do good and not evil.
86324**    May you find forgiveness for yourself and forgive others.
86325**    May you share freely, never taking more than you give.
86326**
86327*************************************************************************
86328** Main file for the SQLite library.  The routines in this file
86329** implement the programmer interface to the library.  Routines in
86330** other files are for internal use by SQLite and should not be
86331** accessed by users of the library.
86332*/
86333
86334
86335/*
86336** Execute SQL code.  Return one of the SQLITE_ success/failure
86337** codes.  Also write an error message into memory obtained from
86338** malloc() and make *pzErrMsg point to that message.
86339**
86340** If the SQL is a query, then for each row in the query result
86341** the xCallback() function is called.  pArg becomes the first
86342** argument to xCallback().  If xCallback=NULL then no callback
86343** is invoked, even for queries.
86344*/
86345SQLITE_API int sqlite3_exec(
86346  sqlite3 *db,                /* The database on which the SQL executes */
86347  const char *zSql,           /* The SQL to be executed */
86348  sqlite3_callback xCallback, /* Invoke this callback routine */
86349  void *pArg,                 /* First argument to xCallback() */
86350  char **pzErrMsg             /* Write error messages here */
86351){
86352  int rc = SQLITE_OK;         /* Return code */
86353  const char *zLeftover;      /* Tail of unprocessed SQL */
86354  sqlite3_stmt *pStmt = 0;    /* The current SQL statement */
86355  char **azCols = 0;          /* Names of result columns */
86356  int nRetry = 0;             /* Number of retry attempts */
86357  int callbackIsInit;         /* True if callback data is initialized */
86358
86359  if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
86360  if( zSql==0 ) zSql = "";
86361
86362  sqlite3_mutex_enter(db->mutex);
86363  sqlite3Error(db, SQLITE_OK, 0);
86364  while( (rc==SQLITE_OK || (rc==SQLITE_SCHEMA && (++nRetry)<2)) && zSql[0] ){
86365    int nCol;
86366    char **azVals = 0;
86367
86368    pStmt = 0;
86369    rc = sqlite3_prepare(db, zSql, -1, &pStmt, &zLeftover);
86370    assert( rc==SQLITE_OK || pStmt==0 );
86371    if( rc!=SQLITE_OK ){
86372      continue;
86373    }
86374    if( !pStmt ){
86375      /* this happens for a comment or white-space */
86376      zSql = zLeftover;
86377      continue;
86378    }
86379
86380    callbackIsInit = 0;
86381    nCol = sqlite3_column_count(pStmt);
86382
86383    while( 1 ){
86384      int i;
86385      rc = sqlite3_step(pStmt);
86386
86387      /* Invoke the callback function if required */
86388      if( xCallback && (SQLITE_ROW==rc ||
86389          (SQLITE_DONE==rc && !callbackIsInit
86390                           && db->flags&SQLITE_NullCallback)) ){
86391        if( !callbackIsInit ){
86392          azCols = sqlite3DbMallocZero(db, 2*nCol*sizeof(const char*) + 1);
86393          if( azCols==0 ){
86394            goto exec_out;
86395          }
86396          for(i=0; i<nCol; i++){
86397            azCols[i] = (char *)sqlite3_column_name(pStmt, i);
86398            /* sqlite3VdbeSetColName() installs column names as UTF8
86399            ** strings so there is no way for sqlite3_column_name() to fail. */
86400            assert( azCols[i]!=0 );
86401          }
86402          callbackIsInit = 1;
86403        }
86404        if( rc==SQLITE_ROW ){
86405          azVals = &azCols[nCol];
86406          for(i=0; i<nCol; i++){
86407            azVals[i] = (char *)sqlite3_column_text(pStmt, i);
86408            if( !azVals[i] && sqlite3_column_type(pStmt, i)!=SQLITE_NULL ){
86409              db->mallocFailed = 1;
86410              goto exec_out;
86411            }
86412          }
86413        }
86414        if( xCallback(pArg, nCol, azVals, azCols) ){
86415          rc = SQLITE_ABORT;
86416          sqlite3VdbeFinalize((Vdbe *)pStmt);
86417          pStmt = 0;
86418          sqlite3Error(db, SQLITE_ABORT, 0);
86419          goto exec_out;
86420        }
86421      }
86422
86423      if( rc!=SQLITE_ROW ){
86424        rc = sqlite3VdbeFinalize((Vdbe *)pStmt);
86425        pStmt = 0;
86426        if( rc!=SQLITE_SCHEMA ){
86427          nRetry = 0;
86428          zSql = zLeftover;
86429          while( sqlite3Isspace(zSql[0]) ) zSql++;
86430        }
86431        break;
86432      }
86433    }
86434
86435    sqlite3DbFree(db, azCols);
86436    azCols = 0;
86437  }
86438
86439exec_out:
86440  if( pStmt ) sqlite3VdbeFinalize((Vdbe *)pStmt);
86441  sqlite3DbFree(db, azCols);
86442
86443  rc = sqlite3ApiExit(db, rc);
86444  if( rc!=SQLITE_OK && ALWAYS(rc==sqlite3_errcode(db)) && pzErrMsg ){
86445    int nErrMsg = 1 + sqlite3Strlen30(sqlite3_errmsg(db));
86446    *pzErrMsg = sqlite3Malloc(nErrMsg);
86447    if( *pzErrMsg ){
86448      memcpy(*pzErrMsg, sqlite3_errmsg(db), nErrMsg);
86449    }else{
86450      rc = SQLITE_NOMEM;
86451      sqlite3Error(db, SQLITE_NOMEM, 0);
86452    }
86453  }else if( pzErrMsg ){
86454    *pzErrMsg = 0;
86455  }
86456
86457  assert( (rc&db->errMask)==rc );
86458  sqlite3_mutex_leave(db->mutex);
86459  return rc;
86460}
86461
86462/************** End of legacy.c **********************************************/
86463/************** Begin file loadext.c *****************************************/
86464/*
86465** 2006 June 7
86466**
86467** The author disclaims copyright to this source code.  In place of
86468** a legal notice, here is a blessing:
86469**
86470**    May you do good and not evil.
86471**    May you find forgiveness for yourself and forgive others.
86472**    May you share freely, never taking more than you give.
86473**
86474*************************************************************************
86475** This file contains code used to dynamically load extensions into
86476** the SQLite library.
86477*/
86478
86479#ifndef SQLITE_CORE
86480  #define SQLITE_CORE 1  /* Disable the API redefinition in sqlite3ext.h */
86481#endif
86482/************** Include sqlite3ext.h in the middle of loadext.c **************/
86483/************** Begin file sqlite3ext.h **************************************/
86484/*
86485** 2006 June 7
86486**
86487** The author disclaims copyright to this source code.  In place of
86488** a legal notice, here is a blessing:
86489**
86490**    May you do good and not evil.
86491**    May you find forgiveness for yourself and forgive others.
86492**    May you share freely, never taking more than you give.
86493**
86494*************************************************************************
86495** This header file defines the SQLite interface for use by
86496** shared libraries that want to be imported as extensions into
86497** an SQLite instance.  Shared libraries that intend to be loaded
86498** as extensions by SQLite should #include this file instead of
86499** sqlite3.h.
86500*/
86501#ifndef _SQLITE3EXT_H_
86502#define _SQLITE3EXT_H_
86503
86504typedef struct sqlite3_api_routines sqlite3_api_routines;
86505
86506/*
86507** The following structure holds pointers to all of the SQLite API
86508** routines.
86509**
86510** WARNING:  In order to maintain backwards compatibility, add new
86511** interfaces to the end of this structure only.  If you insert new
86512** interfaces in the middle of this structure, then older different
86513** versions of SQLite will not be able to load each others' shared
86514** libraries!
86515*/
86516struct sqlite3_api_routines {
86517  void * (*aggregate_context)(sqlite3_context*,int nBytes);
86518  int  (*aggregate_count)(sqlite3_context*);
86519  int  (*bind_blob)(sqlite3_stmt*,int,const void*,int n,void(*)(void*));
86520  int  (*bind_double)(sqlite3_stmt*,int,double);
86521  int  (*bind_int)(sqlite3_stmt*,int,int);
86522  int  (*bind_int64)(sqlite3_stmt*,int,sqlite_int64);
86523  int  (*bind_null)(sqlite3_stmt*,int);
86524  int  (*bind_parameter_count)(sqlite3_stmt*);
86525  int  (*bind_parameter_index)(sqlite3_stmt*,const char*zName);
86526  const char * (*bind_parameter_name)(sqlite3_stmt*,int);
86527  int  (*bind_text)(sqlite3_stmt*,int,const char*,int n,void(*)(void*));
86528  int  (*bind_text16)(sqlite3_stmt*,int,const void*,int,void(*)(void*));
86529  int  (*bind_value)(sqlite3_stmt*,int,const sqlite3_value*);
86530  int  (*busy_handler)(sqlite3*,int(*)(void*,int),void*);
86531  int  (*busy_timeout)(sqlite3*,int ms);
86532  int  (*changes)(sqlite3*);
86533  int  (*close)(sqlite3*);
86534  int  (*collation_needed)(sqlite3*,void*,void(*)(void*,sqlite3*,int eTextRep,const char*));
86535  int  (*collation_needed16)(sqlite3*,void*,void(*)(void*,sqlite3*,int eTextRep,const void*));
86536  const void * (*column_blob)(sqlite3_stmt*,int iCol);
86537  int  (*column_bytes)(sqlite3_stmt*,int iCol);
86538  int  (*column_bytes16)(sqlite3_stmt*,int iCol);
86539  int  (*column_count)(sqlite3_stmt*pStmt);
86540  const char * (*column_database_name)(sqlite3_stmt*,int);
86541  const void * (*column_database_name16)(sqlite3_stmt*,int);
86542  const char * (*column_decltype)(sqlite3_stmt*,int i);
86543  const void * (*column_decltype16)(sqlite3_stmt*,int);
86544  double  (*column_double)(sqlite3_stmt*,int iCol);
86545  int  (*column_int)(sqlite3_stmt*,int iCol);
86546  sqlite_int64  (*column_int64)(sqlite3_stmt*,int iCol);
86547  const char * (*column_name)(sqlite3_stmt*,int);
86548  const void * (*column_name16)(sqlite3_stmt*,int);
86549  const char * (*column_origin_name)(sqlite3_stmt*,int);
86550  const void * (*column_origin_name16)(sqlite3_stmt*,int);
86551  const char * (*column_table_name)(sqlite3_stmt*,int);
86552  const void * (*column_table_name16)(sqlite3_stmt*,int);
86553  const unsigned char * (*column_text)(sqlite3_stmt*,int iCol);
86554  const void * (*column_text16)(sqlite3_stmt*,int iCol);
86555  int  (*column_type)(sqlite3_stmt*,int iCol);
86556  sqlite3_value* (*column_value)(sqlite3_stmt*,int iCol);
86557  void * (*commit_hook)(sqlite3*,int(*)(void*),void*);
86558  int  (*complete)(const char*sql);
86559  int  (*complete16)(const void*sql);
86560  int  (*create_collation)(sqlite3*,const char*,int,void*,int(*)(void*,int,const void*,int,const void*));
86561  int  (*create_collation16)(sqlite3*,const void*,int,void*,int(*)(void*,int,const void*,int,const void*));
86562  int  (*create_function)(sqlite3*,const char*,int,int,void*,void (*xFunc)(sqlite3_context*,int,sqlite3_value**),void (*xStep)(sqlite3_context*,int,sqlite3_value**),void (*xFinal)(sqlite3_context*));
86563  int  (*create_function16)(sqlite3*,const void*,int,int,void*,void (*xFunc)(sqlite3_context*,int,sqlite3_value**),void (*xStep)(sqlite3_context*,int,sqlite3_value**),void (*xFinal)(sqlite3_context*));
86564  int (*create_module)(sqlite3*,const char*,const sqlite3_module*,void*);
86565  int  (*data_count)(sqlite3_stmt*pStmt);
86566  sqlite3 * (*db_handle)(sqlite3_stmt*);
86567  int (*declare_vtab)(sqlite3*,const char*);
86568  int  (*enable_shared_cache)(int);
86569  int  (*errcode)(sqlite3*db);
86570  const char * (*errmsg)(sqlite3*);
86571  const void * (*errmsg16)(sqlite3*);
86572  int  (*exec)(sqlite3*,const char*,sqlite3_callback,void*,char**);
86573  int  (*expired)(sqlite3_stmt*);
86574  int  (*finalize)(sqlite3_stmt*pStmt);
86575  void  (*free)(void*);
86576  void  (*free_table)(char**result);
86577  int  (*get_autocommit)(sqlite3*);
86578  void * (*get_auxdata)(sqlite3_context*,int);
86579  int  (*get_table)(sqlite3*,const char*,char***,int*,int*,char**);
86580  int  (*global_recover)(void);
86581  void  (*interruptx)(sqlite3*);
86582  sqlite_int64  (*last_insert_rowid)(sqlite3*);
86583  const char * (*libversion)(void);
86584  int  (*libversion_number)(void);
86585  void *(*malloc)(int);
86586  char * (*mprintf)(const char*,...);
86587  int  (*open)(const char*,sqlite3**);
86588  int  (*open16)(const void*,sqlite3**);
86589  int  (*prepare)(sqlite3*,const char*,int,sqlite3_stmt**,const char**);
86590  int  (*prepare16)(sqlite3*,const void*,int,sqlite3_stmt**,const void**);
86591  void * (*profile)(sqlite3*,void(*)(void*,const char*,sqlite_uint64),void*);
86592  void  (*progress_handler)(sqlite3*,int,int(*)(void*),void*);
86593  void *(*realloc)(void*,int);
86594  int  (*reset)(sqlite3_stmt*pStmt);
86595  void  (*result_blob)(sqlite3_context*,const void*,int,void(*)(void*));
86596  void  (*result_double)(sqlite3_context*,double);
86597  void  (*result_error)(sqlite3_context*,const char*,int);
86598  void  (*result_error16)(sqlite3_context*,const void*,int);
86599  void  (*result_int)(sqlite3_context*,int);
86600  void  (*result_int64)(sqlite3_context*,sqlite_int64);
86601  void  (*result_null)(sqlite3_context*);
86602  void  (*result_text)(sqlite3_context*,const char*,int,void(*)(void*));
86603  void  (*result_text16)(sqlite3_context*,const void*,int,void(*)(void*));
86604  void  (*result_text16be)(sqlite3_context*,const void*,int,void(*)(void*));
86605  void  (*result_text16le)(sqlite3_context*,const void*,int,void(*)(void*));
86606  void  (*result_value)(sqlite3_context*,sqlite3_value*);
86607  void * (*rollback_hook)(sqlite3*,void(*)(void*),void*);
86608  int  (*set_authorizer)(sqlite3*,int(*)(void*,int,const char*,const char*,const char*,const char*),void*);
86609  void  (*set_auxdata)(sqlite3_context*,int,void*,void (*)(void*));
86610  char * (*snprintf)(int,char*,const char*,...);
86611  int  (*step)(sqlite3_stmt*);
86612  int  (*table_column_metadata)(sqlite3*,const char*,const char*,const char*,char const**,char const**,int*,int*,int*);
86613  void  (*thread_cleanup)(void);
86614  int  (*total_changes)(sqlite3*);
86615  void * (*trace)(sqlite3*,void(*xTrace)(void*,const char*),void*);
86616  int  (*transfer_bindings)(sqlite3_stmt*,sqlite3_stmt*);
86617  void * (*update_hook)(sqlite3*,void(*)(void*,int ,char const*,char const*,sqlite_int64),void*);
86618  void * (*user_data)(sqlite3_context*);
86619  const void * (*value_blob)(sqlite3_value*);
86620  int  (*value_bytes)(sqlite3_value*);
86621  int  (*value_bytes16)(sqlite3_value*);
86622  double  (*value_double)(sqlite3_value*);
86623  int  (*value_int)(sqlite3_value*);
86624  sqlite_int64  (*value_int64)(sqlite3_value*);
86625  int  (*value_numeric_type)(sqlite3_value*);
86626  const unsigned char * (*value_text)(sqlite3_value*);
86627  const void * (*value_text16)(sqlite3_value*);
86628  const void * (*value_text16be)(sqlite3_value*);
86629  const void * (*value_text16le)(sqlite3_value*);
86630  int  (*value_type)(sqlite3_value*);
86631  char *(*vmprintf)(const char*,va_list);
86632  /* Added ??? */
86633  int (*overload_function)(sqlite3*, const char *zFuncName, int nArg);
86634  /* Added by 3.3.13 */
86635  int (*prepare_v2)(sqlite3*,const char*,int,sqlite3_stmt**,const char**);
86636  int (*prepare16_v2)(sqlite3*,const void*,int,sqlite3_stmt**,const void**);
86637  int (*clear_bindings)(sqlite3_stmt*);
86638  /* Added by 3.4.1 */
86639  int (*create_module_v2)(sqlite3*,const char*,const sqlite3_module*,void*,void (*xDestroy)(void *));
86640  /* Added by 3.5.0 */
86641  int (*bind_zeroblob)(sqlite3_stmt*,int,int);
86642  int (*blob_bytes)(sqlite3_blob*);
86643  int (*blob_close)(sqlite3_blob*);
86644  int (*blob_open)(sqlite3*,const char*,const char*,const char*,sqlite3_int64,int,sqlite3_blob**);
86645  int (*blob_read)(sqlite3_blob*,void*,int,int);
86646  int (*blob_write)(sqlite3_blob*,const void*,int,int);
86647  int (*create_collation_v2)(sqlite3*,const char*,int,void*,int(*)(void*,int,const void*,int,const void*),void(*)(void*));
86648  int (*file_control)(sqlite3*,const char*,int,void*);
86649  sqlite3_int64 (*memory_highwater)(int);
86650  sqlite3_int64 (*memory_used)(void);
86651  sqlite3_mutex *(*mutex_alloc)(int);
86652  void (*mutex_enter)(sqlite3_mutex*);
86653  void (*mutex_free)(sqlite3_mutex*);
86654  void (*mutex_leave)(sqlite3_mutex*);
86655  int (*mutex_try)(sqlite3_mutex*);
86656  int (*open_v2)(const char*,sqlite3**,int,const char*);
86657  int (*release_memory)(int);
86658  void (*result_error_nomem)(sqlite3_context*);
86659  void (*result_error_toobig)(sqlite3_context*);
86660  int (*sleep)(int);
86661  void (*soft_heap_limit)(int);
86662  sqlite3_vfs *(*vfs_find)(const char*);
86663  int (*vfs_register)(sqlite3_vfs*,int);
86664  int (*vfs_unregister)(sqlite3_vfs*);
86665  int (*xthreadsafe)(void);
86666  void (*result_zeroblob)(sqlite3_context*,int);
86667  void (*result_error_code)(sqlite3_context*,int);
86668  int (*test_control)(int, ...);
86669  void (*randomness)(int,void*);
86670  sqlite3 *(*context_db_handle)(sqlite3_context*);
86671  int (*extended_result_codes)(sqlite3*,int);
86672  int (*limit)(sqlite3*,int,int);
86673  sqlite3_stmt *(*next_stmt)(sqlite3*,sqlite3_stmt*);
86674  const char *(*sql)(sqlite3_stmt*);
86675  int (*status)(int,int*,int*,int);
86676  int (*backup_finish)(sqlite3_backup*);
86677  sqlite3_backup *(*backup_init)(sqlite3*,const char*,sqlite3*,const char*);
86678  int (*backup_pagecount)(sqlite3_backup*);
86679  int (*backup_remaining)(sqlite3_backup*);
86680  int (*backup_step)(sqlite3_backup*,int);
86681  const char *(*compileoption_get)(int);
86682  int (*compileoption_used)(const char*);
86683  int (*create_function_v2)(sqlite3*,const char*,int,int,void*,void (*xFunc)(sqlite3_context*,int,sqlite3_value**),void (*xStep)(sqlite3_context*,int,sqlite3_value**),void (*xFinal)(sqlite3_context*),void(*xDestroy)(void*));
86684  int (*db_config)(sqlite3*,int,...);
86685  sqlite3_mutex *(*db_mutex)(sqlite3*);
86686  int (*db_status)(sqlite3*,int,int*,int*,int);
86687  int (*extended_errcode)(sqlite3*);
86688  void (*log)(int,const char*,...);
86689  sqlite3_int64 (*soft_heap_limit64)(sqlite3_int64);
86690  const char *(*sourceid)(void);
86691  int (*stmt_status)(sqlite3_stmt*,int,int);
86692  int (*strnicmp)(const char*,const char*,int);
86693  int (*unlock_notify)(sqlite3*,void(*)(void**,int),void*);
86694  int (*wal_autocheckpoint)(sqlite3*,int);
86695  int (*wal_checkpoint)(sqlite3*,const char*);
86696  void *(*wal_hook)(sqlite3*,int(*)(void*,sqlite3*,const char*,int),void*);
86697};
86698
86699/*
86700** The following macros redefine the API routines so that they are
86701** redirected throught the global sqlite3_api structure.
86702**
86703** This header file is also used by the loadext.c source file
86704** (part of the main SQLite library - not an extension) so that
86705** it can get access to the sqlite3_api_routines structure
86706** definition.  But the main library does not want to redefine
86707** the API.  So the redefinition macros are only valid if the
86708** SQLITE_CORE macros is undefined.
86709*/
86710#ifndef SQLITE_CORE
86711#define sqlite3_aggregate_context      sqlite3_api->aggregate_context
86712#ifndef SQLITE_OMIT_DEPRECATED
86713#define sqlite3_aggregate_count        sqlite3_api->aggregate_count
86714#endif
86715#define sqlite3_bind_blob              sqlite3_api->bind_blob
86716#define sqlite3_bind_double            sqlite3_api->bind_double
86717#define sqlite3_bind_int               sqlite3_api->bind_int
86718#define sqlite3_bind_int64             sqlite3_api->bind_int64
86719#define sqlite3_bind_null              sqlite3_api->bind_null
86720#define sqlite3_bind_parameter_count   sqlite3_api->bind_parameter_count
86721#define sqlite3_bind_parameter_index   sqlite3_api->bind_parameter_index
86722#define sqlite3_bind_parameter_name    sqlite3_api->bind_parameter_name
86723#define sqlite3_bind_text              sqlite3_api->bind_text
86724#define sqlite3_bind_text16            sqlite3_api->bind_text16
86725#define sqlite3_bind_value             sqlite3_api->bind_value
86726#define sqlite3_busy_handler           sqlite3_api->busy_handler
86727#define sqlite3_busy_timeout           sqlite3_api->busy_timeout
86728#define sqlite3_changes                sqlite3_api->changes
86729#define sqlite3_close                  sqlite3_api->close
86730#define sqlite3_collation_needed       sqlite3_api->collation_needed
86731#define sqlite3_collation_needed16     sqlite3_api->collation_needed16
86732#define sqlite3_column_blob            sqlite3_api->column_blob
86733#define sqlite3_column_bytes           sqlite3_api->column_bytes
86734#define sqlite3_column_bytes16         sqlite3_api->column_bytes16
86735#define sqlite3_column_count           sqlite3_api->column_count
86736#define sqlite3_column_database_name   sqlite3_api->column_database_name
86737#define sqlite3_column_database_name16 sqlite3_api->column_database_name16
86738#define sqlite3_column_decltype        sqlite3_api->column_decltype
86739#define sqlite3_column_decltype16      sqlite3_api->column_decltype16
86740#define sqlite3_column_double          sqlite3_api->column_double
86741#define sqlite3_column_int             sqlite3_api->column_int
86742#define sqlite3_column_int64           sqlite3_api->column_int64
86743#define sqlite3_column_name            sqlite3_api->column_name
86744#define sqlite3_column_name16          sqlite3_api->column_name16
86745#define sqlite3_column_origin_name     sqlite3_api->column_origin_name
86746#define sqlite3_column_origin_name16   sqlite3_api->column_origin_name16
86747#define sqlite3_column_table_name      sqlite3_api->column_table_name
86748#define sqlite3_column_table_name16    sqlite3_api->column_table_name16
86749#define sqlite3_column_text            sqlite3_api->column_text
86750#define sqlite3_column_text16          sqlite3_api->column_text16
86751#define sqlite3_column_type            sqlite3_api->column_type
86752#define sqlite3_column_value           sqlite3_api->column_value
86753#define sqlite3_commit_hook            sqlite3_api->commit_hook
86754#define sqlite3_complete               sqlite3_api->complete
86755#define sqlite3_complete16             sqlite3_api->complete16
86756#define sqlite3_create_collation       sqlite3_api->create_collation
86757#define sqlite3_create_collation16     sqlite3_api->create_collation16
86758#define sqlite3_create_function        sqlite3_api->create_function
86759#define sqlite3_create_function16      sqlite3_api->create_function16
86760#define sqlite3_create_module          sqlite3_api->create_module
86761#define sqlite3_create_module_v2       sqlite3_api->create_module_v2
86762#define sqlite3_data_count             sqlite3_api->data_count
86763#define sqlite3_db_handle              sqlite3_api->db_handle
86764#define sqlite3_declare_vtab           sqlite3_api->declare_vtab
86765#define sqlite3_enable_shared_cache    sqlite3_api->enable_shared_cache
86766#define sqlite3_errcode                sqlite3_api->errcode
86767#define sqlite3_errmsg                 sqlite3_api->errmsg
86768#define sqlite3_errmsg16               sqlite3_api->errmsg16
86769#define sqlite3_exec                   sqlite3_api->exec
86770#ifndef SQLITE_OMIT_DEPRECATED
86771#define sqlite3_expired                sqlite3_api->expired
86772#endif
86773#define sqlite3_finalize               sqlite3_api->finalize
86774#define sqlite3_free                   sqlite3_api->free
86775#define sqlite3_free_table             sqlite3_api->free_table
86776#define sqlite3_get_autocommit         sqlite3_api->get_autocommit
86777#define sqlite3_get_auxdata            sqlite3_api->get_auxdata
86778#define sqlite3_get_table              sqlite3_api->get_table
86779#ifndef SQLITE_OMIT_DEPRECATED
86780#define sqlite3_global_recover         sqlite3_api->global_recover
86781#endif
86782#define sqlite3_interrupt              sqlite3_api->interruptx
86783#define sqlite3_last_insert_rowid      sqlite3_api->last_insert_rowid
86784#define sqlite3_libversion             sqlite3_api->libversion
86785#define sqlite3_libversion_number      sqlite3_api->libversion_number
86786#define sqlite3_malloc                 sqlite3_api->malloc
86787#define sqlite3_mprintf                sqlite3_api->mprintf
86788#define sqlite3_open                   sqlite3_api->open
86789#define sqlite3_open16                 sqlite3_api->open16
86790#define sqlite3_prepare                sqlite3_api->prepare
86791#define sqlite3_prepare16              sqlite3_api->prepare16
86792#define sqlite3_prepare_v2             sqlite3_api->prepare_v2
86793#define sqlite3_prepare16_v2           sqlite3_api->prepare16_v2
86794#define sqlite3_profile                sqlite3_api->profile
86795#define sqlite3_progress_handler       sqlite3_api->progress_handler
86796#define sqlite3_realloc                sqlite3_api->realloc
86797#define sqlite3_reset                  sqlite3_api->reset
86798#define sqlite3_result_blob            sqlite3_api->result_blob
86799#define sqlite3_result_double          sqlite3_api->result_double
86800#define sqlite3_result_error           sqlite3_api->result_error
86801#define sqlite3_result_error16         sqlite3_api->result_error16
86802#define sqlite3_result_int             sqlite3_api->result_int
86803#define sqlite3_result_int64           sqlite3_api->result_int64
86804#define sqlite3_result_null            sqlite3_api->result_null
86805#define sqlite3_result_text            sqlite3_api->result_text
86806#define sqlite3_result_text16          sqlite3_api->result_text16
86807#define sqlite3_result_text16be        sqlite3_api->result_text16be
86808#define sqlite3_result_text16le        sqlite3_api->result_text16le
86809#define sqlite3_result_value           sqlite3_api->result_value
86810#define sqlite3_rollback_hook          sqlite3_api->rollback_hook
86811#define sqlite3_set_authorizer         sqlite3_api->set_authorizer
86812#define sqlite3_set_auxdata            sqlite3_api->set_auxdata
86813#define sqlite3_snprintf               sqlite3_api->snprintf
86814#define sqlite3_step                   sqlite3_api->step
86815#define sqlite3_table_column_metadata  sqlite3_api->table_column_metadata
86816#define sqlite3_thread_cleanup         sqlite3_api->thread_cleanup
86817#define sqlite3_total_changes          sqlite3_api->total_changes
86818#define sqlite3_trace                  sqlite3_api->trace
86819#ifndef SQLITE_OMIT_DEPRECATED
86820#define sqlite3_transfer_bindings      sqlite3_api->transfer_bindings
86821#endif
86822#define sqlite3_update_hook            sqlite3_api->update_hook
86823#define sqlite3_user_data              sqlite3_api->user_data
86824#define sqlite3_value_blob             sqlite3_api->value_blob
86825#define sqlite3_value_bytes            sqlite3_api->value_bytes
86826#define sqlite3_value_bytes16          sqlite3_api->value_bytes16
86827#define sqlite3_value_double           sqlite3_api->value_double
86828#define sqlite3_value_int              sqlite3_api->value_int
86829#define sqlite3_value_int64            sqlite3_api->value_int64
86830#define sqlite3_value_numeric_type     sqlite3_api->value_numeric_type
86831#define sqlite3_value_text             sqlite3_api->value_text
86832#define sqlite3_value_text16           sqlite3_api->value_text16
86833#define sqlite3_value_text16be         sqlite3_api->value_text16be
86834#define sqlite3_value_text16le         sqlite3_api->value_text16le
86835#define sqlite3_value_type             sqlite3_api->value_type
86836#define sqlite3_vmprintf               sqlite3_api->vmprintf
86837#define sqlite3_overload_function      sqlite3_api->overload_function
86838#define sqlite3_prepare_v2             sqlite3_api->prepare_v2
86839#define sqlite3_prepare16_v2           sqlite3_api->prepare16_v2
86840#define sqlite3_clear_bindings         sqlite3_api->clear_bindings
86841#define sqlite3_bind_zeroblob          sqlite3_api->bind_zeroblob
86842#define sqlite3_blob_bytes             sqlite3_api->blob_bytes
86843#define sqlite3_blob_close             sqlite3_api->blob_close
86844#define sqlite3_blob_open              sqlite3_api->blob_open
86845#define sqlite3_blob_read              sqlite3_api->blob_read
86846#define sqlite3_blob_write             sqlite3_api->blob_write
86847#define sqlite3_create_collation_v2    sqlite3_api->create_collation_v2
86848#define sqlite3_file_control           sqlite3_api->file_control
86849#define sqlite3_memory_highwater       sqlite3_api->memory_highwater
86850#define sqlite3_memory_used            sqlite3_api->memory_used
86851#define sqlite3_mutex_alloc            sqlite3_api->mutex_alloc
86852#define sqlite3_mutex_enter            sqlite3_api->mutex_enter
86853#define sqlite3_mutex_free             sqlite3_api->mutex_free
86854#define sqlite3_mutex_leave            sqlite3_api->mutex_leave
86855#define sqlite3_mutex_try              sqlite3_api->mutex_try
86856#define sqlite3_open_v2                sqlite3_api->open_v2
86857#define sqlite3_release_memory         sqlite3_api->release_memory
86858#define sqlite3_result_error_nomem     sqlite3_api->result_error_nomem
86859#define sqlite3_result_error_toobig    sqlite3_api->result_error_toobig
86860#define sqlite3_sleep                  sqlite3_api->sleep
86861#define sqlite3_soft_heap_limit        sqlite3_api->soft_heap_limit
86862#define sqlite3_vfs_find               sqlite3_api->vfs_find
86863#define sqlite3_vfs_register           sqlite3_api->vfs_register
86864#define sqlite3_vfs_unregister         sqlite3_api->vfs_unregister
86865#define sqlite3_threadsafe             sqlite3_api->xthreadsafe
86866#define sqlite3_result_zeroblob        sqlite3_api->result_zeroblob
86867#define sqlite3_result_error_code      sqlite3_api->result_error_code
86868#define sqlite3_test_control           sqlite3_api->test_control
86869#define sqlite3_randomness             sqlite3_api->randomness
86870#define sqlite3_context_db_handle      sqlite3_api->context_db_handle
86871#define sqlite3_extended_result_codes  sqlite3_api->extended_result_codes
86872#define sqlite3_limit                  sqlite3_api->limit
86873#define sqlite3_next_stmt              sqlite3_api->next_stmt
86874#define sqlite3_sql                    sqlite3_api->sql
86875#define sqlite3_status                 sqlite3_api->status
86876#define sqlite3_backup_finish          sqlite3_api->backup_finish
86877#define sqlite3_backup_init            sqlite3_api->backup_init
86878#define sqlite3_backup_pagecount       sqlite3_api->backup_pagecount
86879#define sqlite3_backup_remaining       sqlite3_api->backup_remaining
86880#define sqlite3_backup_step            sqlite3_api->backup_step
86881#define sqlite3_compileoption_get      sqlite3_api->compileoption_get
86882#define sqlite3_compileoption_used     sqlite3_api->compileoption_used
86883#define sqlite3_create_function_v2     sqlite3_api->create_function_v2
86884#define sqlite3_db_config              sqlite3_api->db_config
86885#define sqlite3_db_mutex               sqlite3_api->db_mutex
86886#define sqlite3_db_status              sqlite3_api->db_status
86887#define sqlite3_extended_errcode       sqlite3_api->extended_errcode
86888#define sqlite3_log                    sqlite3_api->log
86889#define sqlite3_soft_heap_limit64      sqlite3_api->soft_heap_limit64
86890#define sqlite3_sourceid               sqlite3_api->sourceid
86891#define sqlite3_stmt_status            sqlite3_api->stmt_status
86892#define sqlite3_strnicmp               sqlite3_api->strnicmp
86893#define sqlite3_unlock_notify          sqlite3_api->unlock_notify
86894#define sqlite3_wal_autocheckpoint     sqlite3_api->wal_autocheckpoint
86895#define sqlite3_wal_checkpoint         sqlite3_api->wal_checkpoint
86896#define sqlite3_wal_hook               sqlite3_api->wal_hook
86897#endif /* SQLITE_CORE */
86898
86899#define SQLITE_EXTENSION_INIT1     const sqlite3_api_routines *sqlite3_api = 0;
86900#define SQLITE_EXTENSION_INIT2(v)  sqlite3_api = v;
86901
86902#endif /* _SQLITE3EXT_H_ */
86903
86904/************** End of sqlite3ext.h ******************************************/
86905/************** Continuing where we left off in loadext.c ********************/
86906
86907#ifndef SQLITE_OMIT_LOAD_EXTENSION
86908
86909/*
86910** Some API routines are omitted when various features are
86911** excluded from a build of SQLite.  Substitute a NULL pointer
86912** for any missing APIs.
86913*/
86914#ifndef SQLITE_ENABLE_COLUMN_METADATA
86915# define sqlite3_column_database_name   0
86916# define sqlite3_column_database_name16 0
86917# define sqlite3_column_table_name      0
86918# define sqlite3_column_table_name16    0
86919# define sqlite3_column_origin_name     0
86920# define sqlite3_column_origin_name16   0
86921# define sqlite3_table_column_metadata  0
86922#endif
86923
86924#ifdef SQLITE_OMIT_AUTHORIZATION
86925# define sqlite3_set_authorizer         0
86926#endif
86927
86928#ifdef SQLITE_OMIT_UTF16
86929# define sqlite3_bind_text16            0
86930# define sqlite3_collation_needed16     0
86931# define sqlite3_column_decltype16      0
86932# define sqlite3_column_name16          0
86933# define sqlite3_column_text16          0
86934# define sqlite3_complete16             0
86935# define sqlite3_create_collation16     0
86936# define sqlite3_create_function16      0
86937# define sqlite3_errmsg16               0
86938# define sqlite3_open16                 0
86939# define sqlite3_prepare16              0
86940# define sqlite3_prepare16_v2           0
86941# define sqlite3_result_error16         0
86942# define sqlite3_result_text16          0
86943# define sqlite3_result_text16be        0
86944# define sqlite3_result_text16le        0
86945# define sqlite3_value_text16           0
86946# define sqlite3_value_text16be         0
86947# define sqlite3_value_text16le         0
86948# define sqlite3_column_database_name16 0
86949# define sqlite3_column_table_name16    0
86950# define sqlite3_column_origin_name16   0
86951#endif
86952
86953#ifdef SQLITE_OMIT_COMPLETE
86954# define sqlite3_complete 0
86955# define sqlite3_complete16 0
86956#endif
86957
86958#ifdef SQLITE_OMIT_DECLTYPE
86959# define sqlite3_column_decltype16      0
86960# define sqlite3_column_decltype        0
86961#endif
86962
86963#ifdef SQLITE_OMIT_PROGRESS_CALLBACK
86964# define sqlite3_progress_handler 0
86965#endif
86966
86967#ifdef SQLITE_OMIT_VIRTUALTABLE
86968# define sqlite3_create_module 0
86969# define sqlite3_create_module_v2 0
86970# define sqlite3_declare_vtab 0
86971#endif
86972
86973#ifdef SQLITE_OMIT_SHARED_CACHE
86974# define sqlite3_enable_shared_cache 0
86975#endif
86976
86977#ifdef SQLITE_OMIT_TRACE
86978# define sqlite3_profile       0
86979# define sqlite3_trace         0
86980#endif
86981
86982#ifdef SQLITE_OMIT_GET_TABLE
86983# define sqlite3_free_table    0
86984# define sqlite3_get_table     0
86985#endif
86986
86987#ifdef SQLITE_OMIT_INCRBLOB
86988#define sqlite3_bind_zeroblob  0
86989#define sqlite3_blob_bytes     0
86990#define sqlite3_blob_close     0
86991#define sqlite3_blob_open      0
86992#define sqlite3_blob_read      0
86993#define sqlite3_blob_write     0
86994#endif
86995
86996/*
86997** The following structure contains pointers to all SQLite API routines.
86998** A pointer to this structure is passed into extensions when they are
86999** loaded so that the extension can make calls back into the SQLite
87000** library.
87001**
87002** When adding new APIs, add them to the bottom of this structure
87003** in order to preserve backwards compatibility.
87004**
87005** Extensions that use newer APIs should first call the
87006** sqlite3_libversion_number() to make sure that the API they
87007** intend to use is supported by the library.  Extensions should
87008** also check to make sure that the pointer to the function is
87009** not NULL before calling it.
87010*/
87011static const sqlite3_api_routines sqlite3Apis = {
87012  sqlite3_aggregate_context,
87013#ifndef SQLITE_OMIT_DEPRECATED
87014  sqlite3_aggregate_count,
87015#else
87016  0,
87017#endif
87018  sqlite3_bind_blob,
87019  sqlite3_bind_double,
87020  sqlite3_bind_int,
87021  sqlite3_bind_int64,
87022  sqlite3_bind_null,
87023  sqlite3_bind_parameter_count,
87024  sqlite3_bind_parameter_index,
87025  sqlite3_bind_parameter_name,
87026  sqlite3_bind_text,
87027  sqlite3_bind_text16,
87028  sqlite3_bind_value,
87029  sqlite3_busy_handler,
87030  sqlite3_busy_timeout,
87031  sqlite3_changes,
87032  sqlite3_close,
87033  sqlite3_collation_needed,
87034  sqlite3_collation_needed16,
87035  sqlite3_column_blob,
87036  sqlite3_column_bytes,
87037  sqlite3_column_bytes16,
87038  sqlite3_column_count,
87039  sqlite3_column_database_name,
87040  sqlite3_column_database_name16,
87041  sqlite3_column_decltype,
87042  sqlite3_column_decltype16,
87043  sqlite3_column_double,
87044  sqlite3_column_int,
87045  sqlite3_column_int64,
87046  sqlite3_column_name,
87047  sqlite3_column_name16,
87048  sqlite3_column_origin_name,
87049  sqlite3_column_origin_name16,
87050  sqlite3_column_table_name,
87051  sqlite3_column_table_name16,
87052  sqlite3_column_text,
87053  sqlite3_column_text16,
87054  sqlite3_column_type,
87055  sqlite3_column_value,
87056  sqlite3_commit_hook,
87057  sqlite3_complete,
87058  sqlite3_complete16,
87059  sqlite3_create_collation,
87060  sqlite3_create_collation16,
87061  sqlite3_create_function,
87062  sqlite3_create_function16,
87063  sqlite3_create_module,
87064  sqlite3_data_count,
87065  sqlite3_db_handle,
87066  sqlite3_declare_vtab,
87067  sqlite3_enable_shared_cache,
87068  sqlite3_errcode,
87069  sqlite3_errmsg,
87070  sqlite3_errmsg16,
87071  sqlite3_exec,
87072#ifndef SQLITE_OMIT_DEPRECATED
87073  sqlite3_expired,
87074#else
87075  0,
87076#endif
87077  sqlite3_finalize,
87078  sqlite3_free,
87079  sqlite3_free_table,
87080  sqlite3_get_autocommit,
87081  sqlite3_get_auxdata,
87082  sqlite3_get_table,
87083  0,     /* Was sqlite3_global_recover(), but that function is deprecated */
87084  sqlite3_interrupt,
87085  sqlite3_last_insert_rowid,
87086  sqlite3_libversion,
87087  sqlite3_libversion_number,
87088  sqlite3_malloc,
87089  sqlite3_mprintf,
87090  sqlite3_open,
87091  sqlite3_open16,
87092  sqlite3_prepare,
87093  sqlite3_prepare16,
87094  sqlite3_profile,
87095  sqlite3_progress_handler,
87096  sqlite3_realloc,
87097  sqlite3_reset,
87098  sqlite3_result_blob,
87099  sqlite3_result_double,
87100  sqlite3_result_error,
87101  sqlite3_result_error16,
87102  sqlite3_result_int,
87103  sqlite3_result_int64,
87104  sqlite3_result_null,
87105  sqlite3_result_text,
87106  sqlite3_result_text16,
87107  sqlite3_result_text16be,
87108  sqlite3_result_text16le,
87109  sqlite3_result_value,
87110  sqlite3_rollback_hook,
87111  sqlite3_set_authorizer,
87112  sqlite3_set_auxdata,
87113  sqlite3_snprintf,
87114  sqlite3_step,
87115  sqlite3_table_column_metadata,
87116#ifndef SQLITE_OMIT_DEPRECATED
87117  sqlite3_thread_cleanup,
87118#else
87119  0,
87120#endif
87121  sqlite3_total_changes,
87122  sqlite3_trace,
87123#ifndef SQLITE_OMIT_DEPRECATED
87124  sqlite3_transfer_bindings,
87125#else
87126  0,
87127#endif
87128  sqlite3_update_hook,
87129  sqlite3_user_data,
87130  sqlite3_value_blob,
87131  sqlite3_value_bytes,
87132  sqlite3_value_bytes16,
87133  sqlite3_value_double,
87134  sqlite3_value_int,
87135  sqlite3_value_int64,
87136  sqlite3_value_numeric_type,
87137  sqlite3_value_text,
87138  sqlite3_value_text16,
87139  sqlite3_value_text16be,
87140  sqlite3_value_text16le,
87141  sqlite3_value_type,
87142  sqlite3_vmprintf,
87143  /*
87144  ** The original API set ends here.  All extensions can call any
87145  ** of the APIs above provided that the pointer is not NULL.  But
87146  ** before calling APIs that follow, extension should check the
87147  ** sqlite3_libversion_number() to make sure they are dealing with
87148  ** a library that is new enough to support that API.
87149  *************************************************************************
87150  */
87151  sqlite3_overload_function,
87152
87153  /*
87154  ** Added after 3.3.13
87155  */
87156  sqlite3_prepare_v2,
87157  sqlite3_prepare16_v2,
87158  sqlite3_clear_bindings,
87159
87160  /*
87161  ** Added for 3.4.1
87162  */
87163  sqlite3_create_module_v2,
87164
87165  /*
87166  ** Added for 3.5.0
87167  */
87168  sqlite3_bind_zeroblob,
87169  sqlite3_blob_bytes,
87170  sqlite3_blob_close,
87171  sqlite3_blob_open,
87172  sqlite3_blob_read,
87173  sqlite3_blob_write,
87174  sqlite3_create_collation_v2,
87175  sqlite3_file_control,
87176  sqlite3_memory_highwater,
87177  sqlite3_memory_used,
87178#ifdef SQLITE_MUTEX_OMIT
87179  0,
87180  0,
87181  0,
87182  0,
87183  0,
87184#else
87185  sqlite3_mutex_alloc,
87186  sqlite3_mutex_enter,
87187  sqlite3_mutex_free,
87188  sqlite3_mutex_leave,
87189  sqlite3_mutex_try,
87190#endif
87191  sqlite3_open_v2,
87192  sqlite3_release_memory,
87193  sqlite3_result_error_nomem,
87194  sqlite3_result_error_toobig,
87195  sqlite3_sleep,
87196  sqlite3_soft_heap_limit,
87197  sqlite3_vfs_find,
87198  sqlite3_vfs_register,
87199  sqlite3_vfs_unregister,
87200
87201  /*
87202  ** Added for 3.5.8
87203  */
87204  sqlite3_threadsafe,
87205  sqlite3_result_zeroblob,
87206  sqlite3_result_error_code,
87207  sqlite3_test_control,
87208  sqlite3_randomness,
87209  sqlite3_context_db_handle,
87210
87211  /*
87212  ** Added for 3.6.0
87213  */
87214  sqlite3_extended_result_codes,
87215  sqlite3_limit,
87216  sqlite3_next_stmt,
87217  sqlite3_sql,
87218  sqlite3_status,
87219
87220  /*
87221  ** Added for 3.7.4
87222  */
87223  sqlite3_backup_finish,
87224  sqlite3_backup_init,
87225  sqlite3_backup_pagecount,
87226  sqlite3_backup_remaining,
87227  sqlite3_backup_step,
87228#ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
87229  sqlite3_compileoption_get,
87230  sqlite3_compileoption_used,
87231#else
87232  0,
87233  0,
87234#endif
87235  sqlite3_create_function_v2,
87236  sqlite3_db_config,
87237  sqlite3_db_mutex,
87238  sqlite3_db_status,
87239  sqlite3_extended_errcode,
87240  sqlite3_log,
87241  sqlite3_soft_heap_limit64,
87242  sqlite3_sourceid,
87243  sqlite3_stmt_status,
87244  sqlite3_strnicmp,
87245#ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
87246  sqlite3_unlock_notify,
87247#else
87248  0,
87249#endif
87250#ifndef SQLITE_OMIT_WAL
87251  sqlite3_wal_autocheckpoint,
87252  sqlite3_wal_checkpoint,
87253  sqlite3_wal_hook,
87254#else
87255  0,
87256  0,
87257  0,
87258#endif
87259};
87260
87261/*
87262** Attempt to load an SQLite extension library contained in the file
87263** zFile.  The entry point is zProc.  zProc may be 0 in which case a
87264** default entry point name (sqlite3_extension_init) is used.  Use
87265** of the default name is recommended.
87266**
87267** Return SQLITE_OK on success and SQLITE_ERROR if something goes wrong.
87268**
87269** If an error occurs and pzErrMsg is not 0, then fill *pzErrMsg with
87270** error message text.  The calling function should free this memory
87271** by calling sqlite3DbFree(db, ).
87272*/
87273static int sqlite3LoadExtension(
87274  sqlite3 *db,          /* Load the extension into this database connection */
87275  const char *zFile,    /* Name of the shared library containing extension */
87276  const char *zProc,    /* Entry point.  Use "sqlite3_extension_init" if 0 */
87277  char **pzErrMsg       /* Put error message here if not 0 */
87278){
87279  sqlite3_vfs *pVfs = db->pVfs;
87280  void *handle;
87281  int (*xInit)(sqlite3*,char**,const sqlite3_api_routines*);
87282  char *zErrmsg = 0;
87283  void **aHandle;
87284  const int nMsg = 300;
87285
87286  if( pzErrMsg ) *pzErrMsg = 0;
87287
87288  /* Ticket #1863.  To avoid a creating security problems for older
87289  ** applications that relink against newer versions of SQLite, the
87290  ** ability to run load_extension is turned off by default.  One
87291  ** must call sqlite3_enable_load_extension() to turn on extension
87292  ** loading.  Otherwise you get the following error.
87293  */
87294  if( (db->flags & SQLITE_LoadExtension)==0 ){
87295    if( pzErrMsg ){
87296      *pzErrMsg = sqlite3_mprintf("not authorized");
87297    }
87298    return SQLITE_ERROR;
87299  }
87300
87301  if( zProc==0 ){
87302    zProc = "sqlite3_extension_init";
87303  }
87304
87305  handle = sqlite3OsDlOpen(pVfs, zFile);
87306  if( handle==0 ){
87307    if( pzErrMsg ){
87308      *pzErrMsg = zErrmsg = sqlite3_malloc(nMsg);
87309      if( zErrmsg ){
87310        sqlite3_snprintf(nMsg, zErrmsg,
87311            "unable to open shared library [%s]", zFile);
87312        sqlite3OsDlError(pVfs, nMsg-1, zErrmsg);
87313      }
87314    }
87315    return SQLITE_ERROR;
87316  }
87317  xInit = (int(*)(sqlite3*,char**,const sqlite3_api_routines*))
87318                   sqlite3OsDlSym(pVfs, handle, zProc);
87319  if( xInit==0 ){
87320    if( pzErrMsg ){
87321      *pzErrMsg = zErrmsg = sqlite3_malloc(nMsg);
87322      if( zErrmsg ){
87323        sqlite3_snprintf(nMsg, zErrmsg,
87324            "no entry point [%s] in shared library [%s]", zProc,zFile);
87325        sqlite3OsDlError(pVfs, nMsg-1, zErrmsg);
87326      }
87327      sqlite3OsDlClose(pVfs, handle);
87328    }
87329    return SQLITE_ERROR;
87330  }else if( xInit(db, &zErrmsg, &sqlite3Apis) ){
87331    if( pzErrMsg ){
87332      *pzErrMsg = sqlite3_mprintf("error during initialization: %s", zErrmsg);
87333    }
87334    sqlite3_free(zErrmsg);
87335    sqlite3OsDlClose(pVfs, handle);
87336    return SQLITE_ERROR;
87337  }
87338
87339  /* Append the new shared library handle to the db->aExtension array. */
87340  aHandle = sqlite3DbMallocZero(db, sizeof(handle)*(db->nExtension+1));
87341  if( aHandle==0 ){
87342    return SQLITE_NOMEM;
87343  }
87344  if( db->nExtension>0 ){
87345    memcpy(aHandle, db->aExtension, sizeof(handle)*db->nExtension);
87346  }
87347  sqlite3DbFree(db, db->aExtension);
87348  db->aExtension = aHandle;
87349
87350  db->aExtension[db->nExtension++] = handle;
87351  return SQLITE_OK;
87352}
87353SQLITE_API int sqlite3_load_extension(
87354  sqlite3 *db,          /* Load the extension into this database connection */
87355  const char *zFile,    /* Name of the shared library containing extension */
87356  const char *zProc,    /* Entry point.  Use "sqlite3_extension_init" if 0 */
87357  char **pzErrMsg       /* Put error message here if not 0 */
87358){
87359  int rc;
87360  sqlite3_mutex_enter(db->mutex);
87361  rc = sqlite3LoadExtension(db, zFile, zProc, pzErrMsg);
87362  rc = sqlite3ApiExit(db, rc);
87363  sqlite3_mutex_leave(db->mutex);
87364  return rc;
87365}
87366
87367/*
87368** Call this routine when the database connection is closing in order
87369** to clean up loaded extensions
87370*/
87371SQLITE_PRIVATE void sqlite3CloseExtensions(sqlite3 *db){
87372  int i;
87373  assert( sqlite3_mutex_held(db->mutex) );
87374  for(i=0; i<db->nExtension; i++){
87375    sqlite3OsDlClose(db->pVfs, db->aExtension[i]);
87376  }
87377  sqlite3DbFree(db, db->aExtension);
87378}
87379
87380/*
87381** Enable or disable extension loading.  Extension loading is disabled by
87382** default so as not to open security holes in older applications.
87383*/
87384SQLITE_API int sqlite3_enable_load_extension(sqlite3 *db, int onoff){
87385  sqlite3_mutex_enter(db->mutex);
87386  if( onoff ){
87387    db->flags |= SQLITE_LoadExtension;
87388  }else{
87389    db->flags &= ~SQLITE_LoadExtension;
87390  }
87391  sqlite3_mutex_leave(db->mutex);
87392  return SQLITE_OK;
87393}
87394
87395#endif /* SQLITE_OMIT_LOAD_EXTENSION */
87396
87397/*
87398** The auto-extension code added regardless of whether or not extension
87399** loading is supported.  We need a dummy sqlite3Apis pointer for that
87400** code if regular extension loading is not available.  This is that
87401** dummy pointer.
87402*/
87403#ifdef SQLITE_OMIT_LOAD_EXTENSION
87404static const sqlite3_api_routines sqlite3Apis = { 0 };
87405#endif
87406
87407
87408/*
87409** The following object holds the list of automatically loaded
87410** extensions.
87411**
87412** This list is shared across threads.  The SQLITE_MUTEX_STATIC_MASTER
87413** mutex must be held while accessing this list.
87414*/
87415typedef struct sqlite3AutoExtList sqlite3AutoExtList;
87416static SQLITE_WSD struct sqlite3AutoExtList {
87417  int nExt;              /* Number of entries in aExt[] */
87418  void (**aExt)(void);   /* Pointers to the extension init functions */
87419} sqlite3Autoext = { 0, 0 };
87420
87421/* The "wsdAutoext" macro will resolve to the autoextension
87422** state vector.  If writable static data is unsupported on the target,
87423** we have to locate the state vector at run-time.  In the more common
87424** case where writable static data is supported, wsdStat can refer directly
87425** to the "sqlite3Autoext" state vector declared above.
87426*/
87427#ifdef SQLITE_OMIT_WSD
87428# define wsdAutoextInit \
87429  sqlite3AutoExtList *x = &GLOBAL(sqlite3AutoExtList,sqlite3Autoext)
87430# define wsdAutoext x[0]
87431#else
87432# define wsdAutoextInit
87433# define wsdAutoext sqlite3Autoext
87434#endif
87435
87436
87437/*
87438** Register a statically linked extension that is automatically
87439** loaded by every new database connection.
87440*/
87441SQLITE_API int sqlite3_auto_extension(void (*xInit)(void)){
87442  int rc = SQLITE_OK;
87443#ifndef SQLITE_OMIT_AUTOINIT
87444  rc = sqlite3_initialize();
87445  if( rc ){
87446    return rc;
87447  }else
87448#endif
87449  {
87450    int i;
87451#if SQLITE_THREADSAFE
87452    sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
87453#endif
87454    wsdAutoextInit;
87455    sqlite3_mutex_enter(mutex);
87456    for(i=0; i<wsdAutoext.nExt; i++){
87457      if( wsdAutoext.aExt[i]==xInit ) break;
87458    }
87459    if( i==wsdAutoext.nExt ){
87460      int nByte = (wsdAutoext.nExt+1)*sizeof(wsdAutoext.aExt[0]);
87461      void (**aNew)(void);
87462      aNew = sqlite3_realloc(wsdAutoext.aExt, nByte);
87463      if( aNew==0 ){
87464        rc = SQLITE_NOMEM;
87465      }else{
87466        wsdAutoext.aExt = aNew;
87467        wsdAutoext.aExt[wsdAutoext.nExt] = xInit;
87468        wsdAutoext.nExt++;
87469      }
87470    }
87471    sqlite3_mutex_leave(mutex);
87472    assert( (rc&0xff)==rc );
87473    return rc;
87474  }
87475}
87476
87477/*
87478** Reset the automatic extension loading mechanism.
87479*/
87480SQLITE_API void sqlite3_reset_auto_extension(void){
87481#ifndef SQLITE_OMIT_AUTOINIT
87482  if( sqlite3_initialize()==SQLITE_OK )
87483#endif
87484  {
87485#if SQLITE_THREADSAFE
87486    sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
87487#endif
87488    wsdAutoextInit;
87489    sqlite3_mutex_enter(mutex);
87490    sqlite3_free(wsdAutoext.aExt);
87491    wsdAutoext.aExt = 0;
87492    wsdAutoext.nExt = 0;
87493    sqlite3_mutex_leave(mutex);
87494  }
87495}
87496
87497/*
87498** Load all automatic extensions.
87499**
87500** If anything goes wrong, set an error in the database connection.
87501*/
87502SQLITE_PRIVATE void sqlite3AutoLoadExtensions(sqlite3 *db){
87503  int i;
87504  int go = 1;
87505  int (*xInit)(sqlite3*,char**,const sqlite3_api_routines*);
87506
87507  wsdAutoextInit;
87508  if( wsdAutoext.nExt==0 ){
87509    /* Common case: early out without every having to acquire a mutex */
87510    return;
87511  }
87512  for(i=0; go; i++){
87513    char *zErrmsg;
87514#if SQLITE_THREADSAFE
87515    sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
87516#endif
87517    sqlite3_mutex_enter(mutex);
87518    if( i>=wsdAutoext.nExt ){
87519      xInit = 0;
87520      go = 0;
87521    }else{
87522      xInit = (int(*)(sqlite3*,char**,const sqlite3_api_routines*))
87523              wsdAutoext.aExt[i];
87524    }
87525    sqlite3_mutex_leave(mutex);
87526    zErrmsg = 0;
87527    if( xInit && xInit(db, &zErrmsg, &sqlite3Apis) ){
87528      sqlite3Error(db, SQLITE_ERROR,
87529            "automatic extension loading failed: %s", zErrmsg);
87530      go = 0;
87531    }
87532    sqlite3_free(zErrmsg);
87533  }
87534}
87535
87536/************** End of loadext.c *********************************************/
87537/************** Begin file pragma.c ******************************************/
87538/*
87539** 2003 April 6
87540**
87541** The author disclaims copyright to this source code.  In place of
87542** a legal notice, here is a blessing:
87543**
87544**    May you do good and not evil.
87545**    May you find forgiveness for yourself and forgive others.
87546**    May you share freely, never taking more than you give.
87547**
87548*************************************************************************
87549** This file contains code used to implement the PRAGMA command.
87550*/
87551
87552/* Ignore this whole file if pragmas are disabled
87553*/
87554#if !defined(SQLITE_OMIT_PRAGMA)
87555
87556/*
87557** Interpret the given string as a safety level.  Return 0 for OFF,
87558** 1 for ON or NORMAL and 2 for FULL.  Return 1 for an empty or
87559** unrecognized string argument.
87560**
87561** Note that the values returned are one less that the values that
87562** should be passed into sqlite3BtreeSetSafetyLevel().  The is done
87563** to support legacy SQL code.  The safety level used to be boolean
87564** and older scripts may have used numbers 0 for OFF and 1 for ON.
87565*/
87566static u8 getSafetyLevel(const char *z){
87567                             /* 123456789 123456789 */
87568  static const char zText[] = "onoffalseyestruefull";
87569  static const u8 iOffset[] = {0, 1, 2, 4, 9, 12, 16};
87570  static const u8 iLength[] = {2, 2, 3, 5, 3, 4, 4};
87571  static const u8 iValue[] =  {1, 0, 0, 0, 1, 1, 2};
87572  int i, n;
87573  if( sqlite3Isdigit(*z) ){
87574    return (u8)sqlite3Atoi(z);
87575  }
87576  n = sqlite3Strlen30(z);
87577  for(i=0; i<ArraySize(iLength); i++){
87578    if( iLength[i]==n && sqlite3StrNICmp(&zText[iOffset[i]],z,n)==0 ){
87579      return iValue[i];
87580    }
87581  }
87582  return 1;
87583}
87584
87585/*
87586** Interpret the given string as a boolean value.
87587*/
87588static u8 getBoolean(const char *z){
87589  return getSafetyLevel(z)&1;
87590}
87591
87592/*
87593** Interpret the given string as a locking mode value.
87594*/
87595static int getLockingMode(const char *z){
87596  if( z ){
87597    if( 0==sqlite3StrICmp(z, "exclusive") ) return PAGER_LOCKINGMODE_EXCLUSIVE;
87598    if( 0==sqlite3StrICmp(z, "normal") ) return PAGER_LOCKINGMODE_NORMAL;
87599  }
87600  return PAGER_LOCKINGMODE_QUERY;
87601}
87602
87603#ifndef SQLITE_OMIT_AUTOVACUUM
87604/*
87605** Interpret the given string as an auto-vacuum mode value.
87606**
87607** The following strings, "none", "full" and "incremental" are
87608** acceptable, as are their numeric equivalents: 0, 1 and 2 respectively.
87609*/
87610static int getAutoVacuum(const char *z){
87611  int i;
87612  if( 0==sqlite3StrICmp(z, "none") ) return BTREE_AUTOVACUUM_NONE;
87613  if( 0==sqlite3StrICmp(z, "full") ) return BTREE_AUTOVACUUM_FULL;
87614  if( 0==sqlite3StrICmp(z, "incremental") ) return BTREE_AUTOVACUUM_INCR;
87615  i = sqlite3Atoi(z);
87616  return (u8)((i>=0&&i<=2)?i:0);
87617}
87618#endif /* ifndef SQLITE_OMIT_AUTOVACUUM */
87619
87620#ifndef SQLITE_OMIT_PAGER_PRAGMAS
87621/*
87622** Interpret the given string as a temp db location. Return 1 for file
87623** backed temporary databases, 2 for the Red-Black tree in memory database
87624** and 0 to use the compile-time default.
87625*/
87626static int getTempStore(const char *z){
87627  if( z[0]>='0' && z[0]<='2' ){
87628    return z[0] - '0';
87629  }else if( sqlite3StrICmp(z, "file")==0 ){
87630    return 1;
87631  }else if( sqlite3StrICmp(z, "memory")==0 ){
87632    return 2;
87633  }else{
87634    return 0;
87635  }
87636}
87637#endif /* SQLITE_PAGER_PRAGMAS */
87638
87639#ifndef SQLITE_OMIT_PAGER_PRAGMAS
87640/*
87641** Invalidate temp storage, either when the temp storage is changed
87642** from default, or when 'file' and the temp_store_directory has changed
87643*/
87644static int invalidateTempStorage(Parse *pParse){
87645  sqlite3 *db = pParse->db;
87646  if( db->aDb[1].pBt!=0 ){
87647    if( !db->autoCommit || sqlite3BtreeIsInReadTrans(db->aDb[1].pBt) ){
87648      sqlite3ErrorMsg(pParse, "temporary storage cannot be changed "
87649        "from within a transaction");
87650      return SQLITE_ERROR;
87651    }
87652    sqlite3BtreeClose(db->aDb[1].pBt);
87653    db->aDb[1].pBt = 0;
87654    sqlite3ResetInternalSchema(db, -1);
87655  }
87656  return SQLITE_OK;
87657}
87658#endif /* SQLITE_PAGER_PRAGMAS */
87659
87660#ifndef SQLITE_OMIT_PAGER_PRAGMAS
87661/*
87662** If the TEMP database is open, close it and mark the database schema
87663** as needing reloading.  This must be done when using the SQLITE_TEMP_STORE
87664** or DEFAULT_TEMP_STORE pragmas.
87665*/
87666static int changeTempStorage(Parse *pParse, const char *zStorageType){
87667  int ts = getTempStore(zStorageType);
87668  sqlite3 *db = pParse->db;
87669  if( db->temp_store==ts ) return SQLITE_OK;
87670  if( invalidateTempStorage( pParse ) != SQLITE_OK ){
87671    return SQLITE_ERROR;
87672  }
87673  db->temp_store = (u8)ts;
87674  return SQLITE_OK;
87675}
87676#endif /* SQLITE_PAGER_PRAGMAS */
87677
87678/*
87679** Generate code to return a single integer value.
87680*/
87681static void returnSingleInt(Parse *pParse, const char *zLabel, i64 value){
87682  Vdbe *v = sqlite3GetVdbe(pParse);
87683  int mem = ++pParse->nMem;
87684  i64 *pI64 = sqlite3DbMallocRaw(pParse->db, sizeof(value));
87685  if( pI64 ){
87686    memcpy(pI64, &value, sizeof(value));
87687  }
87688  sqlite3VdbeAddOp4(v, OP_Int64, 0, mem, 0, (char*)pI64, P4_INT64);
87689  sqlite3VdbeSetNumCols(v, 1);
87690  sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLabel, SQLITE_STATIC);
87691  sqlite3VdbeAddOp2(v, OP_ResultRow, mem, 1);
87692}
87693
87694#ifndef SQLITE_OMIT_FLAG_PRAGMAS
87695/*
87696** Check to see if zRight and zLeft refer to a pragma that queries
87697** or changes one of the flags in db->flags.  Return 1 if so and 0 if not.
87698** Also, implement the pragma.
87699*/
87700static int flagPragma(Parse *pParse, const char *zLeft, const char *zRight){
87701  static const struct sPragmaType {
87702    const char *zName;  /* Name of the pragma */
87703    int mask;           /* Mask for the db->flags value */
87704  } aPragma[] = {
87705    { "full_column_names",        SQLITE_FullColNames  },
87706    { "short_column_names",       SQLITE_ShortColNames },
87707    { "count_changes",            SQLITE_CountRows     },
87708    { "empty_result_callbacks",   SQLITE_NullCallback  },
87709    { "legacy_file_format",       SQLITE_LegacyFileFmt },
87710    { "fullfsync",                SQLITE_FullFSync     },
87711    { "checkpoint_fullfsync",     SQLITE_CkptFullFSync },
87712    { "reverse_unordered_selects", SQLITE_ReverseOrder  },
87713#ifndef SQLITE_OMIT_AUTOMATIC_INDEX
87714    { "automatic_index",          SQLITE_AutoIndex     },
87715#endif
87716#ifdef SQLITE_DEBUG
87717    { "sql_trace",                SQLITE_SqlTrace      },
87718    { "vdbe_listing",             SQLITE_VdbeListing   },
87719    { "vdbe_trace",               SQLITE_VdbeTrace     },
87720#endif
87721#ifndef SQLITE_OMIT_CHECK
87722    { "ignore_check_constraints", SQLITE_IgnoreChecks  },
87723#endif
87724    /* The following is VERY experimental */
87725    { "writable_schema",          SQLITE_WriteSchema|SQLITE_RecoveryMode },
87726    { "omit_readlock",            SQLITE_NoReadlock    },
87727
87728    /* TODO: Maybe it shouldn't be possible to change the ReadUncommitted
87729    ** flag if there are any active statements. */
87730    { "read_uncommitted",         SQLITE_ReadUncommitted },
87731    { "recursive_triggers",       SQLITE_RecTriggers },
87732
87733    /* This flag may only be set if both foreign-key and trigger support
87734    ** are present in the build.  */
87735#if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
87736    { "foreign_keys",             SQLITE_ForeignKeys },
87737#endif
87738  };
87739  int i;
87740  const struct sPragmaType *p;
87741  for(i=0, p=aPragma; i<ArraySize(aPragma); i++, p++){
87742    if( sqlite3StrICmp(zLeft, p->zName)==0 ){
87743      sqlite3 *db = pParse->db;
87744      Vdbe *v;
87745      v = sqlite3GetVdbe(pParse);
87746      assert( v!=0 );  /* Already allocated by sqlite3Pragma() */
87747      if( ALWAYS(v) ){
87748        if( zRight==0 ){
87749          returnSingleInt(pParse, p->zName, (db->flags & p->mask)!=0 );
87750        }else{
87751          int mask = p->mask;          /* Mask of bits to set or clear. */
87752          if( db->autoCommit==0 ){
87753            /* Foreign key support may not be enabled or disabled while not
87754            ** in auto-commit mode.  */
87755            mask &= ~(SQLITE_ForeignKeys);
87756          }
87757
87758          if( getBoolean(zRight) ){
87759            db->flags |= mask;
87760          }else{
87761            db->flags &= ~mask;
87762          }
87763
87764          /* Many of the flag-pragmas modify the code generated by the SQL
87765          ** compiler (eg. count_changes). So add an opcode to expire all
87766          ** compiled SQL statements after modifying a pragma value.
87767          */
87768          sqlite3VdbeAddOp2(v, OP_Expire, 0, 0);
87769        }
87770      }
87771
87772      return 1;
87773    }
87774  }
87775  return 0;
87776}
87777#endif /* SQLITE_OMIT_FLAG_PRAGMAS */
87778
87779/*
87780** Return a human-readable name for a constraint resolution action.
87781*/
87782#ifndef SQLITE_OMIT_FOREIGN_KEY
87783static const char *actionName(u8 action){
87784  const char *zName;
87785  switch( action ){
87786    case OE_SetNull:  zName = "SET NULL";        break;
87787    case OE_SetDflt:  zName = "SET DEFAULT";     break;
87788    case OE_Cascade:  zName = "CASCADE";         break;
87789    case OE_Restrict: zName = "RESTRICT";        break;
87790    default:          zName = "NO ACTION";
87791                      assert( action==OE_None ); break;
87792  }
87793  return zName;
87794}
87795#endif
87796
87797
87798/*
87799** Parameter eMode must be one of the PAGER_JOURNALMODE_XXX constants
87800** defined in pager.h. This function returns the associated lowercase
87801** journal-mode name.
87802*/
87803SQLITE_PRIVATE const char *sqlite3JournalModename(int eMode){
87804  static char * const azModeName[] = {
87805    "delete", "persist", "off", "truncate", "memory"
87806#ifndef SQLITE_OMIT_WAL
87807     , "wal"
87808#endif
87809  };
87810  assert( PAGER_JOURNALMODE_DELETE==0 );
87811  assert( PAGER_JOURNALMODE_PERSIST==1 );
87812  assert( PAGER_JOURNALMODE_OFF==2 );
87813  assert( PAGER_JOURNALMODE_TRUNCATE==3 );
87814  assert( PAGER_JOURNALMODE_MEMORY==4 );
87815  assert( PAGER_JOURNALMODE_WAL==5 );
87816  assert( eMode>=0 && eMode<=ArraySize(azModeName) );
87817
87818  if( eMode==ArraySize(azModeName) ) return 0;
87819  return azModeName[eMode];
87820}
87821
87822/*
87823** Process a pragma statement.
87824**
87825** Pragmas are of this form:
87826**
87827**      PRAGMA [database.]id [= value]
87828**
87829** The identifier might also be a string.  The value is a string, and
87830** identifier, or a number.  If minusFlag is true, then the value is
87831** a number that was preceded by a minus sign.
87832**
87833** If the left side is "database.id" then pId1 is the database name
87834** and pId2 is the id.  If the left side is just "id" then pId1 is the
87835** id and pId2 is any empty string.
87836*/
87837SQLITE_PRIVATE void sqlite3Pragma(
87838  Parse *pParse,
87839  Token *pId1,        /* First part of [database.]id field */
87840  Token *pId2,        /* Second part of [database.]id field, or NULL */
87841  Token *pValue,      /* Token for <value>, or NULL */
87842  int minusFlag       /* True if a '-' sign preceded <value> */
87843){
87844  char *zLeft = 0;       /* Nul-terminated UTF-8 string <id> */
87845  char *zRight = 0;      /* Nul-terminated UTF-8 string <value>, or NULL */
87846  const char *zDb = 0;   /* The database name */
87847  Token *pId;            /* Pointer to <id> token */
87848  int iDb;               /* Database index for <database> */
87849  sqlite3 *db = pParse->db;
87850  Db *pDb;
87851  Vdbe *v = pParse->pVdbe = sqlite3VdbeCreate(db);
87852  if( v==0 ) return;
87853  sqlite3VdbeRunOnlyOnce(v);
87854  pParse->nMem = 2;
87855
87856  /* Interpret the [database.] part of the pragma statement. iDb is the
87857  ** index of the database this pragma is being applied to in db.aDb[]. */
87858  iDb = sqlite3TwoPartName(pParse, pId1, pId2, &pId);
87859  if( iDb<0 ) return;
87860  pDb = &db->aDb[iDb];
87861
87862  /* If the temp database has been explicitly named as part of the
87863  ** pragma, make sure it is open.
87864  */
87865  if( iDb==1 && sqlite3OpenTempDatabase(pParse) ){
87866    return;
87867  }
87868
87869  zLeft = sqlite3NameFromToken(db, pId);
87870  if( !zLeft ) return;
87871  if( minusFlag ){
87872    zRight = sqlite3MPrintf(db, "-%T", pValue);
87873  }else{
87874    zRight = sqlite3NameFromToken(db, pValue);
87875  }
87876
87877  assert( pId2 );
87878  zDb = pId2->n>0 ? pDb->zName : 0;
87879  if( sqlite3AuthCheck(pParse, SQLITE_PRAGMA, zLeft, zRight, zDb) ){
87880    goto pragma_out;
87881  }
87882
87883#ifndef SQLITE_OMIT_PAGER_PRAGMAS
87884  /*
87885  **  PRAGMA [database.]default_cache_size
87886  **  PRAGMA [database.]default_cache_size=N
87887  **
87888  ** The first form reports the current persistent setting for the
87889  ** page cache size.  The value returned is the maximum number of
87890  ** pages in the page cache.  The second form sets both the current
87891  ** page cache size value and the persistent page cache size value
87892  ** stored in the database file.
87893  **
87894  ** Older versions of SQLite would set the default cache size to a
87895  ** negative number to indicate synchronous=OFF.  These days, synchronous
87896  ** is always on by default regardless of the sign of the default cache
87897  ** size.  But continue to take the absolute value of the default cache
87898  ** size of historical compatibility.
87899  */
87900  if( sqlite3StrICmp(zLeft,"default_cache_size")==0 ){
87901    static const VdbeOpList getCacheSize[] = {
87902      { OP_Transaction, 0, 0,        0},                         /* 0 */
87903      { OP_ReadCookie,  0, 1,        BTREE_DEFAULT_CACHE_SIZE},  /* 1 */
87904      { OP_IfPos,       1, 7,        0},
87905      { OP_Integer,     0, 2,        0},
87906      { OP_Subtract,    1, 2,        1},
87907      { OP_IfPos,       1, 7,        0},
87908      { OP_Integer,     0, 1,        0},                         /* 6 */
87909      { OP_ResultRow,   1, 1,        0},
87910    };
87911    int addr;
87912    if( sqlite3ReadSchema(pParse) ) goto pragma_out;
87913    sqlite3VdbeUsesBtree(v, iDb);
87914    if( !zRight ){
87915      sqlite3VdbeSetNumCols(v, 1);
87916      sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "cache_size", SQLITE_STATIC);
87917      pParse->nMem += 2;
87918      addr = sqlite3VdbeAddOpList(v, ArraySize(getCacheSize), getCacheSize);
87919      sqlite3VdbeChangeP1(v, addr, iDb);
87920      sqlite3VdbeChangeP1(v, addr+1, iDb);
87921      sqlite3VdbeChangeP1(v, addr+6, SQLITE_DEFAULT_CACHE_SIZE);
87922    }else{
87923      int size = sqlite3AbsInt32(sqlite3Atoi(zRight));
87924      sqlite3BeginWriteOperation(pParse, 0, iDb);
87925      sqlite3VdbeAddOp2(v, OP_Integer, size, 1);
87926      sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_DEFAULT_CACHE_SIZE, 1);
87927      assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
87928      pDb->pSchema->cache_size = size;
87929      sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
87930    }
87931  }else
87932
87933  /*
87934  **  PRAGMA [database.]page_size
87935  **  PRAGMA [database.]page_size=N
87936  **
87937  ** The first form reports the current setting for the
87938  ** database page size in bytes.  The second form sets the
87939  ** database page size value.  The value can only be set if
87940  ** the database has not yet been created.
87941  */
87942  if( sqlite3StrICmp(zLeft,"page_size")==0 ){
87943    Btree *pBt = pDb->pBt;
87944    assert( pBt!=0 );
87945    if( !zRight ){
87946      int size = ALWAYS(pBt) ? sqlite3BtreeGetPageSize(pBt) : 0;
87947      returnSingleInt(pParse, "page_size", size);
87948    }else{
87949      /* Malloc may fail when setting the page-size, as there is an internal
87950      ** buffer that the pager module resizes using sqlite3_realloc().
87951      */
87952      db->nextPagesize = sqlite3Atoi(zRight);
87953      if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize, -1, 0) ){
87954        db->mallocFailed = 1;
87955      }
87956    }
87957  }else
87958
87959  /*
87960  **  PRAGMA [database.]secure_delete
87961  **  PRAGMA [database.]secure_delete=ON/OFF
87962  **
87963  ** The first form reports the current setting for the
87964  ** secure_delete flag.  The second form changes the secure_delete
87965  ** flag setting and reports thenew value.
87966  */
87967  if( sqlite3StrICmp(zLeft,"secure_delete")==0 ){
87968    Btree *pBt = pDb->pBt;
87969    int b = -1;
87970    assert( pBt!=0 );
87971    if( zRight ){
87972      b = getBoolean(zRight);
87973    }
87974    if( pId2->n==0 && b>=0 ){
87975      int ii;
87976      for(ii=0; ii<db->nDb; ii++){
87977        sqlite3BtreeSecureDelete(db->aDb[ii].pBt, b);
87978      }
87979    }
87980    b = sqlite3BtreeSecureDelete(pBt, b);
87981    returnSingleInt(pParse, "secure_delete", b);
87982  }else
87983
87984  /*
87985  **  PRAGMA [database.]max_page_count
87986  **  PRAGMA [database.]max_page_count=N
87987  **
87988  ** The first form reports the current setting for the
87989  ** maximum number of pages in the database file.  The
87990  ** second form attempts to change this setting.  Both
87991  ** forms return the current setting.
87992  **
87993  **  PRAGMA [database.]page_count
87994  **
87995  ** Return the number of pages in the specified database.
87996  */
87997  if( sqlite3StrICmp(zLeft,"page_count")==0
87998   || sqlite3StrICmp(zLeft,"max_page_count")==0
87999  ){
88000    int iReg;
88001    if( sqlite3ReadSchema(pParse) ) goto pragma_out;
88002    sqlite3CodeVerifySchema(pParse, iDb);
88003    iReg = ++pParse->nMem;
88004    if( zLeft[0]=='p' ){
88005      sqlite3VdbeAddOp2(v, OP_Pagecount, iDb, iReg);
88006    }else{
88007      sqlite3VdbeAddOp3(v, OP_MaxPgcnt, iDb, iReg, sqlite3Atoi(zRight));
88008    }
88009    sqlite3VdbeAddOp2(v, OP_ResultRow, iReg, 1);
88010    sqlite3VdbeSetNumCols(v, 1);
88011    sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLeft, SQLITE_TRANSIENT);
88012  }else
88013
88014  /*
88015  **  PRAGMA [database.]locking_mode
88016  **  PRAGMA [database.]locking_mode = (normal|exclusive)
88017  */
88018  if( sqlite3StrICmp(zLeft,"locking_mode")==0 ){
88019    const char *zRet = "normal";
88020    int eMode = getLockingMode(zRight);
88021
88022    if( pId2->n==0 && eMode==PAGER_LOCKINGMODE_QUERY ){
88023      /* Simple "PRAGMA locking_mode;" statement. This is a query for
88024      ** the current default locking mode (which may be different to
88025      ** the locking-mode of the main database).
88026      */
88027      eMode = db->dfltLockMode;
88028    }else{
88029      Pager *pPager;
88030      if( pId2->n==0 ){
88031        /* This indicates that no database name was specified as part
88032        ** of the PRAGMA command. In this case the locking-mode must be
88033        ** set on all attached databases, as well as the main db file.
88034        **
88035        ** Also, the sqlite3.dfltLockMode variable is set so that
88036        ** any subsequently attached databases also use the specified
88037        ** locking mode.
88038        */
88039        int ii;
88040        assert(pDb==&db->aDb[0]);
88041        for(ii=2; ii<db->nDb; ii++){
88042          pPager = sqlite3BtreePager(db->aDb[ii].pBt);
88043          sqlite3PagerLockingMode(pPager, eMode);
88044        }
88045        db->dfltLockMode = (u8)eMode;
88046      }
88047      pPager = sqlite3BtreePager(pDb->pBt);
88048      eMode = sqlite3PagerLockingMode(pPager, eMode);
88049    }
88050
88051    assert(eMode==PAGER_LOCKINGMODE_NORMAL||eMode==PAGER_LOCKINGMODE_EXCLUSIVE);
88052    if( eMode==PAGER_LOCKINGMODE_EXCLUSIVE ){
88053      zRet = "exclusive";
88054    }
88055    sqlite3VdbeSetNumCols(v, 1);
88056    sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "locking_mode", SQLITE_STATIC);
88057    sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, zRet, 0);
88058    sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
88059  }else
88060
88061  /*
88062  **  PRAGMA [database.]journal_mode
88063  **  PRAGMA [database.]journal_mode =
88064  **                      (delete|persist|off|truncate|memory|wal|off)
88065  */
88066  if( sqlite3StrICmp(zLeft,"journal_mode")==0 ){
88067    int eMode;        /* One of the PAGER_JOURNALMODE_XXX symbols */
88068    int ii;           /* Loop counter */
88069
88070    /* Force the schema to be loaded on all databases.  This cases all
88071    ** database files to be opened and the journal_modes set. */
88072    if( sqlite3ReadSchema(pParse) ){
88073      goto pragma_out;
88074    }
88075
88076    sqlite3VdbeSetNumCols(v, 1);
88077    sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "journal_mode", SQLITE_STATIC);
88078
88079    if( zRight==0 ){
88080      /* If there is no "=MODE" part of the pragma, do a query for the
88081      ** current mode */
88082      eMode = PAGER_JOURNALMODE_QUERY;
88083    }else{
88084      const char *zMode;
88085      int n = sqlite3Strlen30(zRight);
88086      for(eMode=0; (zMode = sqlite3JournalModename(eMode))!=0; eMode++){
88087        if( sqlite3StrNICmp(zRight, zMode, n)==0 ) break;
88088      }
88089      if( !zMode ){
88090        /* If the "=MODE" part does not match any known journal mode,
88091        ** then do a query */
88092        eMode = PAGER_JOURNALMODE_QUERY;
88093      }
88094    }
88095    if( eMode==PAGER_JOURNALMODE_QUERY && pId2->n==0 ){
88096      /* Convert "PRAGMA journal_mode" into "PRAGMA main.journal_mode" */
88097      iDb = 0;
88098      pId2->n = 1;
88099    }
88100    for(ii=db->nDb-1; ii>=0; ii--){
88101      if( db->aDb[ii].pBt && (ii==iDb || pId2->n==0) ){
88102        sqlite3VdbeUsesBtree(v, ii);
88103        sqlite3VdbeAddOp3(v, OP_JournalMode, ii, 1, eMode);
88104      }
88105    }
88106    sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
88107  }else
88108
88109  /*
88110  **  PRAGMA [database.]journal_size_limit
88111  **  PRAGMA [database.]journal_size_limit=N
88112  **
88113  ** Get or set the size limit on rollback journal files.
88114  */
88115  if( sqlite3StrICmp(zLeft,"journal_size_limit")==0 ){
88116    Pager *pPager = sqlite3BtreePager(pDb->pBt);
88117    i64 iLimit = -2;
88118    if( zRight ){
88119      sqlite3Atoi64(zRight, &iLimit, 1000000, SQLITE_UTF8);
88120      if( iLimit<-1 ) iLimit = -1;
88121    }
88122    iLimit = sqlite3PagerJournalSizeLimit(pPager, iLimit);
88123    returnSingleInt(pParse, "journal_size_limit", iLimit);
88124  }else
88125
88126#endif /* SQLITE_OMIT_PAGER_PRAGMAS */
88127
88128  /*
88129  **  PRAGMA [database.]auto_vacuum
88130  **  PRAGMA [database.]auto_vacuum=N
88131  **
88132  ** Get or set the value of the database 'auto-vacuum' parameter.
88133  ** The value is one of:  0 NONE 1 FULL 2 INCREMENTAL
88134  */
88135#ifndef SQLITE_OMIT_AUTOVACUUM
88136  if( sqlite3StrICmp(zLeft,"auto_vacuum")==0 ){
88137    Btree *pBt = pDb->pBt;
88138    assert( pBt!=0 );
88139    if( sqlite3ReadSchema(pParse) ){
88140      goto pragma_out;
88141    }
88142    if( !zRight ){
88143      int auto_vacuum;
88144      if( ALWAYS(pBt) ){
88145         auto_vacuum = sqlite3BtreeGetAutoVacuum(pBt);
88146      }else{
88147         auto_vacuum = SQLITE_DEFAULT_AUTOVACUUM;
88148      }
88149      returnSingleInt(pParse, "auto_vacuum", auto_vacuum);
88150    }else{
88151      int eAuto = getAutoVacuum(zRight);
88152      assert( eAuto>=0 && eAuto<=2 );
88153      db->nextAutovac = (u8)eAuto;
88154      if( ALWAYS(eAuto>=0) ){
88155        /* Call SetAutoVacuum() to set initialize the internal auto and
88156        ** incr-vacuum flags. This is required in case this connection
88157        ** creates the database file. It is important that it is created
88158        ** as an auto-vacuum capable db.
88159        */
88160        int rc = sqlite3BtreeSetAutoVacuum(pBt, eAuto);
88161        if( rc==SQLITE_OK && (eAuto==1 || eAuto==2) ){
88162          /* When setting the auto_vacuum mode to either "full" or
88163          ** "incremental", write the value of meta[6] in the database
88164          ** file. Before writing to meta[6], check that meta[3] indicates
88165          ** that this really is an auto-vacuum capable database.
88166          */
88167          static const VdbeOpList setMeta6[] = {
88168            { OP_Transaction,    0,         1,                 0},    /* 0 */
88169            { OP_ReadCookie,     0,         1,         BTREE_LARGEST_ROOT_PAGE},
88170            { OP_If,             1,         0,                 0},    /* 2 */
88171            { OP_Halt,           SQLITE_OK, OE_Abort,          0},    /* 3 */
88172            { OP_Integer,        0,         1,                 0},    /* 4 */
88173            { OP_SetCookie,      0,         BTREE_INCR_VACUUM, 1},    /* 5 */
88174          };
88175          int iAddr;
88176          iAddr = sqlite3VdbeAddOpList(v, ArraySize(setMeta6), setMeta6);
88177          sqlite3VdbeChangeP1(v, iAddr, iDb);
88178          sqlite3VdbeChangeP1(v, iAddr+1, iDb);
88179          sqlite3VdbeChangeP2(v, iAddr+2, iAddr+4);
88180          sqlite3VdbeChangeP1(v, iAddr+4, eAuto-1);
88181          sqlite3VdbeChangeP1(v, iAddr+5, iDb);
88182          sqlite3VdbeUsesBtree(v, iDb);
88183        }
88184      }
88185    }
88186  }else
88187#endif
88188
88189  /*
88190  **  PRAGMA [database.]incremental_vacuum(N)
88191  **
88192  ** Do N steps of incremental vacuuming on a database.
88193  */
88194#ifndef SQLITE_OMIT_AUTOVACUUM
88195  if( sqlite3StrICmp(zLeft,"incremental_vacuum")==0 ){
88196    int iLimit, addr;
88197    if( sqlite3ReadSchema(pParse) ){
88198      goto pragma_out;
88199    }
88200    if( zRight==0 || !sqlite3GetInt32(zRight, &iLimit) || iLimit<=0 ){
88201      iLimit = 0x7fffffff;
88202    }
88203    sqlite3BeginWriteOperation(pParse, 0, iDb);
88204    sqlite3VdbeAddOp2(v, OP_Integer, iLimit, 1);
88205    addr = sqlite3VdbeAddOp1(v, OP_IncrVacuum, iDb);
88206    sqlite3VdbeAddOp1(v, OP_ResultRow, 1);
88207    sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1);
88208    sqlite3VdbeAddOp2(v, OP_IfPos, 1, addr);
88209    sqlite3VdbeJumpHere(v, addr);
88210  }else
88211#endif
88212
88213#ifndef SQLITE_OMIT_PAGER_PRAGMAS
88214  /*
88215  **  PRAGMA [database.]cache_size
88216  **  PRAGMA [database.]cache_size=N
88217  **
88218  ** The first form reports the current local setting for the
88219  ** page cache size.  The local setting can be different from
88220  ** the persistent cache size value that is stored in the database
88221  ** file itself.  The value returned is the maximum number of
88222  ** pages in the page cache.  The second form sets the local
88223  ** page cache size value.  It does not change the persistent
88224  ** cache size stored on the disk so the cache size will revert
88225  ** to its default value when the database is closed and reopened.
88226  ** N should be a positive integer.
88227  */
88228  if( sqlite3StrICmp(zLeft,"cache_size")==0 ){
88229    if( sqlite3ReadSchema(pParse) ) goto pragma_out;
88230    assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
88231    if( !zRight ){
88232      returnSingleInt(pParse, "cache_size", pDb->pSchema->cache_size);
88233    }else{
88234      int size = sqlite3AbsInt32(sqlite3Atoi(zRight));
88235      pDb->pSchema->cache_size = size;
88236      sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
88237    }
88238  }else
88239
88240  /*
88241  **   PRAGMA temp_store
88242  **   PRAGMA temp_store = "default"|"memory"|"file"
88243  **
88244  ** Return or set the local value of the temp_store flag.  Changing
88245  ** the local value does not make changes to the disk file and the default
88246  ** value will be restored the next time the database is opened.
88247  **
88248  ** Note that it is possible for the library compile-time options to
88249  ** override this setting
88250  */
88251  if( sqlite3StrICmp(zLeft, "temp_store")==0 ){
88252    if( !zRight ){
88253      returnSingleInt(pParse, "temp_store", db->temp_store);
88254    }else{
88255      changeTempStorage(pParse, zRight);
88256    }
88257  }else
88258
88259  /*
88260  **   PRAGMA temp_store_directory
88261  **   PRAGMA temp_store_directory = ""|"directory_name"
88262  **
88263  ** Return or set the local value of the temp_store_directory flag.  Changing
88264  ** the value sets a specific directory to be used for temporary files.
88265  ** Setting to a null string reverts to the default temporary directory search.
88266  ** If temporary directory is changed, then invalidateTempStorage.
88267  **
88268  */
88269  if( sqlite3StrICmp(zLeft, "temp_store_directory")==0 ){
88270    if( !zRight ){
88271      if( sqlite3_temp_directory ){
88272        sqlite3VdbeSetNumCols(v, 1);
88273        sqlite3VdbeSetColName(v, 0, COLNAME_NAME,
88274            "temp_store_directory", SQLITE_STATIC);
88275        sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, sqlite3_temp_directory, 0);
88276        sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
88277      }
88278    }else{
88279#ifndef SQLITE_OMIT_WSD
88280      if( zRight[0] ){
88281        int rc;
88282        int res;
88283        rc = sqlite3OsAccess(db->pVfs, zRight, SQLITE_ACCESS_READWRITE, &res);
88284        if( rc!=SQLITE_OK || res==0 ){
88285          sqlite3ErrorMsg(pParse, "not a writable directory");
88286          goto pragma_out;
88287        }
88288      }
88289      if( SQLITE_TEMP_STORE==0
88290       || (SQLITE_TEMP_STORE==1 && db->temp_store<=1)
88291       || (SQLITE_TEMP_STORE==2 && db->temp_store==1)
88292      ){
88293        invalidateTempStorage(pParse);
88294      }
88295      sqlite3_free(sqlite3_temp_directory);
88296      if( zRight[0] ){
88297        sqlite3_temp_directory = sqlite3_mprintf("%s", zRight);
88298      }else{
88299        sqlite3_temp_directory = 0;
88300      }
88301#endif /* SQLITE_OMIT_WSD */
88302    }
88303  }else
88304
88305#if !defined(SQLITE_ENABLE_LOCKING_STYLE)
88306#  if defined(__APPLE__)
88307#    define SQLITE_ENABLE_LOCKING_STYLE 1
88308#  else
88309#    define SQLITE_ENABLE_LOCKING_STYLE 0
88310#  endif
88311#endif
88312#if SQLITE_ENABLE_LOCKING_STYLE
88313  /*
88314   **   PRAGMA [database.]lock_proxy_file
88315   **   PRAGMA [database.]lock_proxy_file = ":auto:"|"lock_file_path"
88316   **
88317   ** Return or set the value of the lock_proxy_file flag.  Changing
88318   ** the value sets a specific file to be used for database access locks.
88319   **
88320   */
88321  if( sqlite3StrICmp(zLeft, "lock_proxy_file")==0 ){
88322    if( !zRight ){
88323      Pager *pPager = sqlite3BtreePager(pDb->pBt);
88324      char *proxy_file_path = NULL;
88325      sqlite3_file *pFile = sqlite3PagerFile(pPager);
88326      sqlite3OsFileControl(pFile, SQLITE_GET_LOCKPROXYFILE,
88327                           &proxy_file_path);
88328
88329      if( proxy_file_path ){
88330        sqlite3VdbeSetNumCols(v, 1);
88331        sqlite3VdbeSetColName(v, 0, COLNAME_NAME,
88332                              "lock_proxy_file", SQLITE_STATIC);
88333        sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, proxy_file_path, 0);
88334        sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
88335      }
88336    }else{
88337      Pager *pPager = sqlite3BtreePager(pDb->pBt);
88338      sqlite3_file *pFile = sqlite3PagerFile(pPager);
88339      int res;
88340      if( zRight[0] ){
88341        res=sqlite3OsFileControl(pFile, SQLITE_SET_LOCKPROXYFILE,
88342                                     zRight);
88343      } else {
88344        res=sqlite3OsFileControl(pFile, SQLITE_SET_LOCKPROXYFILE,
88345                                     NULL);
88346      }
88347      if( res!=SQLITE_OK ){
88348        sqlite3ErrorMsg(pParse, "failed to set lock proxy file");
88349        goto pragma_out;
88350      }
88351    }
88352  }else
88353#endif /* SQLITE_ENABLE_LOCKING_STYLE */
88354
88355  /*
88356  **   PRAGMA [database.]synchronous
88357  **   PRAGMA [database.]synchronous=OFF|ON|NORMAL|FULL
88358  **
88359  ** Return or set the local value of the synchronous flag.  Changing
88360  ** the local value does not make changes to the disk file and the
88361  ** default value will be restored the next time the database is
88362  ** opened.
88363  */
88364  if( sqlite3StrICmp(zLeft,"synchronous")==0 ){
88365    if( sqlite3ReadSchema(pParse) ) goto pragma_out;
88366    if( !zRight ){
88367      returnSingleInt(pParse, "synchronous", pDb->safety_level-1);
88368    }else{
88369      if( !db->autoCommit ){
88370        sqlite3ErrorMsg(pParse,
88371            "Safety level may not be changed inside a transaction");
88372      }else{
88373        pDb->safety_level = getSafetyLevel(zRight)+1;
88374      }
88375    }
88376  }else
88377#endif /* SQLITE_OMIT_PAGER_PRAGMAS */
88378
88379#ifndef SQLITE_OMIT_FLAG_PRAGMAS
88380  if( flagPragma(pParse, zLeft, zRight) ){
88381    /* The flagPragma() subroutine also generates any necessary code
88382    ** there is nothing more to do here */
88383  }else
88384#endif /* SQLITE_OMIT_FLAG_PRAGMAS */
88385
88386#ifndef SQLITE_OMIT_SCHEMA_PRAGMAS
88387  /*
88388  **   PRAGMA table_info(<table>)
88389  **
88390  ** Return a single row for each column of the named table. The columns of
88391  ** the returned data set are:
88392  **
88393  ** cid:        Column id (numbered from left to right, starting at 0)
88394  ** name:       Column name
88395  ** type:       Column declaration type.
88396  ** notnull:    True if 'NOT NULL' is part of column declaration
88397  ** dflt_value: The default value for the column, if any.
88398  */
88399  if( sqlite3StrICmp(zLeft, "table_info")==0 && zRight ){
88400    Table *pTab;
88401    if( sqlite3ReadSchema(pParse) ) goto pragma_out;
88402    pTab = sqlite3FindTable(db, zRight, zDb);
88403    if( pTab ){
88404      int i;
88405      int nHidden = 0;
88406      Column *pCol;
88407      sqlite3VdbeSetNumCols(v, 6);
88408      pParse->nMem = 6;
88409      sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "cid", SQLITE_STATIC);
88410      sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
88411      sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "type", SQLITE_STATIC);
88412      sqlite3VdbeSetColName(v, 3, COLNAME_NAME, "notnull", SQLITE_STATIC);
88413      sqlite3VdbeSetColName(v, 4, COLNAME_NAME, "dflt_value", SQLITE_STATIC);
88414      sqlite3VdbeSetColName(v, 5, COLNAME_NAME, "pk", SQLITE_STATIC);
88415      sqlite3ViewGetColumnNames(pParse, pTab);
88416      for(i=0, pCol=pTab->aCol; i<pTab->nCol; i++, pCol++){
88417        if( IsHiddenColumn(pCol) ){
88418          nHidden++;
88419          continue;
88420        }
88421        sqlite3VdbeAddOp2(v, OP_Integer, i-nHidden, 1);
88422        sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pCol->zName, 0);
88423        sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
88424           pCol->zType ? pCol->zType : "", 0);
88425        sqlite3VdbeAddOp2(v, OP_Integer, (pCol->notNull ? 1 : 0), 4);
88426        if( pCol->zDflt ){
88427          sqlite3VdbeAddOp4(v, OP_String8, 0, 5, 0, (char*)pCol->zDflt, 0);
88428        }else{
88429          sqlite3VdbeAddOp2(v, OP_Null, 0, 5);
88430        }
88431        sqlite3VdbeAddOp2(v, OP_Integer, pCol->isPrimKey, 6);
88432        sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 6);
88433      }
88434    }
88435  }else
88436
88437  if( sqlite3StrICmp(zLeft, "index_info")==0 && zRight ){
88438    Index *pIdx;
88439    Table *pTab;
88440    if( sqlite3ReadSchema(pParse) ) goto pragma_out;
88441    pIdx = sqlite3FindIndex(db, zRight, zDb);
88442    if( pIdx ){
88443      int i;
88444      pTab = pIdx->pTable;
88445      sqlite3VdbeSetNumCols(v, 3);
88446      pParse->nMem = 3;
88447      sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seqno", SQLITE_STATIC);
88448      sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "cid", SQLITE_STATIC);
88449      sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "name", SQLITE_STATIC);
88450      for(i=0; i<pIdx->nColumn; i++){
88451        int cnum = pIdx->aiColumn[i];
88452        sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
88453        sqlite3VdbeAddOp2(v, OP_Integer, cnum, 2);
88454        assert( pTab->nCol>cnum );
88455        sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, pTab->aCol[cnum].zName, 0);
88456        sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
88457      }
88458    }
88459  }else
88460
88461  if( sqlite3StrICmp(zLeft, "index_list")==0 && zRight ){
88462    Index *pIdx;
88463    Table *pTab;
88464    if( sqlite3ReadSchema(pParse) ) goto pragma_out;
88465    pTab = sqlite3FindTable(db, zRight, zDb);
88466    if( pTab ){
88467      v = sqlite3GetVdbe(pParse);
88468      pIdx = pTab->pIndex;
88469      if( pIdx ){
88470        int i = 0;
88471        sqlite3VdbeSetNumCols(v, 3);
88472        pParse->nMem = 3;
88473        sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", SQLITE_STATIC);
88474        sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
88475        sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "unique", SQLITE_STATIC);
88476        while(pIdx){
88477          sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
88478          sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pIdx->zName, 0);
88479          sqlite3VdbeAddOp2(v, OP_Integer, pIdx->onError!=OE_None, 3);
88480          sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
88481          ++i;
88482          pIdx = pIdx->pNext;
88483        }
88484      }
88485    }
88486  }else
88487
88488  if( sqlite3StrICmp(zLeft, "database_list")==0 ){
88489    int i;
88490    if( sqlite3ReadSchema(pParse) ) goto pragma_out;
88491    sqlite3VdbeSetNumCols(v, 3);
88492    pParse->nMem = 3;
88493    sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", SQLITE_STATIC);
88494    sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
88495    sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "file", SQLITE_STATIC);
88496    for(i=0; i<db->nDb; i++){
88497      if( db->aDb[i].pBt==0 ) continue;
88498      assert( db->aDb[i].zName!=0 );
88499      sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
88500      sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, db->aDb[i].zName, 0);
88501      sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
88502           sqlite3BtreeGetFilename(db->aDb[i].pBt), 0);
88503      sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
88504    }
88505  }else
88506
88507  if( sqlite3StrICmp(zLeft, "collation_list")==0 ){
88508    int i = 0;
88509    HashElem *p;
88510    sqlite3VdbeSetNumCols(v, 2);
88511    pParse->nMem = 2;
88512    sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", SQLITE_STATIC);
88513    sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
88514    for(p=sqliteHashFirst(&db->aCollSeq); p; p=sqliteHashNext(p)){
88515      CollSeq *pColl = (CollSeq *)sqliteHashData(p);
88516      sqlite3VdbeAddOp2(v, OP_Integer, i++, 1);
88517      sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pColl->zName, 0);
88518      sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 2);
88519    }
88520  }else
88521#endif /* SQLITE_OMIT_SCHEMA_PRAGMAS */
88522
88523#ifndef SQLITE_OMIT_FOREIGN_KEY
88524  if( sqlite3StrICmp(zLeft, "foreign_key_list")==0 && zRight ){
88525    FKey *pFK;
88526    Table *pTab;
88527    if( sqlite3ReadSchema(pParse) ) goto pragma_out;
88528    pTab = sqlite3FindTable(db, zRight, zDb);
88529    if( pTab ){
88530      v = sqlite3GetVdbe(pParse);
88531      pFK = pTab->pFKey;
88532      if( pFK ){
88533        int i = 0;
88534        sqlite3VdbeSetNumCols(v, 8);
88535        pParse->nMem = 8;
88536        sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "id", SQLITE_STATIC);
88537        sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "seq", SQLITE_STATIC);
88538        sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "table", SQLITE_STATIC);
88539        sqlite3VdbeSetColName(v, 3, COLNAME_NAME, "from", SQLITE_STATIC);
88540        sqlite3VdbeSetColName(v, 4, COLNAME_NAME, "to", SQLITE_STATIC);
88541        sqlite3VdbeSetColName(v, 5, COLNAME_NAME, "on_update", SQLITE_STATIC);
88542        sqlite3VdbeSetColName(v, 6, COLNAME_NAME, "on_delete", SQLITE_STATIC);
88543        sqlite3VdbeSetColName(v, 7, COLNAME_NAME, "match", SQLITE_STATIC);
88544        while(pFK){
88545          int j;
88546          for(j=0; j<pFK->nCol; j++){
88547            char *zCol = pFK->aCol[j].zCol;
88548            char *zOnDelete = (char *)actionName(pFK->aAction[0]);
88549            char *zOnUpdate = (char *)actionName(pFK->aAction[1]);
88550            sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
88551            sqlite3VdbeAddOp2(v, OP_Integer, j, 2);
88552            sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, pFK->zTo, 0);
88553            sqlite3VdbeAddOp4(v, OP_String8, 0, 4, 0,
88554                              pTab->aCol[pFK->aCol[j].iFrom].zName, 0);
88555            sqlite3VdbeAddOp4(v, zCol ? OP_String8 : OP_Null, 0, 5, 0, zCol, 0);
88556            sqlite3VdbeAddOp4(v, OP_String8, 0, 6, 0, zOnUpdate, 0);
88557            sqlite3VdbeAddOp4(v, OP_String8, 0, 7, 0, zOnDelete, 0);
88558            sqlite3VdbeAddOp4(v, OP_String8, 0, 8, 0, "NONE", 0);
88559            sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 8);
88560          }
88561          ++i;
88562          pFK = pFK->pNextFrom;
88563        }
88564      }
88565    }
88566  }else
88567#endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
88568
88569#ifndef NDEBUG
88570  if( sqlite3StrICmp(zLeft, "parser_trace")==0 ){
88571    if( zRight ){
88572      if( getBoolean(zRight) ){
88573        sqlite3ParserTrace(stderr, "parser: ");
88574      }else{
88575        sqlite3ParserTrace(0, 0);
88576      }
88577    }
88578  }else
88579#endif
88580
88581  /* Reinstall the LIKE and GLOB functions.  The variant of LIKE
88582  ** used will be case sensitive or not depending on the RHS.
88583  */
88584  if( sqlite3StrICmp(zLeft, "case_sensitive_like")==0 ){
88585    if( zRight ){
88586      sqlite3RegisterLikeFunctions(db, getBoolean(zRight));
88587    }
88588  }else
88589
88590#ifndef SQLITE_INTEGRITY_CHECK_ERROR_MAX
88591# define SQLITE_INTEGRITY_CHECK_ERROR_MAX 100
88592#endif
88593
88594#ifndef SQLITE_OMIT_INTEGRITY_CHECK
88595  /* Pragma "quick_check" is an experimental reduced version of
88596  ** integrity_check designed to detect most database corruption
88597  ** without most of the overhead of a full integrity-check.
88598  */
88599  if( sqlite3StrICmp(zLeft, "integrity_check")==0
88600   || sqlite3StrICmp(zLeft, "quick_check")==0
88601  ){
88602    int i, j, addr, mxErr;
88603
88604    /* Code that appears at the end of the integrity check.  If no error
88605    ** messages have been generated, output OK.  Otherwise output the
88606    ** error message
88607    */
88608    static const VdbeOpList endCode[] = {
88609      { OP_AddImm,      1, 0,        0},    /* 0 */
88610      { OP_IfNeg,       1, 0,        0},    /* 1 */
88611      { OP_String8,     0, 3,        0},    /* 2 */
88612      { OP_ResultRow,   3, 1,        0},
88613    };
88614
88615    int isQuick = (zLeft[0]=='q');
88616
88617    /* Initialize the VDBE program */
88618    if( sqlite3ReadSchema(pParse) ) goto pragma_out;
88619    pParse->nMem = 6;
88620    sqlite3VdbeSetNumCols(v, 1);
88621    sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "integrity_check", SQLITE_STATIC);
88622
88623    /* Set the maximum error count */
88624    mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;
88625    if( zRight ){
88626      sqlite3GetInt32(zRight, &mxErr);
88627      if( mxErr<=0 ){
88628        mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;
88629      }
88630    }
88631    sqlite3VdbeAddOp2(v, OP_Integer, mxErr, 1);  /* reg[1] holds errors left */
88632
88633    /* Do an integrity check on each database file */
88634    for(i=0; i<db->nDb; i++){
88635      HashElem *x;
88636      Hash *pTbls;
88637      int cnt = 0;
88638
88639      if( OMIT_TEMPDB && i==1 ) continue;
88640
88641      sqlite3CodeVerifySchema(pParse, i);
88642      addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1); /* Halt if out of errors */
88643      sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
88644      sqlite3VdbeJumpHere(v, addr);
88645
88646      /* Do an integrity check of the B-Tree
88647      **
88648      ** Begin by filling registers 2, 3, ... with the root pages numbers
88649      ** for all tables and indices in the database.
88650      */
88651      assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
88652      pTbls = &db->aDb[i].pSchema->tblHash;
88653      for(x=sqliteHashFirst(pTbls); x; x=sqliteHashNext(x)){
88654        Table *pTab = sqliteHashData(x);
88655        Index *pIdx;
88656        sqlite3VdbeAddOp2(v, OP_Integer, pTab->tnum, 2+cnt);
88657        cnt++;
88658        for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
88659          sqlite3VdbeAddOp2(v, OP_Integer, pIdx->tnum, 2+cnt);
88660          cnt++;
88661        }
88662      }
88663
88664      /* Make sure sufficient number of registers have been allocated */
88665      if( pParse->nMem < cnt+4 ){
88666        pParse->nMem = cnt+4;
88667      }
88668
88669      /* Do the b-tree integrity checks */
88670      sqlite3VdbeAddOp3(v, OP_IntegrityCk, 2, cnt, 1);
88671      sqlite3VdbeChangeP5(v, (u8)i);
88672      addr = sqlite3VdbeAddOp1(v, OP_IsNull, 2);
88673      sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
88674         sqlite3MPrintf(db, "*** in database %s ***\n", db->aDb[i].zName),
88675         P4_DYNAMIC);
88676      sqlite3VdbeAddOp3(v, OP_Move, 2, 4, 1);
88677      sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 2);
88678      sqlite3VdbeAddOp2(v, OP_ResultRow, 2, 1);
88679      sqlite3VdbeJumpHere(v, addr);
88680
88681      /* Make sure all the indices are constructed correctly.
88682      */
88683      for(x=sqliteHashFirst(pTbls); x && !isQuick; x=sqliteHashNext(x)){
88684        Table *pTab = sqliteHashData(x);
88685        Index *pIdx;
88686        int loopTop;
88687
88688        if( pTab->pIndex==0 ) continue;
88689        addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1);  /* Stop if out of errors */
88690        sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
88691        sqlite3VdbeJumpHere(v, addr);
88692        sqlite3OpenTableAndIndices(pParse, pTab, 1, OP_OpenRead);
88693        sqlite3VdbeAddOp2(v, OP_Integer, 0, 2);  /* reg(2) will count entries */
88694        loopTop = sqlite3VdbeAddOp2(v, OP_Rewind, 1, 0);
88695        sqlite3VdbeAddOp2(v, OP_AddImm, 2, 1);   /* increment entry count */
88696        for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
88697          int jmp2;
88698          int r1;
88699          static const VdbeOpList idxErr[] = {
88700            { OP_AddImm,      1, -1,  0},
88701            { OP_String8,     0,  3,  0},    /* 1 */
88702            { OP_Rowid,       1,  4,  0},
88703            { OP_String8,     0,  5,  0},    /* 3 */
88704            { OP_String8,     0,  6,  0},    /* 4 */
88705            { OP_Concat,      4,  3,  3},
88706            { OP_Concat,      5,  3,  3},
88707            { OP_Concat,      6,  3,  3},
88708            { OP_ResultRow,   3,  1,  0},
88709            { OP_IfPos,       1,  0,  0},    /* 9 */
88710            { OP_Halt,        0,  0,  0},
88711          };
88712          r1 = sqlite3GenerateIndexKey(pParse, pIdx, 1, 3, 0);
88713          jmp2 = sqlite3VdbeAddOp4Int(v, OP_Found, j+2, 0, r1, pIdx->nColumn+1);
88714          addr = sqlite3VdbeAddOpList(v, ArraySize(idxErr), idxErr);
88715          sqlite3VdbeChangeP4(v, addr+1, "rowid ", P4_STATIC);
88716          sqlite3VdbeChangeP4(v, addr+3, " missing from index ", P4_STATIC);
88717          sqlite3VdbeChangeP4(v, addr+4, pIdx->zName, P4_TRANSIENT);
88718          sqlite3VdbeJumpHere(v, addr+9);
88719          sqlite3VdbeJumpHere(v, jmp2);
88720        }
88721        sqlite3VdbeAddOp2(v, OP_Next, 1, loopTop+1);
88722        sqlite3VdbeJumpHere(v, loopTop);
88723        for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
88724          static const VdbeOpList cntIdx[] = {
88725             { OP_Integer,      0,  3,  0},
88726             { OP_Rewind,       0,  0,  0},  /* 1 */
88727             { OP_AddImm,       3,  1,  0},
88728             { OP_Next,         0,  0,  0},  /* 3 */
88729             { OP_Eq,           2,  0,  3},  /* 4 */
88730             { OP_AddImm,       1, -1,  0},
88731             { OP_String8,      0,  2,  0},  /* 6 */
88732             { OP_String8,      0,  3,  0},  /* 7 */
88733             { OP_Concat,       3,  2,  2},
88734             { OP_ResultRow,    2,  1,  0},
88735          };
88736          addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1);
88737          sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
88738          sqlite3VdbeJumpHere(v, addr);
88739          addr = sqlite3VdbeAddOpList(v, ArraySize(cntIdx), cntIdx);
88740          sqlite3VdbeChangeP1(v, addr+1, j+2);
88741          sqlite3VdbeChangeP2(v, addr+1, addr+4);
88742          sqlite3VdbeChangeP1(v, addr+3, j+2);
88743          sqlite3VdbeChangeP2(v, addr+3, addr+2);
88744          sqlite3VdbeJumpHere(v, addr+4);
88745          sqlite3VdbeChangeP4(v, addr+6,
88746                     "wrong # of entries in index ", P4_STATIC);
88747          sqlite3VdbeChangeP4(v, addr+7, pIdx->zName, P4_TRANSIENT);
88748        }
88749      }
88750    }
88751    addr = sqlite3VdbeAddOpList(v, ArraySize(endCode), endCode);
88752    sqlite3VdbeChangeP2(v, addr, -mxErr);
88753    sqlite3VdbeJumpHere(v, addr+1);
88754    sqlite3VdbeChangeP4(v, addr+2, "ok", P4_STATIC);
88755  }else
88756#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
88757
88758#ifndef SQLITE_OMIT_UTF16
88759  /*
88760  **   PRAGMA encoding
88761  **   PRAGMA encoding = "utf-8"|"utf-16"|"utf-16le"|"utf-16be"
88762  **
88763  ** In its first form, this pragma returns the encoding of the main
88764  ** database. If the database is not initialized, it is initialized now.
88765  **
88766  ** The second form of this pragma is a no-op if the main database file
88767  ** has not already been initialized. In this case it sets the default
88768  ** encoding that will be used for the main database file if a new file
88769  ** is created. If an existing main database file is opened, then the
88770  ** default text encoding for the existing database is used.
88771  **
88772  ** In all cases new databases created using the ATTACH command are
88773  ** created to use the same default text encoding as the main database. If
88774  ** the main database has not been initialized and/or created when ATTACH
88775  ** is executed, this is done before the ATTACH operation.
88776  **
88777  ** In the second form this pragma sets the text encoding to be used in
88778  ** new database files created using this database handle. It is only
88779  ** useful if invoked immediately after the main database i
88780  */
88781  if( sqlite3StrICmp(zLeft, "encoding")==0 ){
88782    static const struct EncName {
88783      char *zName;
88784      u8 enc;
88785    } encnames[] = {
88786      { "UTF8",     SQLITE_UTF8        },
88787      { "UTF-8",    SQLITE_UTF8        },  /* Must be element [1] */
88788      { "UTF-16le", SQLITE_UTF16LE     },  /* Must be element [2] */
88789      { "UTF-16be", SQLITE_UTF16BE     },  /* Must be element [3] */
88790      { "UTF16le",  SQLITE_UTF16LE     },
88791      { "UTF16be",  SQLITE_UTF16BE     },
88792      { "UTF-16",   0                  }, /* SQLITE_UTF16NATIVE */
88793      { "UTF16",    0                  }, /* SQLITE_UTF16NATIVE */
88794      { 0, 0 }
88795    };
88796    const struct EncName *pEnc;
88797    if( !zRight ){    /* "PRAGMA encoding" */
88798      if( sqlite3ReadSchema(pParse) ) goto pragma_out;
88799      sqlite3VdbeSetNumCols(v, 1);
88800      sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "encoding", SQLITE_STATIC);
88801      sqlite3VdbeAddOp2(v, OP_String8, 0, 1);
88802      assert( encnames[SQLITE_UTF8].enc==SQLITE_UTF8 );
88803      assert( encnames[SQLITE_UTF16LE].enc==SQLITE_UTF16LE );
88804      assert( encnames[SQLITE_UTF16BE].enc==SQLITE_UTF16BE );
88805      sqlite3VdbeChangeP4(v, -1, encnames[ENC(pParse->db)].zName, P4_STATIC);
88806      sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
88807    }else{                        /* "PRAGMA encoding = XXX" */
88808      /* Only change the value of sqlite.enc if the database handle is not
88809      ** initialized. If the main database exists, the new sqlite.enc value
88810      ** will be overwritten when the schema is next loaded. If it does not
88811      ** already exists, it will be created to use the new encoding value.
88812      */
88813      if(
88814        !(DbHasProperty(db, 0, DB_SchemaLoaded)) ||
88815        DbHasProperty(db, 0, DB_Empty)
88816      ){
88817        for(pEnc=&encnames[0]; pEnc->zName; pEnc++){
88818          if( 0==sqlite3StrICmp(zRight, pEnc->zName) ){
88819            ENC(pParse->db) = pEnc->enc ? pEnc->enc : SQLITE_UTF16NATIVE;
88820            break;
88821          }
88822        }
88823        if( !pEnc->zName ){
88824          sqlite3ErrorMsg(pParse, "unsupported encoding: %s", zRight);
88825        }
88826      }
88827    }
88828  }else
88829#endif /* SQLITE_OMIT_UTF16 */
88830
88831#ifndef SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS
88832  /*
88833  **   PRAGMA [database.]schema_version
88834  **   PRAGMA [database.]schema_version = <integer>
88835  **
88836  **   PRAGMA [database.]user_version
88837  **   PRAGMA [database.]user_version = <integer>
88838  **
88839  ** The pragma's schema_version and user_version are used to set or get
88840  ** the value of the schema-version and user-version, respectively. Both
88841  ** the schema-version and the user-version are 32-bit signed integers
88842  ** stored in the database header.
88843  **
88844  ** The schema-cookie is usually only manipulated internally by SQLite. It
88845  ** is incremented by SQLite whenever the database schema is modified (by
88846  ** creating or dropping a table or index). The schema version is used by
88847  ** SQLite each time a query is executed to ensure that the internal cache
88848  ** of the schema used when compiling the SQL query matches the schema of
88849  ** the database against which the compiled query is actually executed.
88850  ** Subverting this mechanism by using "PRAGMA schema_version" to modify
88851  ** the schema-version is potentially dangerous and may lead to program
88852  ** crashes or database corruption. Use with caution!
88853  **
88854  ** The user-version is not used internally by SQLite. It may be used by
88855  ** applications for any purpose.
88856  */
88857  if( sqlite3StrICmp(zLeft, "schema_version")==0
88858   || sqlite3StrICmp(zLeft, "user_version")==0
88859   || sqlite3StrICmp(zLeft, "freelist_count")==0
88860  ){
88861    int iCookie;   /* Cookie index. 1 for schema-cookie, 6 for user-cookie. */
88862    sqlite3VdbeUsesBtree(v, iDb);
88863    switch( zLeft[0] ){
88864      case 'f': case 'F':
88865        iCookie = BTREE_FREE_PAGE_COUNT;
88866        break;
88867      case 's': case 'S':
88868        iCookie = BTREE_SCHEMA_VERSION;
88869        break;
88870      default:
88871        iCookie = BTREE_USER_VERSION;
88872        break;
88873    }
88874
88875    if( zRight && iCookie!=BTREE_FREE_PAGE_COUNT ){
88876      /* Write the specified cookie value */
88877      static const VdbeOpList setCookie[] = {
88878        { OP_Transaction,    0,  1,  0},    /* 0 */
88879        { OP_Integer,        0,  1,  0},    /* 1 */
88880        { OP_SetCookie,      0,  0,  1},    /* 2 */
88881      };
88882      int addr = sqlite3VdbeAddOpList(v, ArraySize(setCookie), setCookie);
88883      sqlite3VdbeChangeP1(v, addr, iDb);
88884      sqlite3VdbeChangeP1(v, addr+1, sqlite3Atoi(zRight));
88885      sqlite3VdbeChangeP1(v, addr+2, iDb);
88886      sqlite3VdbeChangeP2(v, addr+2, iCookie);
88887    }else{
88888      /* Read the specified cookie value */
88889      static const VdbeOpList readCookie[] = {
88890        { OP_Transaction,     0,  0,  0},    /* 0 */
88891        { OP_ReadCookie,      0,  1,  0},    /* 1 */
88892        { OP_ResultRow,       1,  1,  0}
88893      };
88894      int addr = sqlite3VdbeAddOpList(v, ArraySize(readCookie), readCookie);
88895      sqlite3VdbeChangeP1(v, addr, iDb);
88896      sqlite3VdbeChangeP1(v, addr+1, iDb);
88897      sqlite3VdbeChangeP3(v, addr+1, iCookie);
88898      sqlite3VdbeSetNumCols(v, 1);
88899      sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLeft, SQLITE_TRANSIENT);
88900    }
88901  }else
88902#endif /* SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS */
88903
88904#ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
88905  /*
88906  **   PRAGMA compile_options
88907  **
88908  ** Return the names of all compile-time options used in this build,
88909  ** one option per row.
88910  */
88911  if( sqlite3StrICmp(zLeft, "compile_options")==0 ){
88912    int i = 0;
88913    const char *zOpt;
88914    sqlite3VdbeSetNumCols(v, 1);
88915    pParse->nMem = 1;
88916    sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "compile_option", SQLITE_STATIC);
88917    while( (zOpt = sqlite3_compileoption_get(i++))!=0 ){
88918      sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, zOpt, 0);
88919      sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
88920    }
88921  }else
88922#endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
88923
88924#ifndef SQLITE_OMIT_WAL
88925  /*
88926  **   PRAGMA [database.]wal_checkpoint = passive|full|restart
88927  **
88928  ** Checkpoint the database.
88929  */
88930  if( sqlite3StrICmp(zLeft, "wal_checkpoint")==0 ){
88931    int iBt = (pId2->z?iDb:SQLITE_MAX_ATTACHED);
88932    int eMode = SQLITE_CHECKPOINT_PASSIVE;
88933    if( zRight ){
88934      if( sqlite3StrICmp(zRight, "full")==0 ){
88935        eMode = SQLITE_CHECKPOINT_FULL;
88936      }else if( sqlite3StrICmp(zRight, "restart")==0 ){
88937        eMode = SQLITE_CHECKPOINT_RESTART;
88938      }
88939    }
88940    if( sqlite3ReadSchema(pParse) ) goto pragma_out;
88941    sqlite3VdbeSetNumCols(v, 3);
88942    pParse->nMem = 3;
88943    sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "busy", SQLITE_STATIC);
88944    sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "log", SQLITE_STATIC);
88945    sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "checkpointed", SQLITE_STATIC);
88946
88947    sqlite3VdbeAddOp3(v, OP_Checkpoint, iBt, eMode, 1);
88948    sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
88949  }else
88950
88951  /*
88952  **   PRAGMA wal_autocheckpoint
88953  **   PRAGMA wal_autocheckpoint = N
88954  **
88955  ** Configure a database connection to automatically checkpoint a database
88956  ** after accumulating N frames in the log. Or query for the current value
88957  ** of N.
88958  */
88959  if( sqlite3StrICmp(zLeft, "wal_autocheckpoint")==0 ){
88960    if( zRight ){
88961      sqlite3_wal_autocheckpoint(db, sqlite3Atoi(zRight));
88962    }
88963    returnSingleInt(pParse, "wal_autocheckpoint",
88964       db->xWalCallback==sqlite3WalDefaultHook ?
88965           SQLITE_PTR_TO_INT(db->pWalArg) : 0);
88966  }else
88967#endif
88968
88969#if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
88970  /*
88971  ** Report the current state of file logs for all databases
88972  */
88973  if( sqlite3StrICmp(zLeft, "lock_status")==0 ){
88974    static const char *const azLockName[] = {
88975      "unlocked", "shared", "reserved", "pending", "exclusive"
88976    };
88977    int i;
88978    sqlite3VdbeSetNumCols(v, 2);
88979    pParse->nMem = 2;
88980    sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "database", SQLITE_STATIC);
88981    sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "status", SQLITE_STATIC);
88982    for(i=0; i<db->nDb; i++){
88983      Btree *pBt;
88984      Pager *pPager;
88985      const char *zState = "unknown";
88986      int j;
88987      if( db->aDb[i].zName==0 ) continue;
88988      sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, db->aDb[i].zName, P4_STATIC);
88989      pBt = db->aDb[i].pBt;
88990      if( pBt==0 || (pPager = sqlite3BtreePager(pBt))==0 ){
88991        zState = "closed";
88992      }else if( sqlite3_file_control(db, i ? db->aDb[i].zName : 0,
88993                                     SQLITE_FCNTL_LOCKSTATE, &j)==SQLITE_OK ){
88994         zState = azLockName[j];
88995      }
88996      sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, zState, P4_STATIC);
88997      sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 2);
88998    }
88999
89000  }else
89001#endif
89002
89003#ifdef SQLITE_HAS_CODEC
89004  if( sqlite3StrICmp(zLeft, "key")==0 && zRight ){
89005    sqlite3_key(db, zRight, sqlite3Strlen30(zRight));
89006  }else
89007  if( sqlite3StrICmp(zLeft, "rekey")==0 && zRight ){
89008    sqlite3_rekey(db, zRight, sqlite3Strlen30(zRight));
89009  }else
89010  if( zRight && (sqlite3StrICmp(zLeft, "hexkey")==0 ||
89011                 sqlite3StrICmp(zLeft, "hexrekey")==0) ){
89012    int i, h1, h2;
89013    char zKey[40];
89014    for(i=0; (h1 = zRight[i])!=0 && (h2 = zRight[i+1])!=0; i+=2){
89015      h1 += 9*(1&(h1>>6));
89016      h2 += 9*(1&(h2>>6));
89017      zKey[i/2] = (h2 & 0x0f) | ((h1 & 0xf)<<4);
89018    }
89019    if( (zLeft[3] & 0xf)==0xb ){
89020      sqlite3_key(db, zKey, i/2);
89021    }else{
89022      sqlite3_rekey(db, zKey, i/2);
89023    }
89024  }else
89025#endif
89026#if defined(SQLITE_HAS_CODEC) || defined(SQLITE_ENABLE_CEROD)
89027  if( sqlite3StrICmp(zLeft, "activate_extensions")==0 ){
89028#ifdef SQLITE_HAS_CODEC
89029    if( sqlite3StrNICmp(zRight, "see-", 4)==0 ){
89030      sqlite3_activate_see(&zRight[4]);
89031    }
89032#endif
89033#ifdef SQLITE_ENABLE_CEROD
89034    if( sqlite3StrNICmp(zRight, "cerod-", 6)==0 ){
89035      sqlite3_activate_cerod(&zRight[6]);
89036    }
89037#endif
89038  }else
89039#endif
89040
89041
89042  {/* Empty ELSE clause */}
89043
89044  /*
89045  ** Reset the safety level, in case the fullfsync flag or synchronous
89046  ** setting changed.
89047  */
89048#ifndef SQLITE_OMIT_PAGER_PRAGMAS
89049  if( db->autoCommit ){
89050    sqlite3BtreeSetSafetyLevel(pDb->pBt, pDb->safety_level,
89051               (db->flags&SQLITE_FullFSync)!=0,
89052               (db->flags&SQLITE_CkptFullFSync)!=0);
89053  }
89054#endif
89055pragma_out:
89056  sqlite3DbFree(db, zLeft);
89057  sqlite3DbFree(db, zRight);
89058}
89059
89060#endif /* SQLITE_OMIT_PRAGMA */
89061
89062/************** End of pragma.c **********************************************/
89063/************** Begin file prepare.c *****************************************/
89064/*
89065** 2005 May 25
89066**
89067** The author disclaims copyright to this source code.  In place of
89068** a legal notice, here is a blessing:
89069**
89070**    May you do good and not evil.
89071**    May you find forgiveness for yourself and forgive others.
89072**    May you share freely, never taking more than you give.
89073**
89074*************************************************************************
89075** This file contains the implementation of the sqlite3_prepare()
89076** interface, and routines that contribute to loading the database schema
89077** from disk.
89078*/
89079
89080/*
89081** Fill the InitData structure with an error message that indicates
89082** that the database is corrupt.
89083*/
89084static void corruptSchema(
89085  InitData *pData,     /* Initialization context */
89086  const char *zObj,    /* Object being parsed at the point of error */
89087  const char *zExtra   /* Error information */
89088){
89089  sqlite3 *db = pData->db;
89090  if( !db->mallocFailed && (db->flags & SQLITE_RecoveryMode)==0 ){
89091    if( zObj==0 ) zObj = "?";
89092    sqlite3SetString(pData->pzErrMsg, db,
89093      "malformed database schema (%s)", zObj);
89094    if( zExtra ){
89095      *pData->pzErrMsg = sqlite3MAppendf(db, *pData->pzErrMsg,
89096                                 "%s - %s", *pData->pzErrMsg, zExtra);
89097    }
89098  }
89099  pData->rc = db->mallocFailed ? SQLITE_NOMEM : SQLITE_CORRUPT_BKPT;
89100}
89101
89102/*
89103** This is the callback routine for the code that initializes the
89104** database.  See sqlite3Init() below for additional information.
89105** This routine is also called from the OP_ParseSchema opcode of the VDBE.
89106**
89107** Each callback contains the following information:
89108**
89109**     argv[0] = name of thing being created
89110**     argv[1] = root page number for table or index. 0 for trigger or view.
89111**     argv[2] = SQL text for the CREATE statement.
89112**
89113*/
89114SQLITE_PRIVATE int sqlite3InitCallback(void *pInit, int argc, char **argv, char **NotUsed){
89115  InitData *pData = (InitData*)pInit;
89116  sqlite3 *db = pData->db;
89117  int iDb = pData->iDb;
89118
89119  assert( argc==3 );
89120  UNUSED_PARAMETER2(NotUsed, argc);
89121  assert( sqlite3_mutex_held(db->mutex) );
89122  DbClearProperty(db, iDb, DB_Empty);
89123  if( db->mallocFailed ){
89124    corruptSchema(pData, argv[0], 0);
89125    return 1;
89126  }
89127
89128  assert( iDb>=0 && iDb<db->nDb );
89129  if( argv==0 ) return 0;   /* Might happen if EMPTY_RESULT_CALLBACKS are on */
89130  if( argv[1]==0 ){
89131    corruptSchema(pData, argv[0], 0);
89132  }else if( argv[2] && argv[2][0] ){
89133    /* Call the parser to process a CREATE TABLE, INDEX or VIEW.
89134    ** But because db->init.busy is set to 1, no VDBE code is generated
89135    ** or executed.  All the parser does is build the internal data
89136    ** structures that describe the table, index, or view.
89137    */
89138    int rc;
89139    sqlite3_stmt *pStmt;
89140    TESTONLY(int rcp);            /* Return code from sqlite3_prepare() */
89141
89142    assert( db->init.busy );
89143    db->init.iDb = iDb;
89144    db->init.newTnum = sqlite3Atoi(argv[1]);
89145    db->init.orphanTrigger = 0;
89146    TESTONLY(rcp = ) sqlite3_prepare(db, argv[2], -1, &pStmt, 0);
89147    rc = db->errCode;
89148    assert( (rc&0xFF)==(rcp&0xFF) );
89149    db->init.iDb = 0;
89150    if( SQLITE_OK!=rc ){
89151      if( db->init.orphanTrigger ){
89152        assert( iDb==1 );
89153      }else{
89154        pData->rc = rc;
89155        if( rc==SQLITE_NOMEM ){
89156          db->mallocFailed = 1;
89157        }else if( rc!=SQLITE_INTERRUPT && (rc&0xFF)!=SQLITE_LOCKED ){
89158          corruptSchema(pData, argv[0], sqlite3_errmsg(db));
89159        }
89160      }
89161    }
89162    sqlite3_finalize(pStmt);
89163  }else if( argv[0]==0 ){
89164    corruptSchema(pData, 0, 0);
89165  }else{
89166    /* If the SQL column is blank it means this is an index that
89167    ** was created to be the PRIMARY KEY or to fulfill a UNIQUE
89168    ** constraint for a CREATE TABLE.  The index should have already
89169    ** been created when we processed the CREATE TABLE.  All we have
89170    ** to do here is record the root page number for that index.
89171    */
89172    Index *pIndex;
89173    pIndex = sqlite3FindIndex(db, argv[0], db->aDb[iDb].zName);
89174    if( pIndex==0 ){
89175      /* This can occur if there exists an index on a TEMP table which
89176      ** has the same name as another index on a permanent index.  Since
89177      ** the permanent table is hidden by the TEMP table, we can also
89178      ** safely ignore the index on the permanent table.
89179      */
89180      /* Do Nothing */;
89181    }else if( sqlite3GetInt32(argv[1], &pIndex->tnum)==0 ){
89182      corruptSchema(pData, argv[0], "invalid rootpage");
89183    }
89184  }
89185  return 0;
89186}
89187
89188/*
89189** Attempt to read the database schema and initialize internal
89190** data structures for a single database file.  The index of the
89191** database file is given by iDb.  iDb==0 is used for the main
89192** database.  iDb==1 should never be used.  iDb>=2 is used for
89193** auxiliary databases.  Return one of the SQLITE_ error codes to
89194** indicate success or failure.
89195*/
89196static int sqlite3InitOne(sqlite3 *db, int iDb, char **pzErrMsg){
89197  int rc;
89198  int i;
89199  int size;
89200  Table *pTab;
89201  Db *pDb;
89202  char const *azArg[4];
89203  int meta[5];
89204  InitData initData;
89205  char const *zMasterSchema;
89206  char const *zMasterName;
89207  int openedTransaction = 0;
89208
89209  /*
89210  ** The master database table has a structure like this
89211  */
89212  static const char master_schema[] =
89213     "CREATE TABLE sqlite_master(\n"
89214     "  type text,\n"
89215     "  name text,\n"
89216     "  tbl_name text,\n"
89217     "  rootpage integer,\n"
89218     "  sql text\n"
89219     ")"
89220  ;
89221#ifndef SQLITE_OMIT_TEMPDB
89222  static const char temp_master_schema[] =
89223     "CREATE TEMP TABLE sqlite_temp_master(\n"
89224     "  type text,\n"
89225     "  name text,\n"
89226     "  tbl_name text,\n"
89227     "  rootpage integer,\n"
89228     "  sql text\n"
89229     ")"
89230  ;
89231#else
89232  #define temp_master_schema 0
89233#endif
89234
89235  assert( iDb>=0 && iDb<db->nDb );
89236  assert( db->aDb[iDb].pSchema );
89237  assert( sqlite3_mutex_held(db->mutex) );
89238  assert( iDb==1 || sqlite3BtreeHoldsMutex(db->aDb[iDb].pBt) );
89239
89240  /* zMasterSchema and zInitScript are set to point at the master schema
89241  ** and initialisation script appropriate for the database being
89242  ** initialised. zMasterName is the name of the master table.
89243  */
89244  if( !OMIT_TEMPDB && iDb==1 ){
89245    zMasterSchema = temp_master_schema;
89246  }else{
89247    zMasterSchema = master_schema;
89248  }
89249  zMasterName = SCHEMA_TABLE(iDb);
89250
89251  /* Construct the schema tables.  */
89252  azArg[0] = zMasterName;
89253  azArg[1] = "1";
89254  azArg[2] = zMasterSchema;
89255  azArg[3] = 0;
89256  initData.db = db;
89257  initData.iDb = iDb;
89258  initData.rc = SQLITE_OK;
89259  initData.pzErrMsg = pzErrMsg;
89260  sqlite3InitCallback(&initData, 3, (char **)azArg, 0);
89261  if( initData.rc ){
89262    rc = initData.rc;
89263    goto error_out;
89264  }
89265  pTab = sqlite3FindTable(db, zMasterName, db->aDb[iDb].zName);
89266  if( ALWAYS(pTab) ){
89267    pTab->tabFlags |= TF_Readonly;
89268  }
89269
89270  /* Create a cursor to hold the database open
89271  */
89272  pDb = &db->aDb[iDb];
89273  if( pDb->pBt==0 ){
89274    if( !OMIT_TEMPDB && ALWAYS(iDb==1) ){
89275      DbSetProperty(db, 1, DB_SchemaLoaded);
89276    }
89277    return SQLITE_OK;
89278  }
89279
89280  /* If there is not already a read-only (or read-write) transaction opened
89281  ** on the b-tree database, open one now. If a transaction is opened, it
89282  ** will be closed before this function returns.  */
89283  sqlite3BtreeEnter(pDb->pBt);
89284  if( !sqlite3BtreeIsInReadTrans(pDb->pBt) ){
89285    rc = sqlite3BtreeBeginTrans(pDb->pBt, 0);
89286    if( rc!=SQLITE_OK ){
89287      sqlite3SetString(pzErrMsg, db, "%s", sqlite3ErrStr(rc));
89288      goto initone_error_out;
89289    }
89290    openedTransaction = 1;
89291  }
89292
89293  /* Get the database meta information.
89294  **
89295  ** Meta values are as follows:
89296  **    meta[0]   Schema cookie.  Changes with each schema change.
89297  **    meta[1]   File format of schema layer.
89298  **    meta[2]   Size of the page cache.
89299  **    meta[3]   Largest rootpage (auto/incr_vacuum mode)
89300  **    meta[4]   Db text encoding. 1:UTF-8 2:UTF-16LE 3:UTF-16BE
89301  **    meta[5]   User version
89302  **    meta[6]   Incremental vacuum mode
89303  **    meta[7]   unused
89304  **    meta[8]   unused
89305  **    meta[9]   unused
89306  **
89307  ** Note: The #defined SQLITE_UTF* symbols in sqliteInt.h correspond to
89308  ** the possible values of meta[4].
89309  */
89310  for(i=0; i<ArraySize(meta); i++){
89311    sqlite3BtreeGetMeta(pDb->pBt, i+1, (u32 *)&meta[i]);
89312  }
89313  pDb->pSchema->schema_cookie = meta[BTREE_SCHEMA_VERSION-1];
89314
89315  /* If opening a non-empty database, check the text encoding. For the
89316  ** main database, set sqlite3.enc to the encoding of the main database.
89317  ** For an attached db, it is an error if the encoding is not the same
89318  ** as sqlite3.enc.
89319  */
89320  if( meta[BTREE_TEXT_ENCODING-1] ){  /* text encoding */
89321    if( iDb==0 ){
89322      u8 encoding;
89323      /* If opening the main database, set ENC(db). */
89324      encoding = (u8)meta[BTREE_TEXT_ENCODING-1] & 3;
89325      if( encoding==0 ) encoding = SQLITE_UTF8;
89326      ENC(db) = encoding;
89327      db->pDfltColl = sqlite3FindCollSeq(db, SQLITE_UTF8, "BINARY", 0);
89328    }else{
89329      /* If opening an attached database, the encoding much match ENC(db) */
89330      if( meta[BTREE_TEXT_ENCODING-1]!=ENC(db) ){
89331        sqlite3SetString(pzErrMsg, db, "attached databases must use the same"
89332            " text encoding as main database");
89333        rc = SQLITE_ERROR;
89334        goto initone_error_out;
89335      }
89336    }
89337  }else{
89338    DbSetProperty(db, iDb, DB_Empty);
89339  }
89340  pDb->pSchema->enc = ENC(db);
89341
89342  if( pDb->pSchema->cache_size==0 ){
89343    size = sqlite3AbsInt32(meta[BTREE_DEFAULT_CACHE_SIZE-1]);
89344    if( size==0 ){ size = SQLITE_DEFAULT_CACHE_SIZE; }
89345    pDb->pSchema->cache_size = size;
89346    sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
89347  }
89348
89349  /*
89350  ** file_format==1    Version 3.0.0.
89351  ** file_format==2    Version 3.1.3.  // ALTER TABLE ADD COLUMN
89352  ** file_format==3    Version 3.1.4.  // ditto but with non-NULL defaults
89353  ** file_format==4    Version 3.3.0.  // DESC indices.  Boolean constants
89354  */
89355  pDb->pSchema->file_format = (u8)meta[BTREE_FILE_FORMAT-1];
89356  if( pDb->pSchema->file_format==0 ){
89357    pDb->pSchema->file_format = 1;
89358  }
89359  if( pDb->pSchema->file_format>SQLITE_MAX_FILE_FORMAT ){
89360    sqlite3SetString(pzErrMsg, db, "unsupported file format");
89361    rc = SQLITE_ERROR;
89362    goto initone_error_out;
89363  }
89364
89365  /* Ticket #2804:  When we open a database in the newer file format,
89366  ** clear the legacy_file_format pragma flag so that a VACUUM will
89367  ** not downgrade the database and thus invalidate any descending
89368  ** indices that the user might have created.
89369  */
89370  if( iDb==0 && meta[BTREE_FILE_FORMAT-1]>=4 ){
89371    db->flags &= ~SQLITE_LegacyFileFmt;
89372  }
89373
89374  /* Read the schema information out of the schema tables
89375  */
89376  assert( db->init.busy );
89377  {
89378    char *zSql;
89379    zSql = sqlite3MPrintf(db,
89380        "SELECT name, rootpage, sql FROM '%q'.%s ORDER BY rowid",
89381        db->aDb[iDb].zName, zMasterName);
89382#ifndef SQLITE_OMIT_AUTHORIZATION
89383    {
89384      int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
89385      xAuth = db->xAuth;
89386      db->xAuth = 0;
89387#endif
89388      rc = sqlite3_exec(db, zSql, sqlite3InitCallback, &initData, 0);
89389#ifndef SQLITE_OMIT_AUTHORIZATION
89390      db->xAuth = xAuth;
89391    }
89392#endif
89393    if( rc==SQLITE_OK ) rc = initData.rc;
89394    sqlite3DbFree(db, zSql);
89395#ifndef SQLITE_OMIT_ANALYZE
89396    if( rc==SQLITE_OK ){
89397      sqlite3AnalysisLoad(db, iDb);
89398    }
89399#endif
89400  }
89401  if( db->mallocFailed ){
89402    rc = SQLITE_NOMEM;
89403    sqlite3ResetInternalSchema(db, -1);
89404  }
89405  if( rc==SQLITE_OK || (db->flags&SQLITE_RecoveryMode)){
89406    /* Black magic: If the SQLITE_RecoveryMode flag is set, then consider
89407    ** the schema loaded, even if errors occurred. In this situation the
89408    ** current sqlite3_prepare() operation will fail, but the following one
89409    ** will attempt to compile the supplied statement against whatever subset
89410    ** of the schema was loaded before the error occurred. The primary
89411    ** purpose of this is to allow access to the sqlite_master table
89412    ** even when its contents have been corrupted.
89413    */
89414    DbSetProperty(db, iDb, DB_SchemaLoaded);
89415    rc = SQLITE_OK;
89416  }
89417
89418  /* Jump here for an error that occurs after successfully allocating
89419  ** curMain and calling sqlite3BtreeEnter(). For an error that occurs
89420  ** before that point, jump to error_out.
89421  */
89422initone_error_out:
89423  if( openedTransaction ){
89424    sqlite3BtreeCommit(pDb->pBt);
89425  }
89426  sqlite3BtreeLeave(pDb->pBt);
89427
89428error_out:
89429  if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
89430    db->mallocFailed = 1;
89431  }
89432  return rc;
89433}
89434
89435/*
89436** Initialize all database files - the main database file, the file
89437** used to store temporary tables, and any additional database files
89438** created using ATTACH statements.  Return a success code.  If an
89439** error occurs, write an error message into *pzErrMsg.
89440**
89441** After a database is initialized, the DB_SchemaLoaded bit is set
89442** bit is set in the flags field of the Db structure. If the database
89443** file was of zero-length, then the DB_Empty flag is also set.
89444*/
89445SQLITE_PRIVATE int sqlite3Init(sqlite3 *db, char **pzErrMsg){
89446  int i, rc;
89447  int commit_internal = !(db->flags&SQLITE_InternChanges);
89448
89449  assert( sqlite3_mutex_held(db->mutex) );
89450  rc = SQLITE_OK;
89451  db->init.busy = 1;
89452  for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
89453    if( DbHasProperty(db, i, DB_SchemaLoaded) || i==1 ) continue;
89454    rc = sqlite3InitOne(db, i, pzErrMsg);
89455    if( rc ){
89456      sqlite3ResetInternalSchema(db, i);
89457    }
89458  }
89459
89460  /* Once all the other databases have been initialised, load the schema
89461  ** for the TEMP database. This is loaded last, as the TEMP database
89462  ** schema may contain references to objects in other databases.
89463  */
89464#ifndef SQLITE_OMIT_TEMPDB
89465  if( rc==SQLITE_OK && ALWAYS(db->nDb>1)
89466                    && !DbHasProperty(db, 1, DB_SchemaLoaded) ){
89467    rc = sqlite3InitOne(db, 1, pzErrMsg);
89468    if( rc ){
89469      sqlite3ResetInternalSchema(db, 1);
89470    }
89471  }
89472#endif
89473
89474  db->init.busy = 0;
89475  if( rc==SQLITE_OK && commit_internal ){
89476    sqlite3CommitInternalChanges(db);
89477  }
89478
89479  return rc;
89480}
89481
89482/*
89483** This routine is a no-op if the database schema is already initialised.
89484** Otherwise, the schema is loaded. An error code is returned.
89485*/
89486SQLITE_PRIVATE int sqlite3ReadSchema(Parse *pParse){
89487  int rc = SQLITE_OK;
89488  sqlite3 *db = pParse->db;
89489  assert( sqlite3_mutex_held(db->mutex) );
89490  if( !db->init.busy ){
89491    rc = sqlite3Init(db, &pParse->zErrMsg);
89492  }
89493  if( rc!=SQLITE_OK ){
89494    pParse->rc = rc;
89495    pParse->nErr++;
89496  }
89497  return rc;
89498}
89499
89500
89501/*
89502** Check schema cookies in all databases.  If any cookie is out
89503** of date set pParse->rc to SQLITE_SCHEMA.  If all schema cookies
89504** make no changes to pParse->rc.
89505*/
89506static void schemaIsValid(Parse *pParse){
89507  sqlite3 *db = pParse->db;
89508  int iDb;
89509  int rc;
89510  int cookie;
89511
89512  assert( pParse->checkSchema );
89513  assert( sqlite3_mutex_held(db->mutex) );
89514  for(iDb=0; iDb<db->nDb; iDb++){
89515    int openedTransaction = 0;         /* True if a transaction is opened */
89516    Btree *pBt = db->aDb[iDb].pBt;     /* Btree database to read cookie from */
89517    if( pBt==0 ) continue;
89518
89519    /* If there is not already a read-only (or read-write) transaction opened
89520    ** on the b-tree database, open one now. If a transaction is opened, it
89521    ** will be closed immediately after reading the meta-value. */
89522    if( !sqlite3BtreeIsInReadTrans(pBt) ){
89523      rc = sqlite3BtreeBeginTrans(pBt, 0);
89524      if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
89525        db->mallocFailed = 1;
89526      }
89527      if( rc!=SQLITE_OK ) return;
89528      openedTransaction = 1;
89529    }
89530
89531    /* Read the schema cookie from the database. If it does not match the
89532    ** value stored as part of the in-memory schema representation,
89533    ** set Parse.rc to SQLITE_SCHEMA. */
89534    sqlite3BtreeGetMeta(pBt, BTREE_SCHEMA_VERSION, (u32 *)&cookie);
89535    assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
89536    if( cookie!=db->aDb[iDb].pSchema->schema_cookie ){
89537      sqlite3ResetInternalSchema(db, iDb);
89538      pParse->rc = SQLITE_SCHEMA;
89539    }
89540
89541    /* Close the transaction, if one was opened. */
89542    if( openedTransaction ){
89543      sqlite3BtreeCommit(pBt);
89544    }
89545  }
89546}
89547
89548/*
89549** Convert a schema pointer into the iDb index that indicates
89550** which database file in db->aDb[] the schema refers to.
89551**
89552** If the same database is attached more than once, the first
89553** attached database is returned.
89554*/
89555SQLITE_PRIVATE int sqlite3SchemaToIndex(sqlite3 *db, Schema *pSchema){
89556  int i = -1000000;
89557
89558  /* If pSchema is NULL, then return -1000000. This happens when code in
89559  ** expr.c is trying to resolve a reference to a transient table (i.e. one
89560  ** created by a sub-select). In this case the return value of this
89561  ** function should never be used.
89562  **
89563  ** We return -1000000 instead of the more usual -1 simply because using
89564  ** -1000000 as the incorrect index into db->aDb[] is much
89565  ** more likely to cause a segfault than -1 (of course there are assert()
89566  ** statements too, but it never hurts to play the odds).
89567  */
89568  assert( sqlite3_mutex_held(db->mutex) );
89569  if( pSchema ){
89570    for(i=0; ALWAYS(i<db->nDb); i++){
89571      if( db->aDb[i].pSchema==pSchema ){
89572        break;
89573      }
89574    }
89575    assert( i>=0 && i<db->nDb );
89576  }
89577  return i;
89578}
89579
89580/*
89581** Compile the UTF-8 encoded SQL statement zSql into a statement handle.
89582*/
89583static int sqlite3Prepare(
89584  sqlite3 *db,              /* Database handle. */
89585  const char *zSql,         /* UTF-8 encoded SQL statement. */
89586  int nBytes,               /* Length of zSql in bytes. */
89587  int saveSqlFlag,          /* True to copy SQL text into the sqlite3_stmt */
89588  Vdbe *pReprepare,         /* VM being reprepared */
89589  sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
89590  const char **pzTail       /* OUT: End of parsed string */
89591){
89592  Parse *pParse;            /* Parsing context */
89593  char *zErrMsg = 0;        /* Error message */
89594  int rc = SQLITE_OK;       /* Result code */
89595  int i;                    /* Loop counter */
89596
89597  /* Allocate the parsing context */
89598  pParse = sqlite3StackAllocZero(db, sizeof(*pParse));
89599  if( pParse==0 ){
89600    rc = SQLITE_NOMEM;
89601    goto end_prepare;
89602  }
89603  pParse->pReprepare = pReprepare;
89604  assert( ppStmt && *ppStmt==0 );
89605  assert( !db->mallocFailed );
89606  assert( sqlite3_mutex_held(db->mutex) );
89607
89608  /* Check to verify that it is possible to get a read lock on all
89609  ** database schemas.  The inability to get a read lock indicates that
89610  ** some other database connection is holding a write-lock, which in
89611  ** turn means that the other connection has made uncommitted changes
89612  ** to the schema.
89613  **
89614  ** Were we to proceed and prepare the statement against the uncommitted
89615  ** schema changes and if those schema changes are subsequently rolled
89616  ** back and different changes are made in their place, then when this
89617  ** prepared statement goes to run the schema cookie would fail to detect
89618  ** the schema change.  Disaster would follow.
89619  **
89620  ** This thread is currently holding mutexes on all Btrees (because
89621  ** of the sqlite3BtreeEnterAll() in sqlite3LockAndPrepare()) so it
89622  ** is not possible for another thread to start a new schema change
89623  ** while this routine is running.  Hence, we do not need to hold
89624  ** locks on the schema, we just need to make sure nobody else is
89625  ** holding them.
89626  **
89627  ** Note that setting READ_UNCOMMITTED overrides most lock detection,
89628  ** but it does *not* override schema lock detection, so this all still
89629  ** works even if READ_UNCOMMITTED is set.
89630  */
89631  for(i=0; i<db->nDb; i++) {
89632    Btree *pBt = db->aDb[i].pBt;
89633    if( pBt ){
89634      assert( sqlite3BtreeHoldsMutex(pBt) );
89635      rc = sqlite3BtreeSchemaLocked(pBt);
89636      if( rc ){
89637        const char *zDb = db->aDb[i].zName;
89638        sqlite3Error(db, rc, "database schema is locked: %s", zDb);
89639        testcase( db->flags & SQLITE_ReadUncommitted );
89640        goto end_prepare;
89641      }
89642    }
89643  }
89644
89645  sqlite3VtabUnlockList(db);
89646
89647  pParse->db = db;
89648  pParse->nQueryLoop = (double)1;
89649  if( nBytes>=0 && (nBytes==0 || zSql[nBytes-1]!=0) ){
89650    char *zSqlCopy;
89651    int mxLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH];
89652    testcase( nBytes==mxLen );
89653    testcase( nBytes==mxLen+1 );
89654    if( nBytes>mxLen ){
89655      sqlite3Error(db, SQLITE_TOOBIG, "statement too long");
89656      rc = sqlite3ApiExit(db, SQLITE_TOOBIG);
89657      goto end_prepare;
89658    }
89659    zSqlCopy = sqlite3DbStrNDup(db, zSql, nBytes);
89660    if( zSqlCopy ){
89661      sqlite3RunParser(pParse, zSqlCopy, &zErrMsg);
89662      sqlite3DbFree(db, zSqlCopy);
89663      pParse->zTail = &zSql[pParse->zTail-zSqlCopy];
89664    }else{
89665      pParse->zTail = &zSql[nBytes];
89666    }
89667  }else{
89668    sqlite3RunParser(pParse, zSql, &zErrMsg);
89669  }
89670  assert( 1==(int)pParse->nQueryLoop );
89671
89672  if( db->mallocFailed ){
89673    pParse->rc = SQLITE_NOMEM;
89674  }
89675  if( pParse->rc==SQLITE_DONE ) pParse->rc = SQLITE_OK;
89676  if( pParse->checkSchema ){
89677    schemaIsValid(pParse);
89678  }
89679  if( db->mallocFailed ){
89680    pParse->rc = SQLITE_NOMEM;
89681  }
89682  if( pzTail ){
89683    *pzTail = pParse->zTail;
89684  }
89685  rc = pParse->rc;
89686
89687#ifndef SQLITE_OMIT_EXPLAIN
89688  if( rc==SQLITE_OK && pParse->pVdbe && pParse->explain ){
89689    static const char * const azColName[] = {
89690       "addr", "opcode", "p1", "p2", "p3", "p4", "p5", "comment",
89691       "selectid", "order", "from", "detail"
89692    };
89693    int iFirst, mx;
89694    if( pParse->explain==2 ){
89695      sqlite3VdbeSetNumCols(pParse->pVdbe, 4);
89696      iFirst = 8;
89697      mx = 12;
89698    }else{
89699      sqlite3VdbeSetNumCols(pParse->pVdbe, 8);
89700      iFirst = 0;
89701      mx = 8;
89702    }
89703    for(i=iFirst; i<mx; i++){
89704      sqlite3VdbeSetColName(pParse->pVdbe, i-iFirst, COLNAME_NAME,
89705                            azColName[i], SQLITE_STATIC);
89706    }
89707  }
89708#endif
89709
89710  assert( db->init.busy==0 || saveSqlFlag==0 );
89711  if( db->init.busy==0 ){
89712    Vdbe *pVdbe = pParse->pVdbe;
89713    sqlite3VdbeSetSql(pVdbe, zSql, (int)(pParse->zTail-zSql), saveSqlFlag);
89714  }
89715  if( pParse->pVdbe && (rc!=SQLITE_OK || db->mallocFailed) ){
89716    sqlite3VdbeFinalize(pParse->pVdbe);
89717    assert(!(*ppStmt));
89718  }else{
89719    *ppStmt = (sqlite3_stmt*)pParse->pVdbe;
89720  }
89721
89722  if( zErrMsg ){
89723    sqlite3Error(db, rc, "%s", zErrMsg);
89724    sqlite3DbFree(db, zErrMsg);
89725  }else{
89726    sqlite3Error(db, rc, 0);
89727  }
89728
89729  /* Delete any TriggerPrg structures allocated while parsing this statement. */
89730  while( pParse->pTriggerPrg ){
89731    TriggerPrg *pT = pParse->pTriggerPrg;
89732    pParse->pTriggerPrg = pT->pNext;
89733    sqlite3DbFree(db, pT);
89734  }
89735
89736end_prepare:
89737
89738  sqlite3StackFree(db, pParse);
89739  rc = sqlite3ApiExit(db, rc);
89740  assert( (rc&db->errMask)==rc );
89741  return rc;
89742}
89743static int sqlite3LockAndPrepare(
89744  sqlite3 *db,              /* Database handle. */
89745  const char *zSql,         /* UTF-8 encoded SQL statement. */
89746  int nBytes,               /* Length of zSql in bytes. */
89747  int saveSqlFlag,          /* True to copy SQL text into the sqlite3_stmt */
89748  Vdbe *pOld,               /* VM being reprepared */
89749  sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
89750  const char **pzTail       /* OUT: End of parsed string */
89751){
89752  int rc;
89753  assert( ppStmt!=0 );
89754  *ppStmt = 0;
89755  if( !sqlite3SafetyCheckOk(db) ){
89756    return SQLITE_MISUSE_BKPT;
89757  }
89758  sqlite3_mutex_enter(db->mutex);
89759  sqlite3BtreeEnterAll(db);
89760  rc = sqlite3Prepare(db, zSql, nBytes, saveSqlFlag, pOld, ppStmt, pzTail);
89761  if( rc==SQLITE_SCHEMA ){
89762    sqlite3_finalize(*ppStmt);
89763    rc = sqlite3Prepare(db, zSql, nBytes, saveSqlFlag, pOld, ppStmt, pzTail);
89764  }
89765  sqlite3BtreeLeaveAll(db);
89766  sqlite3_mutex_leave(db->mutex);
89767  return rc;
89768}
89769
89770/*
89771** Rerun the compilation of a statement after a schema change.
89772**
89773** If the statement is successfully recompiled, return SQLITE_OK. Otherwise,
89774** if the statement cannot be recompiled because another connection has
89775** locked the sqlite3_master table, return SQLITE_LOCKED. If any other error
89776** occurs, return SQLITE_SCHEMA.
89777*/
89778SQLITE_PRIVATE int sqlite3Reprepare(Vdbe *p){
89779  int rc;
89780  sqlite3_stmt *pNew;
89781  const char *zSql;
89782  sqlite3 *db;
89783
89784  assert( sqlite3_mutex_held(sqlite3VdbeDb(p)->mutex) );
89785  zSql = sqlite3_sql((sqlite3_stmt *)p);
89786  assert( zSql!=0 );  /* Reprepare only called for prepare_v2() statements */
89787  db = sqlite3VdbeDb(p);
89788  assert( sqlite3_mutex_held(db->mutex) );
89789  rc = sqlite3LockAndPrepare(db, zSql, -1, 0, p, &pNew, 0);
89790  if( rc ){
89791    if( rc==SQLITE_NOMEM ){
89792      db->mallocFailed = 1;
89793    }
89794    assert( pNew==0 );
89795    return rc;
89796  }else{
89797    assert( pNew!=0 );
89798  }
89799  sqlite3VdbeSwap((Vdbe*)pNew, p);
89800  sqlite3TransferBindings(pNew, (sqlite3_stmt*)p);
89801  sqlite3VdbeResetStepResult((Vdbe*)pNew);
89802  sqlite3VdbeFinalize((Vdbe*)pNew);
89803  return SQLITE_OK;
89804}
89805
89806
89807/*
89808** Two versions of the official API.  Legacy and new use.  In the legacy
89809** version, the original SQL text is not saved in the prepared statement
89810** and so if a schema change occurs, SQLITE_SCHEMA is returned by
89811** sqlite3_step().  In the new version, the original SQL text is retained
89812** and the statement is automatically recompiled if an schema change
89813** occurs.
89814*/
89815SQLITE_API int sqlite3_prepare(
89816  sqlite3 *db,              /* Database handle. */
89817  const char *zSql,         /* UTF-8 encoded SQL statement. */
89818  int nBytes,               /* Length of zSql in bytes. */
89819  sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
89820  const char **pzTail       /* OUT: End of parsed string */
89821){
89822  int rc;
89823  rc = sqlite3LockAndPrepare(db,zSql,nBytes,0,0,ppStmt,pzTail);
89824  assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
89825  return rc;
89826}
89827SQLITE_API int sqlite3_prepare_v2(
89828  sqlite3 *db,              /* Database handle. */
89829  const char *zSql,         /* UTF-8 encoded SQL statement. */
89830  int nBytes,               /* Length of zSql in bytes. */
89831  sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
89832  const char **pzTail       /* OUT: End of parsed string */
89833){
89834  int rc;
89835  rc = sqlite3LockAndPrepare(db,zSql,nBytes,1,0,ppStmt,pzTail);
89836  assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
89837  return rc;
89838}
89839
89840
89841#ifndef SQLITE_OMIT_UTF16
89842/*
89843** Compile the UTF-16 encoded SQL statement zSql into a statement handle.
89844*/
89845static int sqlite3Prepare16(
89846  sqlite3 *db,              /* Database handle. */
89847  const void *zSql,         /* UTF-16 encoded SQL statement. */
89848  int nBytes,               /* Length of zSql in bytes. */
89849  int saveSqlFlag,          /* True to save SQL text into the sqlite3_stmt */
89850  sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
89851  const void **pzTail       /* OUT: End of parsed string */
89852){
89853  /* This function currently works by first transforming the UTF-16
89854  ** encoded string to UTF-8, then invoking sqlite3_prepare(). The
89855  ** tricky bit is figuring out the pointer to return in *pzTail.
89856  */
89857  char *zSql8;
89858  const char *zTail8 = 0;
89859  int rc = SQLITE_OK;
89860
89861  assert( ppStmt );
89862  *ppStmt = 0;
89863  if( !sqlite3SafetyCheckOk(db) ){
89864    return SQLITE_MISUSE_BKPT;
89865  }
89866  sqlite3_mutex_enter(db->mutex);
89867  zSql8 = sqlite3Utf16to8(db, zSql, nBytes, SQLITE_UTF16NATIVE);
89868  if( zSql8 ){
89869    rc = sqlite3LockAndPrepare(db, zSql8, -1, saveSqlFlag, 0, ppStmt, &zTail8);
89870  }
89871
89872  if( zTail8 && pzTail ){
89873    /* If sqlite3_prepare returns a tail pointer, we calculate the
89874    ** equivalent pointer into the UTF-16 string by counting the unicode
89875    ** characters between zSql8 and zTail8, and then returning a pointer
89876    ** the same number of characters into the UTF-16 string.
89877    */
89878    int chars_parsed = sqlite3Utf8CharLen(zSql8, (int)(zTail8-zSql8));
89879    *pzTail = (u8 *)zSql + sqlite3Utf16ByteLen(zSql, chars_parsed);
89880  }
89881  sqlite3DbFree(db, zSql8);
89882  rc = sqlite3ApiExit(db, rc);
89883  sqlite3_mutex_leave(db->mutex);
89884  return rc;
89885}
89886
89887/*
89888** Two versions of the official API.  Legacy and new use.  In the legacy
89889** version, the original SQL text is not saved in the prepared statement
89890** and so if a schema change occurs, SQLITE_SCHEMA is returned by
89891** sqlite3_step().  In the new version, the original SQL text is retained
89892** and the statement is automatically recompiled if an schema change
89893** occurs.
89894*/
89895SQLITE_API int sqlite3_prepare16(
89896  sqlite3 *db,              /* Database handle. */
89897  const void *zSql,         /* UTF-16 encoded SQL statement. */
89898  int nBytes,               /* Length of zSql in bytes. */
89899  sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
89900  const void **pzTail       /* OUT: End of parsed string */
89901){
89902  int rc;
89903  rc = sqlite3Prepare16(db,zSql,nBytes,0,ppStmt,pzTail);
89904  assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
89905  return rc;
89906}
89907SQLITE_API int sqlite3_prepare16_v2(
89908  sqlite3 *db,              /* Database handle. */
89909  const void *zSql,         /* UTF-16 encoded SQL statement. */
89910  int nBytes,               /* Length of zSql in bytes. */
89911  sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
89912  const void **pzTail       /* OUT: End of parsed string */
89913){
89914  int rc;
89915  rc = sqlite3Prepare16(db,zSql,nBytes,1,ppStmt,pzTail);
89916  assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
89917  return rc;
89918}
89919
89920#endif /* SQLITE_OMIT_UTF16 */
89921
89922/************** End of prepare.c *********************************************/
89923/************** Begin file select.c ******************************************/
89924/*
89925** 2001 September 15
89926**
89927** The author disclaims copyright to this source code.  In place of
89928** a legal notice, here is a blessing:
89929**
89930**    May you do good and not evil.
89931**    May you find forgiveness for yourself and forgive others.
89932**    May you share freely, never taking more than you give.
89933**
89934*************************************************************************
89935** This file contains C code routines that are called by the parser
89936** to handle SELECT statements in SQLite.
89937*/
89938
89939
89940/*
89941** Delete all the content of a Select structure but do not deallocate
89942** the select structure itself.
89943*/
89944static void clearSelect(sqlite3 *db, Select *p){
89945  sqlite3ExprListDelete(db, p->pEList);
89946  sqlite3SrcListDelete(db, p->pSrc);
89947  sqlite3ExprDelete(db, p->pWhere);
89948  sqlite3ExprListDelete(db, p->pGroupBy);
89949  sqlite3ExprDelete(db, p->pHaving);
89950  sqlite3ExprListDelete(db, p->pOrderBy);
89951  sqlite3SelectDelete(db, p->pPrior);
89952  sqlite3ExprDelete(db, p->pLimit);
89953  sqlite3ExprDelete(db, p->pOffset);
89954}
89955
89956/*
89957** Initialize a SelectDest structure.
89958*/
89959SQLITE_PRIVATE void sqlite3SelectDestInit(SelectDest *pDest, int eDest, int iParm){
89960  pDest->eDest = (u8)eDest;
89961  pDest->iParm = iParm;
89962  pDest->affinity = 0;
89963  pDest->iMem = 0;
89964  pDest->nMem = 0;
89965}
89966
89967
89968/*
89969** Allocate a new Select structure and return a pointer to that
89970** structure.
89971*/
89972SQLITE_PRIVATE Select *sqlite3SelectNew(
89973  Parse *pParse,        /* Parsing context */
89974  ExprList *pEList,     /* which columns to include in the result */
89975  SrcList *pSrc,        /* the FROM clause -- which tables to scan */
89976  Expr *pWhere,         /* the WHERE clause */
89977  ExprList *pGroupBy,   /* the GROUP BY clause */
89978  Expr *pHaving,        /* the HAVING clause */
89979  ExprList *pOrderBy,   /* the ORDER BY clause */
89980  int isDistinct,       /* true if the DISTINCT keyword is present */
89981  Expr *pLimit,         /* LIMIT value.  NULL means not used */
89982  Expr *pOffset         /* OFFSET value.  NULL means no offset */
89983){
89984  Select *pNew;
89985  Select standin;
89986  sqlite3 *db = pParse->db;
89987  pNew = sqlite3DbMallocZero(db, sizeof(*pNew) );
89988  assert( db->mallocFailed || !pOffset || pLimit ); /* OFFSET implies LIMIT */
89989  if( pNew==0 ){
89990    pNew = &standin;
89991    memset(pNew, 0, sizeof(*pNew));
89992  }
89993  if( pEList==0 ){
89994    pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db,TK_ALL,0));
89995  }
89996  pNew->pEList = pEList;
89997  pNew->pSrc = pSrc;
89998  pNew->pWhere = pWhere;
89999  pNew->pGroupBy = pGroupBy;
90000  pNew->pHaving = pHaving;
90001  pNew->pOrderBy = pOrderBy;
90002  pNew->selFlags = isDistinct ? SF_Distinct : 0;
90003  pNew->op = TK_SELECT;
90004  pNew->pLimit = pLimit;
90005  pNew->pOffset = pOffset;
90006  assert( pOffset==0 || pLimit!=0 );
90007  pNew->addrOpenEphm[0] = -1;
90008  pNew->addrOpenEphm[1] = -1;
90009  pNew->addrOpenEphm[2] = -1;
90010  if( db->mallocFailed ) {
90011    clearSelect(db, pNew);
90012    if( pNew!=&standin ) sqlite3DbFree(db, pNew);
90013    pNew = 0;
90014  }
90015  return pNew;
90016}
90017
90018/*
90019** Delete the given Select structure and all of its substructures.
90020*/
90021SQLITE_PRIVATE void sqlite3SelectDelete(sqlite3 *db, Select *p){
90022  if( p ){
90023    clearSelect(db, p);
90024    sqlite3DbFree(db, p);
90025  }
90026}
90027
90028/*
90029** Given 1 to 3 identifiers preceeding the JOIN keyword, determine the
90030** type of join.  Return an integer constant that expresses that type
90031** in terms of the following bit values:
90032**
90033**     JT_INNER
90034**     JT_CROSS
90035**     JT_OUTER
90036**     JT_NATURAL
90037**     JT_LEFT
90038**     JT_RIGHT
90039**
90040** A full outer join is the combination of JT_LEFT and JT_RIGHT.
90041**
90042** If an illegal or unsupported join type is seen, then still return
90043** a join type, but put an error in the pParse structure.
90044*/
90045SQLITE_PRIVATE int sqlite3JoinType(Parse *pParse, Token *pA, Token *pB, Token *pC){
90046  int jointype = 0;
90047  Token *apAll[3];
90048  Token *p;
90049                             /*   0123456789 123456789 123456789 123 */
90050  static const char zKeyText[] = "naturaleftouterightfullinnercross";
90051  static const struct {
90052    u8 i;        /* Beginning of keyword text in zKeyText[] */
90053    u8 nChar;    /* Length of the keyword in characters */
90054    u8 code;     /* Join type mask */
90055  } aKeyword[] = {
90056    /* natural */ { 0,  7, JT_NATURAL                },
90057    /* left    */ { 6,  4, JT_LEFT|JT_OUTER          },
90058    /* outer   */ { 10, 5, JT_OUTER                  },
90059    /* right   */ { 14, 5, JT_RIGHT|JT_OUTER         },
90060    /* full    */ { 19, 4, JT_LEFT|JT_RIGHT|JT_OUTER },
90061    /* inner   */ { 23, 5, JT_INNER                  },
90062    /* cross   */ { 28, 5, JT_INNER|JT_CROSS         },
90063  };
90064  int i, j;
90065  apAll[0] = pA;
90066  apAll[1] = pB;
90067  apAll[2] = pC;
90068  for(i=0; i<3 && apAll[i]; i++){
90069    p = apAll[i];
90070    for(j=0; j<ArraySize(aKeyword); j++){
90071      if( p->n==aKeyword[j].nChar
90072          && sqlite3StrNICmp((char*)p->z, &zKeyText[aKeyword[j].i], p->n)==0 ){
90073        jointype |= aKeyword[j].code;
90074        break;
90075      }
90076    }
90077    testcase( j==0 || j==1 || j==2 || j==3 || j==4 || j==5 || j==6 );
90078    if( j>=ArraySize(aKeyword) ){
90079      jointype |= JT_ERROR;
90080      break;
90081    }
90082  }
90083  if(
90084     (jointype & (JT_INNER|JT_OUTER))==(JT_INNER|JT_OUTER) ||
90085     (jointype & JT_ERROR)!=0
90086  ){
90087    const char *zSp = " ";
90088    assert( pB!=0 );
90089    if( pC==0 ){ zSp++; }
90090    sqlite3ErrorMsg(pParse, "unknown or unsupported join type: "
90091       "%T %T%s%T", pA, pB, zSp, pC);
90092    jointype = JT_INNER;
90093  }else if( (jointype & JT_OUTER)!=0
90094         && (jointype & (JT_LEFT|JT_RIGHT))!=JT_LEFT ){
90095    sqlite3ErrorMsg(pParse,
90096      "RIGHT and FULL OUTER JOINs are not currently supported");
90097    jointype = JT_INNER;
90098  }
90099  return jointype;
90100}
90101
90102/*
90103** Return the index of a column in a table.  Return -1 if the column
90104** is not contained in the table.
90105*/
90106static int columnIndex(Table *pTab, const char *zCol){
90107  int i;
90108  for(i=0; i<pTab->nCol; i++){
90109    if( sqlite3StrICmp(pTab->aCol[i].zName, zCol)==0 ) return i;
90110  }
90111  return -1;
90112}
90113
90114/*
90115** Search the first N tables in pSrc, from left to right, looking for a
90116** table that has a column named zCol.
90117**
90118** When found, set *piTab and *piCol to the table index and column index
90119** of the matching column and return TRUE.
90120**
90121** If not found, return FALSE.
90122*/
90123static int tableAndColumnIndex(
90124  SrcList *pSrc,       /* Array of tables to search */
90125  int N,               /* Number of tables in pSrc->a[] to search */
90126  const char *zCol,    /* Name of the column we are looking for */
90127  int *piTab,          /* Write index of pSrc->a[] here */
90128  int *piCol           /* Write index of pSrc->a[*piTab].pTab->aCol[] here */
90129){
90130  int i;               /* For looping over tables in pSrc */
90131  int iCol;            /* Index of column matching zCol */
90132
90133  assert( (piTab==0)==(piCol==0) );  /* Both or neither are NULL */
90134  for(i=0; i<N; i++){
90135    iCol = columnIndex(pSrc->a[i].pTab, zCol);
90136    if( iCol>=0 ){
90137      if( piTab ){
90138        *piTab = i;
90139        *piCol = iCol;
90140      }
90141      return 1;
90142    }
90143  }
90144  return 0;
90145}
90146
90147/*
90148** This function is used to add terms implied by JOIN syntax to the
90149** WHERE clause expression of a SELECT statement. The new term, which
90150** is ANDed with the existing WHERE clause, is of the form:
90151**
90152**    (tab1.col1 = tab2.col2)
90153**
90154** where tab1 is the iSrc'th table in SrcList pSrc and tab2 is the
90155** (iSrc+1)'th. Column col1 is column iColLeft of tab1, and col2 is
90156** column iColRight of tab2.
90157*/
90158static void addWhereTerm(
90159  Parse *pParse,                  /* Parsing context */
90160  SrcList *pSrc,                  /* List of tables in FROM clause */
90161  int iLeft,                      /* Index of first table to join in pSrc */
90162  int iColLeft,                   /* Index of column in first table */
90163  int iRight,                     /* Index of second table in pSrc */
90164  int iColRight,                  /* Index of column in second table */
90165  int isOuterJoin,                /* True if this is an OUTER join */
90166  Expr **ppWhere                  /* IN/OUT: The WHERE clause to add to */
90167){
90168  sqlite3 *db = pParse->db;
90169  Expr *pE1;
90170  Expr *pE2;
90171  Expr *pEq;
90172
90173  assert( iLeft<iRight );
90174  assert( pSrc->nSrc>iRight );
90175  assert( pSrc->a[iLeft].pTab );
90176  assert( pSrc->a[iRight].pTab );
90177
90178  pE1 = sqlite3CreateColumnExpr(db, pSrc, iLeft, iColLeft);
90179  pE2 = sqlite3CreateColumnExpr(db, pSrc, iRight, iColRight);
90180
90181  pEq = sqlite3PExpr(pParse, TK_EQ, pE1, pE2, 0);
90182  if( pEq && isOuterJoin ){
90183    ExprSetProperty(pEq, EP_FromJoin);
90184    assert( !ExprHasAnyProperty(pEq, EP_TokenOnly|EP_Reduced) );
90185    ExprSetIrreducible(pEq);
90186    pEq->iRightJoinTable = (i16)pE2->iTable;
90187  }
90188  *ppWhere = sqlite3ExprAnd(db, *ppWhere, pEq);
90189}
90190
90191/*
90192** Set the EP_FromJoin property on all terms of the given expression.
90193** And set the Expr.iRightJoinTable to iTable for every term in the
90194** expression.
90195**
90196** The EP_FromJoin property is used on terms of an expression to tell
90197** the LEFT OUTER JOIN processing logic that this term is part of the
90198** join restriction specified in the ON or USING clause and not a part
90199** of the more general WHERE clause.  These terms are moved over to the
90200** WHERE clause during join processing but we need to remember that they
90201** originated in the ON or USING clause.
90202**
90203** The Expr.iRightJoinTable tells the WHERE clause processing that the
90204** expression depends on table iRightJoinTable even if that table is not
90205** explicitly mentioned in the expression.  That information is needed
90206** for cases like this:
90207**
90208**    SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.b AND t1.x=5
90209**
90210** The where clause needs to defer the handling of the t1.x=5
90211** term until after the t2 loop of the join.  In that way, a
90212** NULL t2 row will be inserted whenever t1.x!=5.  If we do not
90213** defer the handling of t1.x=5, it will be processed immediately
90214** after the t1 loop and rows with t1.x!=5 will never appear in
90215** the output, which is incorrect.
90216*/
90217static void setJoinExpr(Expr *p, int iTable){
90218  while( p ){
90219    ExprSetProperty(p, EP_FromJoin);
90220    assert( !ExprHasAnyProperty(p, EP_TokenOnly|EP_Reduced) );
90221    ExprSetIrreducible(p);
90222    p->iRightJoinTable = (i16)iTable;
90223    setJoinExpr(p->pLeft, iTable);
90224    p = p->pRight;
90225  }
90226}
90227
90228/*
90229** This routine processes the join information for a SELECT statement.
90230** ON and USING clauses are converted into extra terms of the WHERE clause.
90231** NATURAL joins also create extra WHERE clause terms.
90232**
90233** The terms of a FROM clause are contained in the Select.pSrc structure.
90234** The left most table is the first entry in Select.pSrc.  The right-most
90235** table is the last entry.  The join operator is held in the entry to
90236** the left.  Thus entry 0 contains the join operator for the join between
90237** entries 0 and 1.  Any ON or USING clauses associated with the join are
90238** also attached to the left entry.
90239**
90240** This routine returns the number of errors encountered.
90241*/
90242static int sqliteProcessJoin(Parse *pParse, Select *p){
90243  SrcList *pSrc;                  /* All tables in the FROM clause */
90244  int i, j;                       /* Loop counters */
90245  struct SrcList_item *pLeft;     /* Left table being joined */
90246  struct SrcList_item *pRight;    /* Right table being joined */
90247
90248  pSrc = p->pSrc;
90249  pLeft = &pSrc->a[0];
90250  pRight = &pLeft[1];
90251  for(i=0; i<pSrc->nSrc-1; i++, pRight++, pLeft++){
90252    Table *pLeftTab = pLeft->pTab;
90253    Table *pRightTab = pRight->pTab;
90254    int isOuter;
90255
90256    if( NEVER(pLeftTab==0 || pRightTab==0) ) continue;
90257    isOuter = (pRight->jointype & JT_OUTER)!=0;
90258
90259    /* When the NATURAL keyword is present, add WHERE clause terms for
90260    ** every column that the two tables have in common.
90261    */
90262    if( pRight->jointype & JT_NATURAL ){
90263      if( pRight->pOn || pRight->pUsing ){
90264        sqlite3ErrorMsg(pParse, "a NATURAL join may not have "
90265           "an ON or USING clause", 0);
90266        return 1;
90267      }
90268      for(j=0; j<pRightTab->nCol; j++){
90269        char *zName;   /* Name of column in the right table */
90270        int iLeft;     /* Matching left table */
90271        int iLeftCol;  /* Matching column in the left table */
90272
90273        zName = pRightTab->aCol[j].zName;
90274        if( tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol) ){
90275          addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, j,
90276                       isOuter, &p->pWhere);
90277        }
90278      }
90279    }
90280
90281    /* Disallow both ON and USING clauses in the same join
90282    */
90283    if( pRight->pOn && pRight->pUsing ){
90284      sqlite3ErrorMsg(pParse, "cannot have both ON and USING "
90285        "clauses in the same join");
90286      return 1;
90287    }
90288
90289    /* Add the ON clause to the end of the WHERE clause, connected by
90290    ** an AND operator.
90291    */
90292    if( pRight->pOn ){
90293      if( isOuter ) setJoinExpr(pRight->pOn, pRight->iCursor);
90294      p->pWhere = sqlite3ExprAnd(pParse->db, p->pWhere, pRight->pOn);
90295      pRight->pOn = 0;
90296    }
90297
90298    /* Create extra terms on the WHERE clause for each column named
90299    ** in the USING clause.  Example: If the two tables to be joined are
90300    ** A and B and the USING clause names X, Y, and Z, then add this
90301    ** to the WHERE clause:    A.X=B.X AND A.Y=B.Y AND A.Z=B.Z
90302    ** Report an error if any column mentioned in the USING clause is
90303    ** not contained in both tables to be joined.
90304    */
90305    if( pRight->pUsing ){
90306      IdList *pList = pRight->pUsing;
90307      for(j=0; j<pList->nId; j++){
90308        char *zName;     /* Name of the term in the USING clause */
90309        int iLeft;       /* Table on the left with matching column name */
90310        int iLeftCol;    /* Column number of matching column on the left */
90311        int iRightCol;   /* Column number of matching column on the right */
90312
90313        zName = pList->a[j].zName;
90314        iRightCol = columnIndex(pRightTab, zName);
90315        if( iRightCol<0
90316         || !tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol)
90317        ){
90318          sqlite3ErrorMsg(pParse, "cannot join using column %s - column "
90319            "not present in both tables", zName);
90320          return 1;
90321        }
90322        addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, iRightCol,
90323                     isOuter, &p->pWhere);
90324      }
90325    }
90326  }
90327  return 0;
90328}
90329
90330/*
90331** Insert code into "v" that will push the record on the top of the
90332** stack into the sorter.
90333*/
90334static void pushOntoSorter(
90335  Parse *pParse,         /* Parser context */
90336  ExprList *pOrderBy,    /* The ORDER BY clause */
90337  Select *pSelect,       /* The whole SELECT statement */
90338  int regData            /* Register holding data to be sorted */
90339){
90340  Vdbe *v = pParse->pVdbe;
90341  int nExpr = pOrderBy->nExpr;
90342  int regBase = sqlite3GetTempRange(pParse, nExpr+2);
90343  int regRecord = sqlite3GetTempReg(pParse);
90344  sqlite3ExprCacheClear(pParse);
90345  sqlite3ExprCodeExprList(pParse, pOrderBy, regBase, 0);
90346  sqlite3VdbeAddOp2(v, OP_Sequence, pOrderBy->iECursor, regBase+nExpr);
90347  sqlite3ExprCodeMove(pParse, regData, regBase+nExpr+1, 1);
90348  sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nExpr + 2, regRecord);
90349  sqlite3VdbeAddOp2(v, OP_IdxInsert, pOrderBy->iECursor, regRecord);
90350  sqlite3ReleaseTempReg(pParse, regRecord);
90351  sqlite3ReleaseTempRange(pParse, regBase, nExpr+2);
90352  if( pSelect->iLimit ){
90353    int addr1, addr2;
90354    int iLimit;
90355    if( pSelect->iOffset ){
90356      iLimit = pSelect->iOffset+1;
90357    }else{
90358      iLimit = pSelect->iLimit;
90359    }
90360    addr1 = sqlite3VdbeAddOp1(v, OP_IfZero, iLimit);
90361    sqlite3VdbeAddOp2(v, OP_AddImm, iLimit, -1);
90362    addr2 = sqlite3VdbeAddOp0(v, OP_Goto);
90363    sqlite3VdbeJumpHere(v, addr1);
90364    sqlite3VdbeAddOp1(v, OP_Last, pOrderBy->iECursor);
90365    sqlite3VdbeAddOp1(v, OP_Delete, pOrderBy->iECursor);
90366    sqlite3VdbeJumpHere(v, addr2);
90367  }
90368}
90369
90370/*
90371** Add code to implement the OFFSET
90372*/
90373static void codeOffset(
90374  Vdbe *v,          /* Generate code into this VM */
90375  Select *p,        /* The SELECT statement being coded */
90376  int iContinue     /* Jump here to skip the current record */
90377){
90378  if( p->iOffset && iContinue!=0 ){
90379    int addr;
90380    sqlite3VdbeAddOp2(v, OP_AddImm, p->iOffset, -1);
90381    addr = sqlite3VdbeAddOp1(v, OP_IfNeg, p->iOffset);
90382    sqlite3VdbeAddOp2(v, OP_Goto, 0, iContinue);
90383    VdbeComment((v, "skip OFFSET records"));
90384    sqlite3VdbeJumpHere(v, addr);
90385  }
90386}
90387
90388/*
90389** Add code that will check to make sure the N registers starting at iMem
90390** form a distinct entry.  iTab is a sorting index that holds previously
90391** seen combinations of the N values.  A new entry is made in iTab
90392** if the current N values are new.
90393**
90394** A jump to addrRepeat is made and the N+1 values are popped from the
90395** stack if the top N elements are not distinct.
90396*/
90397static void codeDistinct(
90398  Parse *pParse,     /* Parsing and code generating context */
90399  int iTab,          /* A sorting index used to test for distinctness */
90400  int addrRepeat,    /* Jump to here if not distinct */
90401  int N,             /* Number of elements */
90402  int iMem           /* First element */
90403){
90404  Vdbe *v;
90405  int r1;
90406
90407  v = pParse->pVdbe;
90408  r1 = sqlite3GetTempReg(pParse);
90409  sqlite3VdbeAddOp4Int(v, OP_Found, iTab, addrRepeat, iMem, N);
90410  sqlite3VdbeAddOp3(v, OP_MakeRecord, iMem, N, r1);
90411  sqlite3VdbeAddOp2(v, OP_IdxInsert, iTab, r1);
90412  sqlite3ReleaseTempReg(pParse, r1);
90413}
90414
90415#ifndef SQLITE_OMIT_SUBQUERY
90416/*
90417** Generate an error message when a SELECT is used within a subexpression
90418** (example:  "a IN (SELECT * FROM table)") but it has more than 1 result
90419** column.  We do this in a subroutine because the error used to occur
90420** in multiple places.  (The error only occurs in one place now, but we
90421** retain the subroutine to minimize code disruption.)
90422*/
90423static int checkForMultiColumnSelectError(
90424  Parse *pParse,       /* Parse context. */
90425  SelectDest *pDest,   /* Destination of SELECT results */
90426  int nExpr            /* Number of result columns returned by SELECT */
90427){
90428  int eDest = pDest->eDest;
90429  if( nExpr>1 && (eDest==SRT_Mem || eDest==SRT_Set) ){
90430    sqlite3ErrorMsg(pParse, "only a single result allowed for "
90431       "a SELECT that is part of an expression");
90432    return 1;
90433  }else{
90434    return 0;
90435  }
90436}
90437#endif
90438
90439/*
90440** This routine generates the code for the inside of the inner loop
90441** of a SELECT.
90442**
90443** If srcTab and nColumn are both zero, then the pEList expressions
90444** are evaluated in order to get the data for this row.  If nColumn>0
90445** then data is pulled from srcTab and pEList is used only to get the
90446** datatypes for each column.
90447*/
90448static void selectInnerLoop(
90449  Parse *pParse,          /* The parser context */
90450  Select *p,              /* The complete select statement being coded */
90451  ExprList *pEList,       /* List of values being extracted */
90452  int srcTab,             /* Pull data from this table */
90453  int nColumn,            /* Number of columns in the source table */
90454  ExprList *pOrderBy,     /* If not NULL, sort results using this key */
90455  int distinct,           /* If >=0, make sure results are distinct */
90456  SelectDest *pDest,      /* How to dispose of the results */
90457  int iContinue,          /* Jump here to continue with next row */
90458  int iBreak              /* Jump here to break out of the inner loop */
90459){
90460  Vdbe *v = pParse->pVdbe;
90461  int i;
90462  int hasDistinct;        /* True if the DISTINCT keyword is present */
90463  int regResult;              /* Start of memory holding result set */
90464  int eDest = pDest->eDest;   /* How to dispose of results */
90465  int iParm = pDest->iParm;   /* First argument to disposal method */
90466  int nResultCol;             /* Number of result columns */
90467
90468  assert( v );
90469  if( NEVER(v==0) ) return;
90470  assert( pEList!=0 );
90471  hasDistinct = distinct>=0;
90472  if( pOrderBy==0 && !hasDistinct ){
90473    codeOffset(v, p, iContinue);
90474  }
90475
90476  /* Pull the requested columns.
90477  */
90478  if( nColumn>0 ){
90479    nResultCol = nColumn;
90480  }else{
90481    nResultCol = pEList->nExpr;
90482  }
90483  if( pDest->iMem==0 ){
90484    pDest->iMem = pParse->nMem+1;
90485    pDest->nMem = nResultCol;
90486    pParse->nMem += nResultCol;
90487  }else{
90488    assert( pDest->nMem==nResultCol );
90489  }
90490  regResult = pDest->iMem;
90491  if( nColumn>0 ){
90492    for(i=0; i<nColumn; i++){
90493      sqlite3VdbeAddOp3(v, OP_Column, srcTab, i, regResult+i);
90494    }
90495  }else if( eDest!=SRT_Exists ){
90496    /* If the destination is an EXISTS(...) expression, the actual
90497    ** values returned by the SELECT are not required.
90498    */
90499    sqlite3ExprCacheClear(pParse);
90500    sqlite3ExprCodeExprList(pParse, pEList, regResult, eDest==SRT_Output);
90501  }
90502  nColumn = nResultCol;
90503
90504  /* If the DISTINCT keyword was present on the SELECT statement
90505  ** and this row has been seen before, then do not make this row
90506  ** part of the result.
90507  */
90508  if( hasDistinct ){
90509    assert( pEList!=0 );
90510    assert( pEList->nExpr==nColumn );
90511    codeDistinct(pParse, distinct, iContinue, nColumn, regResult);
90512    if( pOrderBy==0 ){
90513      codeOffset(v, p, iContinue);
90514    }
90515  }
90516
90517  switch( eDest ){
90518    /* In this mode, write each query result to the key of the temporary
90519    ** table iParm.
90520    */
90521#ifndef SQLITE_OMIT_COMPOUND_SELECT
90522    case SRT_Union: {
90523      int r1;
90524      r1 = sqlite3GetTempReg(pParse);
90525      sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1);
90526      sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1);
90527      sqlite3ReleaseTempReg(pParse, r1);
90528      break;
90529    }
90530
90531    /* Construct a record from the query result, but instead of
90532    ** saving that record, use it as a key to delete elements from
90533    ** the temporary table iParm.
90534    */
90535    case SRT_Except: {
90536      sqlite3VdbeAddOp3(v, OP_IdxDelete, iParm, regResult, nColumn);
90537      break;
90538    }
90539#endif
90540
90541    /* Store the result as data using a unique key.
90542    */
90543    case SRT_Table:
90544    case SRT_EphemTab: {
90545      int r1 = sqlite3GetTempReg(pParse);
90546      testcase( eDest==SRT_Table );
90547      testcase( eDest==SRT_EphemTab );
90548      sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1);
90549      if( pOrderBy ){
90550        pushOntoSorter(pParse, pOrderBy, p, r1);
90551      }else{
90552        int r2 = sqlite3GetTempReg(pParse);
90553        sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, r2);
90554        sqlite3VdbeAddOp3(v, OP_Insert, iParm, r1, r2);
90555        sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
90556        sqlite3ReleaseTempReg(pParse, r2);
90557      }
90558      sqlite3ReleaseTempReg(pParse, r1);
90559      break;
90560    }
90561
90562#ifndef SQLITE_OMIT_SUBQUERY
90563    /* If we are creating a set for an "expr IN (SELECT ...)" construct,
90564    ** then there should be a single item on the stack.  Write this
90565    ** item into the set table with bogus data.
90566    */
90567    case SRT_Set: {
90568      assert( nColumn==1 );
90569      p->affinity = sqlite3CompareAffinity(pEList->a[0].pExpr, pDest->affinity);
90570      if( pOrderBy ){
90571        /* At first glance you would think we could optimize out the
90572        ** ORDER BY in this case since the order of entries in the set
90573        ** does not matter.  But there might be a LIMIT clause, in which
90574        ** case the order does matter */
90575        pushOntoSorter(pParse, pOrderBy, p, regResult);
90576      }else{
90577        int r1 = sqlite3GetTempReg(pParse);
90578        sqlite3VdbeAddOp4(v, OP_MakeRecord, regResult, 1, r1, &p->affinity, 1);
90579        sqlite3ExprCacheAffinityChange(pParse, regResult, 1);
90580        sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1);
90581        sqlite3ReleaseTempReg(pParse, r1);
90582      }
90583      break;
90584    }
90585
90586    /* If any row exist in the result set, record that fact and abort.
90587    */
90588    case SRT_Exists: {
90589      sqlite3VdbeAddOp2(v, OP_Integer, 1, iParm);
90590      /* The LIMIT clause will terminate the loop for us */
90591      break;
90592    }
90593
90594    /* If this is a scalar select that is part of an expression, then
90595    ** store the results in the appropriate memory cell and break out
90596    ** of the scan loop.
90597    */
90598    case SRT_Mem: {
90599      assert( nColumn==1 );
90600      if( pOrderBy ){
90601        pushOntoSorter(pParse, pOrderBy, p, regResult);
90602      }else{
90603        sqlite3ExprCodeMove(pParse, regResult, iParm, 1);
90604        /* The LIMIT clause will jump out of the loop for us */
90605      }
90606      break;
90607    }
90608#endif /* #ifndef SQLITE_OMIT_SUBQUERY */
90609
90610    /* Send the data to the callback function or to a subroutine.  In the
90611    ** case of a subroutine, the subroutine itself is responsible for
90612    ** popping the data from the stack.
90613    */
90614    case SRT_Coroutine:
90615    case SRT_Output: {
90616      testcase( eDest==SRT_Coroutine );
90617      testcase( eDest==SRT_Output );
90618      if( pOrderBy ){
90619        int r1 = sqlite3GetTempReg(pParse);
90620        sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1);
90621        pushOntoSorter(pParse, pOrderBy, p, r1);
90622        sqlite3ReleaseTempReg(pParse, r1);
90623      }else if( eDest==SRT_Coroutine ){
90624        sqlite3VdbeAddOp1(v, OP_Yield, pDest->iParm);
90625      }else{
90626        sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, nColumn);
90627        sqlite3ExprCacheAffinityChange(pParse, regResult, nColumn);
90628      }
90629      break;
90630    }
90631
90632#if !defined(SQLITE_OMIT_TRIGGER)
90633    /* Discard the results.  This is used for SELECT statements inside
90634    ** the body of a TRIGGER.  The purpose of such selects is to call
90635    ** user-defined functions that have side effects.  We do not care
90636    ** about the actual results of the select.
90637    */
90638    default: {
90639      assert( eDest==SRT_Discard );
90640      break;
90641    }
90642#endif
90643  }
90644
90645  /* Jump to the end of the loop if the LIMIT is reached.  Except, if
90646  ** there is a sorter, in which case the sorter has already limited
90647  ** the output for us.
90648  */
90649  if( pOrderBy==0 && p->iLimit ){
90650    sqlite3VdbeAddOp3(v, OP_IfZero, p->iLimit, iBreak, -1);
90651  }
90652}
90653
90654/*
90655** Given an expression list, generate a KeyInfo structure that records
90656** the collating sequence for each expression in that expression list.
90657**
90658** If the ExprList is an ORDER BY or GROUP BY clause then the resulting
90659** KeyInfo structure is appropriate for initializing a virtual index to
90660** implement that clause.  If the ExprList is the result set of a SELECT
90661** then the KeyInfo structure is appropriate for initializing a virtual
90662** index to implement a DISTINCT test.
90663**
90664** Space to hold the KeyInfo structure is obtain from malloc.  The calling
90665** function is responsible for seeing that this structure is eventually
90666** freed.  Add the KeyInfo structure to the P4 field of an opcode using
90667** P4_KEYINFO_HANDOFF is the usual way of dealing with this.
90668*/
90669static KeyInfo *keyInfoFromExprList(Parse *pParse, ExprList *pList){
90670  sqlite3 *db = pParse->db;
90671  int nExpr;
90672  KeyInfo *pInfo;
90673  struct ExprList_item *pItem;
90674  int i;
90675
90676  nExpr = pList->nExpr;
90677  pInfo = sqlite3DbMallocZero(db, sizeof(*pInfo) + nExpr*(sizeof(CollSeq*)+1) );
90678  if( pInfo ){
90679    pInfo->aSortOrder = (u8*)&pInfo->aColl[nExpr];
90680    pInfo->nField = (u16)nExpr;
90681    pInfo->enc = ENC(db);
90682    pInfo->db = db;
90683    for(i=0, pItem=pList->a; i<nExpr; i++, pItem++){
90684      CollSeq *pColl;
90685      pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
90686      if( !pColl ){
90687        pColl = db->pDfltColl;
90688      }
90689      pInfo->aColl[i] = pColl;
90690      pInfo->aSortOrder[i] = pItem->sortOrder;
90691    }
90692  }
90693  return pInfo;
90694}
90695
90696#ifndef SQLITE_OMIT_COMPOUND_SELECT
90697/*
90698** Name of the connection operator, used for error messages.
90699*/
90700static const char *selectOpName(int id){
90701  char *z;
90702  switch( id ){
90703    case TK_ALL:       z = "UNION ALL";   break;
90704    case TK_INTERSECT: z = "INTERSECT";   break;
90705    case TK_EXCEPT:    z = "EXCEPT";      break;
90706    default:           z = "UNION";       break;
90707  }
90708  return z;
90709}
90710#endif /* SQLITE_OMIT_COMPOUND_SELECT */
90711
90712#ifndef SQLITE_OMIT_EXPLAIN
90713/*
90714** Unless an "EXPLAIN QUERY PLAN" command is being processed, this function
90715** is a no-op. Otherwise, it adds a single row of output to the EQP result,
90716** where the caption is of the form:
90717**
90718**   "USE TEMP B-TREE FOR xxx"
90719**
90720** where xxx is one of "DISTINCT", "ORDER BY" or "GROUP BY". Exactly which
90721** is determined by the zUsage argument.
90722*/
90723static void explainTempTable(Parse *pParse, const char *zUsage){
90724  if( pParse->explain==2 ){
90725    Vdbe *v = pParse->pVdbe;
90726    char *zMsg = sqlite3MPrintf(pParse->db, "USE TEMP B-TREE FOR %s", zUsage);
90727    sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
90728  }
90729}
90730
90731/*
90732** Assign expression b to lvalue a. A second, no-op, version of this macro
90733** is provided when SQLITE_OMIT_EXPLAIN is defined. This allows the code
90734** in sqlite3Select() to assign values to structure member variables that
90735** only exist if SQLITE_OMIT_EXPLAIN is not defined without polluting the
90736** code with #ifndef directives.
90737*/
90738# define explainSetInteger(a, b) a = b
90739
90740#else
90741/* No-op versions of the explainXXX() functions and macros. */
90742# define explainTempTable(y,z)
90743# define explainSetInteger(y,z)
90744#endif
90745
90746#if !defined(SQLITE_OMIT_EXPLAIN) && !defined(SQLITE_OMIT_COMPOUND_SELECT)
90747/*
90748** Unless an "EXPLAIN QUERY PLAN" command is being processed, this function
90749** is a no-op. Otherwise, it adds a single row of output to the EQP result,
90750** where the caption is of one of the two forms:
90751**
90752**   "COMPOSITE SUBQUERIES iSub1 and iSub2 (op)"
90753**   "COMPOSITE SUBQUERIES iSub1 and iSub2 USING TEMP B-TREE (op)"
90754**
90755** where iSub1 and iSub2 are the integers passed as the corresponding
90756** function parameters, and op is the text representation of the parameter
90757** of the same name. The parameter "op" must be one of TK_UNION, TK_EXCEPT,
90758** TK_INTERSECT or TK_ALL. The first form is used if argument bUseTmp is
90759** false, or the second form if it is true.
90760*/
90761static void explainComposite(
90762  Parse *pParse,                  /* Parse context */
90763  int op,                         /* One of TK_UNION, TK_EXCEPT etc. */
90764  int iSub1,                      /* Subquery id 1 */
90765  int iSub2,                      /* Subquery id 2 */
90766  int bUseTmp                     /* True if a temp table was used */
90767){
90768  assert( op==TK_UNION || op==TK_EXCEPT || op==TK_INTERSECT || op==TK_ALL );
90769  if( pParse->explain==2 ){
90770    Vdbe *v = pParse->pVdbe;
90771    char *zMsg = sqlite3MPrintf(
90772        pParse->db, "COMPOUND SUBQUERIES %d AND %d %s(%s)", iSub1, iSub2,
90773        bUseTmp?"USING TEMP B-TREE ":"", selectOpName(op)
90774    );
90775    sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
90776  }
90777}
90778#else
90779/* No-op versions of the explainXXX() functions and macros. */
90780# define explainComposite(v,w,x,y,z)
90781#endif
90782
90783/*
90784** If the inner loop was generated using a non-null pOrderBy argument,
90785** then the results were placed in a sorter.  After the loop is terminated
90786** we need to run the sorter and output the results.  The following
90787** routine generates the code needed to do that.
90788*/
90789static void generateSortTail(
90790  Parse *pParse,    /* Parsing context */
90791  Select *p,        /* The SELECT statement */
90792  Vdbe *v,          /* Generate code into this VDBE */
90793  int nColumn,      /* Number of columns of data */
90794  SelectDest *pDest /* Write the sorted results here */
90795){
90796  int addrBreak = sqlite3VdbeMakeLabel(v);     /* Jump here to exit loop */
90797  int addrContinue = sqlite3VdbeMakeLabel(v);  /* Jump here for next cycle */
90798  int addr;
90799  int iTab;
90800  int pseudoTab = 0;
90801  ExprList *pOrderBy = p->pOrderBy;
90802
90803  int eDest = pDest->eDest;
90804  int iParm = pDest->iParm;
90805
90806  int regRow;
90807  int regRowid;
90808
90809  iTab = pOrderBy->iECursor;
90810  regRow = sqlite3GetTempReg(pParse);
90811  if( eDest==SRT_Output || eDest==SRT_Coroutine ){
90812    pseudoTab = pParse->nTab++;
90813    sqlite3VdbeAddOp3(v, OP_OpenPseudo, pseudoTab, regRow, nColumn);
90814    regRowid = 0;
90815  }else{
90816    regRowid = sqlite3GetTempReg(pParse);
90817  }
90818  addr = 1 + sqlite3VdbeAddOp2(v, OP_Sort, iTab, addrBreak);
90819  codeOffset(v, p, addrContinue);
90820  sqlite3VdbeAddOp3(v, OP_Column, iTab, pOrderBy->nExpr + 1, regRow);
90821  switch( eDest ){
90822    case SRT_Table:
90823    case SRT_EphemTab: {
90824      testcase( eDest==SRT_Table );
90825      testcase( eDest==SRT_EphemTab );
90826      sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, regRowid);
90827      sqlite3VdbeAddOp3(v, OP_Insert, iParm, regRow, regRowid);
90828      sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
90829      break;
90830    }
90831#ifndef SQLITE_OMIT_SUBQUERY
90832    case SRT_Set: {
90833      assert( nColumn==1 );
90834      sqlite3VdbeAddOp4(v, OP_MakeRecord, regRow, 1, regRowid, &p->affinity, 1);
90835      sqlite3ExprCacheAffinityChange(pParse, regRow, 1);
90836      sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, regRowid);
90837      break;
90838    }
90839    case SRT_Mem: {
90840      assert( nColumn==1 );
90841      sqlite3ExprCodeMove(pParse, regRow, iParm, 1);
90842      /* The LIMIT clause will terminate the loop for us */
90843      break;
90844    }
90845#endif
90846    default: {
90847      int i;
90848      assert( eDest==SRT_Output || eDest==SRT_Coroutine );
90849      testcase( eDest==SRT_Output );
90850      testcase( eDest==SRT_Coroutine );
90851      for(i=0; i<nColumn; i++){
90852        assert( regRow!=pDest->iMem+i );
90853        sqlite3VdbeAddOp3(v, OP_Column, pseudoTab, i, pDest->iMem+i);
90854        if( i==0 ){
90855          sqlite3VdbeChangeP5(v, OPFLAG_CLEARCACHE);
90856        }
90857      }
90858      if( eDest==SRT_Output ){
90859        sqlite3VdbeAddOp2(v, OP_ResultRow, pDest->iMem, nColumn);
90860        sqlite3ExprCacheAffinityChange(pParse, pDest->iMem, nColumn);
90861      }else{
90862        sqlite3VdbeAddOp1(v, OP_Yield, pDest->iParm);
90863      }
90864      break;
90865    }
90866  }
90867  sqlite3ReleaseTempReg(pParse, regRow);
90868  sqlite3ReleaseTempReg(pParse, regRowid);
90869
90870  /* The bottom of the loop
90871  */
90872  sqlite3VdbeResolveLabel(v, addrContinue);
90873  sqlite3VdbeAddOp2(v, OP_Next, iTab, addr);
90874  sqlite3VdbeResolveLabel(v, addrBreak);
90875  if( eDest==SRT_Output || eDest==SRT_Coroutine ){
90876    sqlite3VdbeAddOp2(v, OP_Close, pseudoTab, 0);
90877  }
90878}
90879
90880/*
90881** Return a pointer to a string containing the 'declaration type' of the
90882** expression pExpr. The string may be treated as static by the caller.
90883**
90884** The declaration type is the exact datatype definition extracted from the
90885** original CREATE TABLE statement if the expression is a column. The
90886** declaration type for a ROWID field is INTEGER. Exactly when an expression
90887** is considered a column can be complex in the presence of subqueries. The
90888** result-set expression in all of the following SELECT statements is
90889** considered a column by this function.
90890**
90891**   SELECT col FROM tbl;
90892**   SELECT (SELECT col FROM tbl;
90893**   SELECT (SELECT col FROM tbl);
90894**   SELECT abc FROM (SELECT col AS abc FROM tbl);
90895**
90896** The declaration type for any expression other than a column is NULL.
90897*/
90898static const char *columnType(
90899  NameContext *pNC,
90900  Expr *pExpr,
90901  const char **pzOriginDb,
90902  const char **pzOriginTab,
90903  const char **pzOriginCol
90904){
90905  char const *zType = 0;
90906  char const *zOriginDb = 0;
90907  char const *zOriginTab = 0;
90908  char const *zOriginCol = 0;
90909  int j;
90910  if( NEVER(pExpr==0) || pNC->pSrcList==0 ) return 0;
90911
90912  switch( pExpr->op ){
90913    case TK_AGG_COLUMN:
90914    case TK_COLUMN: {
90915      /* The expression is a column. Locate the table the column is being
90916      ** extracted from in NameContext.pSrcList. This table may be real
90917      ** database table or a subquery.
90918      */
90919      Table *pTab = 0;            /* Table structure column is extracted from */
90920      Select *pS = 0;             /* Select the column is extracted from */
90921      int iCol = pExpr->iColumn;  /* Index of column in pTab */
90922      testcase( pExpr->op==TK_AGG_COLUMN );
90923      testcase( pExpr->op==TK_COLUMN );
90924      while( pNC && !pTab ){
90925        SrcList *pTabList = pNC->pSrcList;
90926        for(j=0;j<pTabList->nSrc && pTabList->a[j].iCursor!=pExpr->iTable;j++);
90927        if( j<pTabList->nSrc ){
90928          pTab = pTabList->a[j].pTab;
90929          pS = pTabList->a[j].pSelect;
90930        }else{
90931          pNC = pNC->pNext;
90932        }
90933      }
90934
90935      if( pTab==0 ){
90936        /* At one time, code such as "SELECT new.x" within a trigger would
90937        ** cause this condition to run.  Since then, we have restructured how
90938        ** trigger code is generated and so this condition is no longer
90939        ** possible. However, it can still be true for statements like
90940        ** the following:
90941        **
90942        **   CREATE TABLE t1(col INTEGER);
90943        **   SELECT (SELECT t1.col) FROM FROM t1;
90944        **
90945        ** when columnType() is called on the expression "t1.col" in the
90946        ** sub-select. In this case, set the column type to NULL, even
90947        ** though it should really be "INTEGER".
90948        **
90949        ** This is not a problem, as the column type of "t1.col" is never
90950        ** used. When columnType() is called on the expression
90951        ** "(SELECT t1.col)", the correct type is returned (see the TK_SELECT
90952        ** branch below.  */
90953        break;
90954      }
90955
90956      assert( pTab && pExpr->pTab==pTab );
90957      if( pS ){
90958        /* The "table" is actually a sub-select or a view in the FROM clause
90959        ** of the SELECT statement. Return the declaration type and origin
90960        ** data for the result-set column of the sub-select.
90961        */
90962        if( iCol>=0 && ALWAYS(iCol<pS->pEList->nExpr) ){
90963          /* If iCol is less than zero, then the expression requests the
90964          ** rowid of the sub-select or view. This expression is legal (see
90965          ** test case misc2.2.2) - it always evaluates to NULL.
90966          */
90967          NameContext sNC;
90968          Expr *p = pS->pEList->a[iCol].pExpr;
90969          sNC.pSrcList = pS->pSrc;
90970          sNC.pNext = pNC;
90971          sNC.pParse = pNC->pParse;
90972          zType = columnType(&sNC, p, &zOriginDb, &zOriginTab, &zOriginCol);
90973        }
90974      }else if( ALWAYS(pTab->pSchema) ){
90975        /* A real table */
90976        assert( !pS );
90977        if( iCol<0 ) iCol = pTab->iPKey;
90978        assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
90979        if( iCol<0 ){
90980          zType = "INTEGER";
90981          zOriginCol = "rowid";
90982        }else{
90983          zType = pTab->aCol[iCol].zType;
90984          zOriginCol = pTab->aCol[iCol].zName;
90985        }
90986        zOriginTab = pTab->zName;
90987        if( pNC->pParse ){
90988          int iDb = sqlite3SchemaToIndex(pNC->pParse->db, pTab->pSchema);
90989          zOriginDb = pNC->pParse->db->aDb[iDb].zName;
90990        }
90991      }
90992      break;
90993    }
90994#ifndef SQLITE_OMIT_SUBQUERY
90995    case TK_SELECT: {
90996      /* The expression is a sub-select. Return the declaration type and
90997      ** origin info for the single column in the result set of the SELECT
90998      ** statement.
90999      */
91000      NameContext sNC;
91001      Select *pS = pExpr->x.pSelect;
91002      Expr *p = pS->pEList->a[0].pExpr;
91003      assert( ExprHasProperty(pExpr, EP_xIsSelect) );
91004      sNC.pSrcList = pS->pSrc;
91005      sNC.pNext = pNC;
91006      sNC.pParse = pNC->pParse;
91007      zType = columnType(&sNC, p, &zOriginDb, &zOriginTab, &zOriginCol);
91008      break;
91009    }
91010#endif
91011  }
91012
91013  if( pzOriginDb ){
91014    assert( pzOriginTab && pzOriginCol );
91015    *pzOriginDb = zOriginDb;
91016    *pzOriginTab = zOriginTab;
91017    *pzOriginCol = zOriginCol;
91018  }
91019  return zType;
91020}
91021
91022/*
91023** Generate code that will tell the VDBE the declaration types of columns
91024** in the result set.
91025*/
91026static void generateColumnTypes(
91027  Parse *pParse,      /* Parser context */
91028  SrcList *pTabList,  /* List of tables */
91029  ExprList *pEList    /* Expressions defining the result set */
91030){
91031#ifndef SQLITE_OMIT_DECLTYPE
91032  Vdbe *v = pParse->pVdbe;
91033  int i;
91034  NameContext sNC;
91035  sNC.pSrcList = pTabList;
91036  sNC.pParse = pParse;
91037  for(i=0; i<pEList->nExpr; i++){
91038    Expr *p = pEList->a[i].pExpr;
91039    const char *zType;
91040#ifdef SQLITE_ENABLE_COLUMN_METADATA
91041    const char *zOrigDb = 0;
91042    const char *zOrigTab = 0;
91043    const char *zOrigCol = 0;
91044    zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol);
91045
91046    /* The vdbe must make its own copy of the column-type and other
91047    ** column specific strings, in case the schema is reset before this
91048    ** virtual machine is deleted.
91049    */
91050    sqlite3VdbeSetColName(v, i, COLNAME_DATABASE, zOrigDb, SQLITE_TRANSIENT);
91051    sqlite3VdbeSetColName(v, i, COLNAME_TABLE, zOrigTab, SQLITE_TRANSIENT);
91052    sqlite3VdbeSetColName(v, i, COLNAME_COLUMN, zOrigCol, SQLITE_TRANSIENT);
91053#else
91054    zType = columnType(&sNC, p, 0, 0, 0);
91055#endif
91056    sqlite3VdbeSetColName(v, i, COLNAME_DECLTYPE, zType, SQLITE_TRANSIENT);
91057  }
91058#endif /* SQLITE_OMIT_DECLTYPE */
91059}
91060
91061/*
91062** Generate code that will tell the VDBE the names of columns
91063** in the result set.  This information is used to provide the
91064** azCol[] values in the callback.
91065*/
91066static void generateColumnNames(
91067  Parse *pParse,      /* Parser context */
91068  SrcList *pTabList,  /* List of tables */
91069  ExprList *pEList    /* Expressions defining the result set */
91070){
91071  Vdbe *v = pParse->pVdbe;
91072  int i, j;
91073  sqlite3 *db = pParse->db;
91074  int fullNames, shortNames;
91075
91076#ifndef SQLITE_OMIT_EXPLAIN
91077  /* If this is an EXPLAIN, skip this step */
91078  if( pParse->explain ){
91079    return;
91080  }
91081#endif
91082
91083  if( pParse->colNamesSet || NEVER(v==0) || db->mallocFailed ) return;
91084  pParse->colNamesSet = 1;
91085  fullNames = (db->flags & SQLITE_FullColNames)!=0;
91086  shortNames = (db->flags & SQLITE_ShortColNames)!=0;
91087  sqlite3VdbeSetNumCols(v, pEList->nExpr);
91088  for(i=0; i<pEList->nExpr; i++){
91089    Expr *p;
91090    p = pEList->a[i].pExpr;
91091    if( NEVER(p==0) ) continue;
91092    if( pEList->a[i].zName ){
91093      char *zName = pEList->a[i].zName;
91094      sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_TRANSIENT);
91095    }else if( (p->op==TK_COLUMN || p->op==TK_AGG_COLUMN) && pTabList ){
91096      Table *pTab;
91097      char *zCol;
91098      int iCol = p->iColumn;
91099      for(j=0; ALWAYS(j<pTabList->nSrc); j++){
91100        if( pTabList->a[j].iCursor==p->iTable ) break;
91101      }
91102      assert( j<pTabList->nSrc );
91103      pTab = pTabList->a[j].pTab;
91104      if( iCol<0 ) iCol = pTab->iPKey;
91105      assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
91106      if( iCol<0 ){
91107        zCol = "rowid";
91108      }else{
91109        zCol = pTab->aCol[iCol].zName;
91110      }
91111      if( !shortNames && !fullNames ){
91112        sqlite3VdbeSetColName(v, i, COLNAME_NAME,
91113            sqlite3DbStrDup(db, pEList->a[i].zSpan), SQLITE_DYNAMIC);
91114      }else if( fullNames ){
91115        char *zName = 0;
91116        zName = sqlite3MPrintf(db, "%s.%s", pTab->zName, zCol);
91117        sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_DYNAMIC);
91118      }else{
91119        sqlite3VdbeSetColName(v, i, COLNAME_NAME, zCol, SQLITE_TRANSIENT);
91120      }
91121    }else{
91122      sqlite3VdbeSetColName(v, i, COLNAME_NAME,
91123          sqlite3DbStrDup(db, pEList->a[i].zSpan), SQLITE_DYNAMIC);
91124    }
91125  }
91126  generateColumnTypes(pParse, pTabList, pEList);
91127}
91128
91129/*
91130** Given a an expression list (which is really the list of expressions
91131** that form the result set of a SELECT statement) compute appropriate
91132** column names for a table that would hold the expression list.
91133**
91134** All column names will be unique.
91135**
91136** Only the column names are computed.  Column.zType, Column.zColl,
91137** and other fields of Column are zeroed.
91138**
91139** Return SQLITE_OK on success.  If a memory allocation error occurs,
91140** store NULL in *paCol and 0 in *pnCol and return SQLITE_NOMEM.
91141*/
91142static int selectColumnsFromExprList(
91143  Parse *pParse,          /* Parsing context */
91144  ExprList *pEList,       /* Expr list from which to derive column names */
91145  int *pnCol,             /* Write the number of columns here */
91146  Column **paCol          /* Write the new column list here */
91147){
91148  sqlite3 *db = pParse->db;   /* Database connection */
91149  int i, j;                   /* Loop counters */
91150  int cnt;                    /* Index added to make the name unique */
91151  Column *aCol, *pCol;        /* For looping over result columns */
91152  int nCol;                   /* Number of columns in the result set */
91153  Expr *p;                    /* Expression for a single result column */
91154  char *zName;                /* Column name */
91155  int nName;                  /* Size of name in zName[] */
91156
91157  *pnCol = nCol = pEList->nExpr;
91158  aCol = *paCol = sqlite3DbMallocZero(db, sizeof(aCol[0])*nCol);
91159  if( aCol==0 ) return SQLITE_NOMEM;
91160  for(i=0, pCol=aCol; i<nCol; i++, pCol++){
91161    /* Get an appropriate name for the column
91162    */
91163    p = pEList->a[i].pExpr;
91164    assert( p->pRight==0 || ExprHasProperty(p->pRight, EP_IntValue)
91165               || p->pRight->u.zToken==0 || p->pRight->u.zToken[0]!=0 );
91166    if( (zName = pEList->a[i].zName)!=0 ){
91167      /* If the column contains an "AS <name>" phrase, use <name> as the name */
91168      zName = sqlite3DbStrDup(db, zName);
91169    }else{
91170      Expr *pColExpr = p;  /* The expression that is the result column name */
91171      Table *pTab;         /* Table associated with this expression */
91172      while( pColExpr->op==TK_DOT ) pColExpr = pColExpr->pRight;
91173      if( pColExpr->op==TK_COLUMN && ALWAYS(pColExpr->pTab!=0) ){
91174        /* For columns use the column name name */
91175        int iCol = pColExpr->iColumn;
91176        pTab = pColExpr->pTab;
91177        if( iCol<0 ) iCol = pTab->iPKey;
91178        zName = sqlite3MPrintf(db, "%s",
91179                 iCol>=0 ? pTab->aCol[iCol].zName : "rowid");
91180      }else if( pColExpr->op==TK_ID ){
91181        assert( !ExprHasProperty(pColExpr, EP_IntValue) );
91182        zName = sqlite3MPrintf(db, "%s", pColExpr->u.zToken);
91183      }else{
91184        /* Use the original text of the column expression as its name */
91185        zName = sqlite3MPrintf(db, "%s", pEList->a[i].zSpan);
91186      }
91187    }
91188    if( db->mallocFailed ){
91189      sqlite3DbFree(db, zName);
91190      break;
91191    }
91192
91193    /* Make sure the column name is unique.  If the name is not unique,
91194    ** append a integer to the name so that it becomes unique.
91195    */
91196    nName = sqlite3Strlen30(zName);
91197    for(j=cnt=0; j<i; j++){
91198      if( sqlite3StrICmp(aCol[j].zName, zName)==0 ){
91199        char *zNewName;
91200        zName[nName] = 0;
91201        zNewName = sqlite3MPrintf(db, "%s:%d", zName, ++cnt);
91202        sqlite3DbFree(db, zName);
91203        zName = zNewName;
91204        j = -1;
91205        if( zName==0 ) break;
91206      }
91207    }
91208    pCol->zName = zName;
91209  }
91210  if( db->mallocFailed ){
91211    for(j=0; j<i; j++){
91212      sqlite3DbFree(db, aCol[j].zName);
91213    }
91214    sqlite3DbFree(db, aCol);
91215    *paCol = 0;
91216    *pnCol = 0;
91217    return SQLITE_NOMEM;
91218  }
91219  return SQLITE_OK;
91220}
91221
91222/*
91223** Add type and collation information to a column list based on
91224** a SELECT statement.
91225**
91226** The column list presumably came from selectColumnNamesFromExprList().
91227** The column list has only names, not types or collations.  This
91228** routine goes through and adds the types and collations.
91229**
91230** This routine requires that all identifiers in the SELECT
91231** statement be resolved.
91232*/
91233static void selectAddColumnTypeAndCollation(
91234  Parse *pParse,        /* Parsing contexts */
91235  int nCol,             /* Number of columns */
91236  Column *aCol,         /* List of columns */
91237  Select *pSelect       /* SELECT used to determine types and collations */
91238){
91239  sqlite3 *db = pParse->db;
91240  NameContext sNC;
91241  Column *pCol;
91242  CollSeq *pColl;
91243  int i;
91244  Expr *p;
91245  struct ExprList_item *a;
91246
91247  assert( pSelect!=0 );
91248  assert( (pSelect->selFlags & SF_Resolved)!=0 );
91249  assert( nCol==pSelect->pEList->nExpr || db->mallocFailed );
91250  if( db->mallocFailed ) return;
91251  memset(&sNC, 0, sizeof(sNC));
91252  sNC.pSrcList = pSelect->pSrc;
91253  a = pSelect->pEList->a;
91254  for(i=0, pCol=aCol; i<nCol; i++, pCol++){
91255    p = a[i].pExpr;
91256    pCol->zType = sqlite3DbStrDup(db, columnType(&sNC, p, 0, 0, 0));
91257    pCol->affinity = sqlite3ExprAffinity(p);
91258    if( pCol->affinity==0 ) pCol->affinity = SQLITE_AFF_NONE;
91259    pColl = sqlite3ExprCollSeq(pParse, p);
91260    if( pColl ){
91261      pCol->zColl = sqlite3DbStrDup(db, pColl->zName);
91262    }
91263  }
91264}
91265
91266/*
91267** Given a SELECT statement, generate a Table structure that describes
91268** the result set of that SELECT.
91269*/
91270SQLITE_PRIVATE Table *sqlite3ResultSetOfSelect(Parse *pParse, Select *pSelect){
91271  Table *pTab;
91272  sqlite3 *db = pParse->db;
91273  int savedFlags;
91274
91275  savedFlags = db->flags;
91276  db->flags &= ~SQLITE_FullColNames;
91277  db->flags |= SQLITE_ShortColNames;
91278  sqlite3SelectPrep(pParse, pSelect, 0);
91279  if( pParse->nErr ) return 0;
91280  while( pSelect->pPrior ) pSelect = pSelect->pPrior;
91281  db->flags = savedFlags;
91282  pTab = sqlite3DbMallocZero(db, sizeof(Table) );
91283  if( pTab==0 ){
91284    return 0;
91285  }
91286  /* The sqlite3ResultSetOfSelect() is only used n contexts where lookaside
91287  ** is disabled */
91288  assert( db->lookaside.bEnabled==0 );
91289  pTab->nRef = 1;
91290  pTab->zName = 0;
91291  pTab->nRowEst = 1000000;
91292  selectColumnsFromExprList(pParse, pSelect->pEList, &pTab->nCol, &pTab->aCol);
91293  selectAddColumnTypeAndCollation(pParse, pTab->nCol, pTab->aCol, pSelect);
91294  pTab->iPKey = -1;
91295  if( db->mallocFailed ){
91296    sqlite3DeleteTable(db, pTab);
91297    return 0;
91298  }
91299  return pTab;
91300}
91301
91302/*
91303** Get a VDBE for the given parser context.  Create a new one if necessary.
91304** If an error occurs, return NULL and leave a message in pParse.
91305*/
91306SQLITE_PRIVATE Vdbe *sqlite3GetVdbe(Parse *pParse){
91307  Vdbe *v = pParse->pVdbe;
91308  if( v==0 ){
91309    v = pParse->pVdbe = sqlite3VdbeCreate(pParse->db);
91310#ifndef SQLITE_OMIT_TRACE
91311    if( v ){
91312      sqlite3VdbeAddOp0(v, OP_Trace);
91313    }
91314#endif
91315  }
91316  return v;
91317}
91318
91319
91320/*
91321** Compute the iLimit and iOffset fields of the SELECT based on the
91322** pLimit and pOffset expressions.  pLimit and pOffset hold the expressions
91323** that appear in the original SQL statement after the LIMIT and OFFSET
91324** keywords.  Or NULL if those keywords are omitted. iLimit and iOffset
91325** are the integer memory register numbers for counters used to compute
91326** the limit and offset.  If there is no limit and/or offset, then
91327** iLimit and iOffset are negative.
91328**
91329** This routine changes the values of iLimit and iOffset only if
91330** a limit or offset is defined by pLimit and pOffset.  iLimit and
91331** iOffset should have been preset to appropriate default values
91332** (usually but not always -1) prior to calling this routine.
91333** Only if pLimit!=0 or pOffset!=0 do the limit registers get
91334** redefined.  The UNION ALL operator uses this property to force
91335** the reuse of the same limit and offset registers across multiple
91336** SELECT statements.
91337*/
91338static void computeLimitRegisters(Parse *pParse, Select *p, int iBreak){
91339  Vdbe *v = 0;
91340  int iLimit = 0;
91341  int iOffset;
91342  int addr1, n;
91343  if( p->iLimit ) return;
91344
91345  /*
91346  ** "LIMIT -1" always shows all rows.  There is some
91347  ** contraversy about what the correct behavior should be.
91348  ** The current implementation interprets "LIMIT 0" to mean
91349  ** no rows.
91350  */
91351  sqlite3ExprCacheClear(pParse);
91352  assert( p->pOffset==0 || p->pLimit!=0 );
91353  if( p->pLimit ){
91354    p->iLimit = iLimit = ++pParse->nMem;
91355    v = sqlite3GetVdbe(pParse);
91356    if( NEVER(v==0) ) return;  /* VDBE should have already been allocated */
91357    if( sqlite3ExprIsInteger(p->pLimit, &n) ){
91358      sqlite3VdbeAddOp2(v, OP_Integer, n, iLimit);
91359      VdbeComment((v, "LIMIT counter"));
91360      if( n==0 ){
91361        sqlite3VdbeAddOp2(v, OP_Goto, 0, iBreak);
91362      }else{
91363        if( p->nSelectRow > (double)n ) p->nSelectRow = (double)n;
91364      }
91365    }else{
91366      sqlite3ExprCode(pParse, p->pLimit, iLimit);
91367      sqlite3VdbeAddOp1(v, OP_MustBeInt, iLimit);
91368      VdbeComment((v, "LIMIT counter"));
91369      sqlite3VdbeAddOp2(v, OP_IfZero, iLimit, iBreak);
91370    }
91371    if( p->pOffset ){
91372      p->iOffset = iOffset = ++pParse->nMem;
91373      pParse->nMem++;   /* Allocate an extra register for limit+offset */
91374      sqlite3ExprCode(pParse, p->pOffset, iOffset);
91375      sqlite3VdbeAddOp1(v, OP_MustBeInt, iOffset);
91376      VdbeComment((v, "OFFSET counter"));
91377      addr1 = sqlite3VdbeAddOp1(v, OP_IfPos, iOffset);
91378      sqlite3VdbeAddOp2(v, OP_Integer, 0, iOffset);
91379      sqlite3VdbeJumpHere(v, addr1);
91380      sqlite3VdbeAddOp3(v, OP_Add, iLimit, iOffset, iOffset+1);
91381      VdbeComment((v, "LIMIT+OFFSET"));
91382      addr1 = sqlite3VdbeAddOp1(v, OP_IfPos, iLimit);
91383      sqlite3VdbeAddOp2(v, OP_Integer, -1, iOffset+1);
91384      sqlite3VdbeJumpHere(v, addr1);
91385    }
91386  }
91387}
91388
91389#ifndef SQLITE_OMIT_COMPOUND_SELECT
91390/*
91391** Return the appropriate collating sequence for the iCol-th column of
91392** the result set for the compound-select statement "p".  Return NULL if
91393** the column has no default collating sequence.
91394**
91395** The collating sequence for the compound select is taken from the
91396** left-most term of the select that has a collating sequence.
91397*/
91398static CollSeq *multiSelectCollSeq(Parse *pParse, Select *p, int iCol){
91399  CollSeq *pRet;
91400  if( p->pPrior ){
91401    pRet = multiSelectCollSeq(pParse, p->pPrior, iCol);
91402  }else{
91403    pRet = 0;
91404  }
91405  assert( iCol>=0 );
91406  if( pRet==0 && iCol<p->pEList->nExpr ){
91407    pRet = sqlite3ExprCollSeq(pParse, p->pEList->a[iCol].pExpr);
91408  }
91409  return pRet;
91410}
91411#endif /* SQLITE_OMIT_COMPOUND_SELECT */
91412
91413/* Forward reference */
91414static int multiSelectOrderBy(
91415  Parse *pParse,        /* Parsing context */
91416  Select *p,            /* The right-most of SELECTs to be coded */
91417  SelectDest *pDest     /* What to do with query results */
91418);
91419
91420
91421#ifndef SQLITE_OMIT_COMPOUND_SELECT
91422/*
91423** This routine is called to process a compound query form from
91424** two or more separate queries using UNION, UNION ALL, EXCEPT, or
91425** INTERSECT
91426**
91427** "p" points to the right-most of the two queries.  the query on the
91428** left is p->pPrior.  The left query could also be a compound query
91429** in which case this routine will be called recursively.
91430**
91431** The results of the total query are to be written into a destination
91432** of type eDest with parameter iParm.
91433**
91434** Example 1:  Consider a three-way compound SQL statement.
91435**
91436**     SELECT a FROM t1 UNION SELECT b FROM t2 UNION SELECT c FROM t3
91437**
91438** This statement is parsed up as follows:
91439**
91440**     SELECT c FROM t3
91441**      |
91442**      `----->  SELECT b FROM t2
91443**                |
91444**                `------>  SELECT a FROM t1
91445**
91446** The arrows in the diagram above represent the Select.pPrior pointer.
91447** So if this routine is called with p equal to the t3 query, then
91448** pPrior will be the t2 query.  p->op will be TK_UNION in this case.
91449**
91450** Notice that because of the way SQLite parses compound SELECTs, the
91451** individual selects always group from left to right.
91452*/
91453static int multiSelect(
91454  Parse *pParse,        /* Parsing context */
91455  Select *p,            /* The right-most of SELECTs to be coded */
91456  SelectDest *pDest     /* What to do with query results */
91457){
91458  int rc = SQLITE_OK;   /* Success code from a subroutine */
91459  Select *pPrior;       /* Another SELECT immediately to our left */
91460  Vdbe *v;              /* Generate code to this VDBE */
91461  SelectDest dest;      /* Alternative data destination */
91462  Select *pDelete = 0;  /* Chain of simple selects to delete */
91463  sqlite3 *db;          /* Database connection */
91464#ifndef SQLITE_OMIT_EXPLAIN
91465  int iSub1;            /* EQP id of left-hand query */
91466  int iSub2;            /* EQP id of right-hand query */
91467#endif
91468
91469  /* Make sure there is no ORDER BY or LIMIT clause on prior SELECTs.  Only
91470  ** the last (right-most) SELECT in the series may have an ORDER BY or LIMIT.
91471  */
91472  assert( p && p->pPrior );  /* Calling function guarantees this much */
91473  db = pParse->db;
91474  pPrior = p->pPrior;
91475  assert( pPrior->pRightmost!=pPrior );
91476  assert( pPrior->pRightmost==p->pRightmost );
91477  dest = *pDest;
91478  if( pPrior->pOrderBy ){
91479    sqlite3ErrorMsg(pParse,"ORDER BY clause should come after %s not before",
91480      selectOpName(p->op));
91481    rc = 1;
91482    goto multi_select_end;
91483  }
91484  if( pPrior->pLimit ){
91485    sqlite3ErrorMsg(pParse,"LIMIT clause should come after %s not before",
91486      selectOpName(p->op));
91487    rc = 1;
91488    goto multi_select_end;
91489  }
91490
91491  v = sqlite3GetVdbe(pParse);
91492  assert( v!=0 );  /* The VDBE already created by calling function */
91493
91494  /* Create the destination temporary table if necessary
91495  */
91496  if( dest.eDest==SRT_EphemTab ){
91497    assert( p->pEList );
91498    sqlite3VdbeAddOp2(v, OP_OpenEphemeral, dest.iParm, p->pEList->nExpr);
91499    sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
91500    dest.eDest = SRT_Table;
91501  }
91502
91503  /* Make sure all SELECTs in the statement have the same number of elements
91504  ** in their result sets.
91505  */
91506  assert( p->pEList && pPrior->pEList );
91507  if( p->pEList->nExpr!=pPrior->pEList->nExpr ){
91508    sqlite3ErrorMsg(pParse, "SELECTs to the left and right of %s"
91509      " do not have the same number of result columns", selectOpName(p->op));
91510    rc = 1;
91511    goto multi_select_end;
91512  }
91513
91514  /* Compound SELECTs that have an ORDER BY clause are handled separately.
91515  */
91516  if( p->pOrderBy ){
91517    return multiSelectOrderBy(pParse, p, pDest);
91518  }
91519
91520  /* Generate code for the left and right SELECT statements.
91521  */
91522  switch( p->op ){
91523    case TK_ALL: {
91524      int addr = 0;
91525      int nLimit;
91526      assert( !pPrior->pLimit );
91527      pPrior->pLimit = p->pLimit;
91528      pPrior->pOffset = p->pOffset;
91529      explainSetInteger(iSub1, pParse->iNextSelectId);
91530      rc = sqlite3Select(pParse, pPrior, &dest);
91531      p->pLimit = 0;
91532      p->pOffset = 0;
91533      if( rc ){
91534        goto multi_select_end;
91535      }
91536      p->pPrior = 0;
91537      p->iLimit = pPrior->iLimit;
91538      p->iOffset = pPrior->iOffset;
91539      if( p->iLimit ){
91540        addr = sqlite3VdbeAddOp1(v, OP_IfZero, p->iLimit);
91541        VdbeComment((v, "Jump ahead if LIMIT reached"));
91542      }
91543      explainSetInteger(iSub2, pParse->iNextSelectId);
91544      rc = sqlite3Select(pParse, p, &dest);
91545      testcase( rc!=SQLITE_OK );
91546      pDelete = p->pPrior;
91547      p->pPrior = pPrior;
91548      p->nSelectRow += pPrior->nSelectRow;
91549      if( pPrior->pLimit
91550       && sqlite3ExprIsInteger(pPrior->pLimit, &nLimit)
91551       && p->nSelectRow > (double)nLimit
91552      ){
91553        p->nSelectRow = (double)nLimit;
91554      }
91555      if( addr ){
91556        sqlite3VdbeJumpHere(v, addr);
91557      }
91558      break;
91559    }
91560    case TK_EXCEPT:
91561    case TK_UNION: {
91562      int unionTab;    /* Cursor number of the temporary table holding result */
91563      u8 op = 0;       /* One of the SRT_ operations to apply to self */
91564      int priorOp;     /* The SRT_ operation to apply to prior selects */
91565      Expr *pLimit, *pOffset; /* Saved values of p->nLimit and p->nOffset */
91566      int addr;
91567      SelectDest uniondest;
91568
91569      testcase( p->op==TK_EXCEPT );
91570      testcase( p->op==TK_UNION );
91571      priorOp = SRT_Union;
91572      if( dest.eDest==priorOp && ALWAYS(!p->pLimit &&!p->pOffset) ){
91573        /* We can reuse a temporary table generated by a SELECT to our
91574        ** right.
91575        */
91576        assert( p->pRightmost!=p );  /* Can only happen for leftward elements
91577                                     ** of a 3-way or more compound */
91578        assert( p->pLimit==0 );      /* Not allowed on leftward elements */
91579        assert( p->pOffset==0 );     /* Not allowed on leftward elements */
91580        unionTab = dest.iParm;
91581      }else{
91582        /* We will need to create our own temporary table to hold the
91583        ** intermediate results.
91584        */
91585        unionTab = pParse->nTab++;
91586        assert( p->pOrderBy==0 );
91587        addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, unionTab, 0);
91588        assert( p->addrOpenEphm[0] == -1 );
91589        p->addrOpenEphm[0] = addr;
91590        p->pRightmost->selFlags |= SF_UsesEphemeral;
91591        assert( p->pEList );
91592      }
91593
91594      /* Code the SELECT statements to our left
91595      */
91596      assert( !pPrior->pOrderBy );
91597      sqlite3SelectDestInit(&uniondest, priorOp, unionTab);
91598      explainSetInteger(iSub1, pParse->iNextSelectId);
91599      rc = sqlite3Select(pParse, pPrior, &uniondest);
91600      if( rc ){
91601        goto multi_select_end;
91602      }
91603
91604      /* Code the current SELECT statement
91605      */
91606      if( p->op==TK_EXCEPT ){
91607        op = SRT_Except;
91608      }else{
91609        assert( p->op==TK_UNION );
91610        op = SRT_Union;
91611      }
91612      p->pPrior = 0;
91613      pLimit = p->pLimit;
91614      p->pLimit = 0;
91615      pOffset = p->pOffset;
91616      p->pOffset = 0;
91617      uniondest.eDest = op;
91618      explainSetInteger(iSub2, pParse->iNextSelectId);
91619      rc = sqlite3Select(pParse, p, &uniondest);
91620      testcase( rc!=SQLITE_OK );
91621      /* Query flattening in sqlite3Select() might refill p->pOrderBy.
91622      ** Be sure to delete p->pOrderBy, therefore, to avoid a memory leak. */
91623      sqlite3ExprListDelete(db, p->pOrderBy);
91624      pDelete = p->pPrior;
91625      p->pPrior = pPrior;
91626      p->pOrderBy = 0;
91627      if( p->op==TK_UNION ) p->nSelectRow += pPrior->nSelectRow;
91628      sqlite3ExprDelete(db, p->pLimit);
91629      p->pLimit = pLimit;
91630      p->pOffset = pOffset;
91631      p->iLimit = 0;
91632      p->iOffset = 0;
91633
91634      /* Convert the data in the temporary table into whatever form
91635      ** it is that we currently need.
91636      */
91637      assert( unionTab==dest.iParm || dest.eDest!=priorOp );
91638      if( dest.eDest!=priorOp ){
91639        int iCont, iBreak, iStart;
91640        assert( p->pEList );
91641        if( dest.eDest==SRT_Output ){
91642          Select *pFirst = p;
91643          while( pFirst->pPrior ) pFirst = pFirst->pPrior;
91644          generateColumnNames(pParse, 0, pFirst->pEList);
91645        }
91646        iBreak = sqlite3VdbeMakeLabel(v);
91647        iCont = sqlite3VdbeMakeLabel(v);
91648        computeLimitRegisters(pParse, p, iBreak);
91649        sqlite3VdbeAddOp2(v, OP_Rewind, unionTab, iBreak);
91650        iStart = sqlite3VdbeCurrentAddr(v);
91651        selectInnerLoop(pParse, p, p->pEList, unionTab, p->pEList->nExpr,
91652                        0, -1, &dest, iCont, iBreak);
91653        sqlite3VdbeResolveLabel(v, iCont);
91654        sqlite3VdbeAddOp2(v, OP_Next, unionTab, iStart);
91655        sqlite3VdbeResolveLabel(v, iBreak);
91656        sqlite3VdbeAddOp2(v, OP_Close, unionTab, 0);
91657      }
91658      break;
91659    }
91660    default: assert( p->op==TK_INTERSECT ); {
91661      int tab1, tab2;
91662      int iCont, iBreak, iStart;
91663      Expr *pLimit, *pOffset;
91664      int addr;
91665      SelectDest intersectdest;
91666      int r1;
91667
91668      /* INTERSECT is different from the others since it requires
91669      ** two temporary tables.  Hence it has its own case.  Begin
91670      ** by allocating the tables we will need.
91671      */
91672      tab1 = pParse->nTab++;
91673      tab2 = pParse->nTab++;
91674      assert( p->pOrderBy==0 );
91675
91676      addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab1, 0);
91677      assert( p->addrOpenEphm[0] == -1 );
91678      p->addrOpenEphm[0] = addr;
91679      p->pRightmost->selFlags |= SF_UsesEphemeral;
91680      assert( p->pEList );
91681
91682      /* Code the SELECTs to our left into temporary table "tab1".
91683      */
91684      sqlite3SelectDestInit(&intersectdest, SRT_Union, tab1);
91685      explainSetInteger(iSub1, pParse->iNextSelectId);
91686      rc = sqlite3Select(pParse, pPrior, &intersectdest);
91687      if( rc ){
91688        goto multi_select_end;
91689      }
91690
91691      /* Code the current SELECT into temporary table "tab2"
91692      */
91693      addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab2, 0);
91694      assert( p->addrOpenEphm[1] == -1 );
91695      p->addrOpenEphm[1] = addr;
91696      p->pPrior = 0;
91697      pLimit = p->pLimit;
91698      p->pLimit = 0;
91699      pOffset = p->pOffset;
91700      p->pOffset = 0;
91701      intersectdest.iParm = tab2;
91702      explainSetInteger(iSub2, pParse->iNextSelectId);
91703      rc = sqlite3Select(pParse, p, &intersectdest);
91704      testcase( rc!=SQLITE_OK );
91705      pDelete = p->pPrior;
91706      p->pPrior = pPrior;
91707      if( p->nSelectRow>pPrior->nSelectRow ) p->nSelectRow = pPrior->nSelectRow;
91708      sqlite3ExprDelete(db, p->pLimit);
91709      p->pLimit = pLimit;
91710      p->pOffset = pOffset;
91711
91712      /* Generate code to take the intersection of the two temporary
91713      ** tables.
91714      */
91715      assert( p->pEList );
91716      if( dest.eDest==SRT_Output ){
91717        Select *pFirst = p;
91718        while( pFirst->pPrior ) pFirst = pFirst->pPrior;
91719        generateColumnNames(pParse, 0, pFirst->pEList);
91720      }
91721      iBreak = sqlite3VdbeMakeLabel(v);
91722      iCont = sqlite3VdbeMakeLabel(v);
91723      computeLimitRegisters(pParse, p, iBreak);
91724      sqlite3VdbeAddOp2(v, OP_Rewind, tab1, iBreak);
91725      r1 = sqlite3GetTempReg(pParse);
91726      iStart = sqlite3VdbeAddOp2(v, OP_RowKey, tab1, r1);
91727      sqlite3VdbeAddOp4Int(v, OP_NotFound, tab2, iCont, r1, 0);
91728      sqlite3ReleaseTempReg(pParse, r1);
91729      selectInnerLoop(pParse, p, p->pEList, tab1, p->pEList->nExpr,
91730                      0, -1, &dest, iCont, iBreak);
91731      sqlite3VdbeResolveLabel(v, iCont);
91732      sqlite3VdbeAddOp2(v, OP_Next, tab1, iStart);
91733      sqlite3VdbeResolveLabel(v, iBreak);
91734      sqlite3VdbeAddOp2(v, OP_Close, tab2, 0);
91735      sqlite3VdbeAddOp2(v, OP_Close, tab1, 0);
91736      break;
91737    }
91738  }
91739
91740  explainComposite(pParse, p->op, iSub1, iSub2, p->op!=TK_ALL);
91741
91742  /* Compute collating sequences used by
91743  ** temporary tables needed to implement the compound select.
91744  ** Attach the KeyInfo structure to all temporary tables.
91745  **
91746  ** This section is run by the right-most SELECT statement only.
91747  ** SELECT statements to the left always skip this part.  The right-most
91748  ** SELECT might also skip this part if it has no ORDER BY clause and
91749  ** no temp tables are required.
91750  */
91751  if( p->selFlags & SF_UsesEphemeral ){
91752    int i;                        /* Loop counter */
91753    KeyInfo *pKeyInfo;            /* Collating sequence for the result set */
91754    Select *pLoop;                /* For looping through SELECT statements */
91755    CollSeq **apColl;             /* For looping through pKeyInfo->aColl[] */
91756    int nCol;                     /* Number of columns in result set */
91757
91758    assert( p->pRightmost==p );
91759    nCol = p->pEList->nExpr;
91760    pKeyInfo = sqlite3DbMallocZero(db,
91761                       sizeof(*pKeyInfo)+nCol*(sizeof(CollSeq*) + 1));
91762    if( !pKeyInfo ){
91763      rc = SQLITE_NOMEM;
91764      goto multi_select_end;
91765    }
91766
91767    pKeyInfo->enc = ENC(db);
91768    pKeyInfo->nField = (u16)nCol;
91769
91770    for(i=0, apColl=pKeyInfo->aColl; i<nCol; i++, apColl++){
91771      *apColl = multiSelectCollSeq(pParse, p, i);
91772      if( 0==*apColl ){
91773        *apColl = db->pDfltColl;
91774      }
91775    }
91776
91777    for(pLoop=p; pLoop; pLoop=pLoop->pPrior){
91778      for(i=0; i<2; i++){
91779        int addr = pLoop->addrOpenEphm[i];
91780        if( addr<0 ){
91781          /* If [0] is unused then [1] is also unused.  So we can
91782          ** always safely abort as soon as the first unused slot is found */
91783          assert( pLoop->addrOpenEphm[1]<0 );
91784          break;
91785        }
91786        sqlite3VdbeChangeP2(v, addr, nCol);
91787        sqlite3VdbeChangeP4(v, addr, (char*)pKeyInfo, P4_KEYINFO);
91788        pLoop->addrOpenEphm[i] = -1;
91789      }
91790    }
91791    sqlite3DbFree(db, pKeyInfo);
91792  }
91793
91794multi_select_end:
91795  pDest->iMem = dest.iMem;
91796  pDest->nMem = dest.nMem;
91797  sqlite3SelectDelete(db, pDelete);
91798  return rc;
91799}
91800#endif /* SQLITE_OMIT_COMPOUND_SELECT */
91801
91802/*
91803** Code an output subroutine for a coroutine implementation of a
91804** SELECT statment.
91805**
91806** The data to be output is contained in pIn->iMem.  There are
91807** pIn->nMem columns to be output.  pDest is where the output should
91808** be sent.
91809**
91810** regReturn is the number of the register holding the subroutine
91811** return address.
91812**
91813** If regPrev>0 then it is the first register in a vector that
91814** records the previous output.  mem[regPrev] is a flag that is false
91815** if there has been no previous output.  If regPrev>0 then code is
91816** generated to suppress duplicates.  pKeyInfo is used for comparing
91817** keys.
91818**
91819** If the LIMIT found in p->iLimit is reached, jump immediately to
91820** iBreak.
91821*/
91822static int generateOutputSubroutine(
91823  Parse *pParse,          /* Parsing context */
91824  Select *p,              /* The SELECT statement */
91825  SelectDest *pIn,        /* Coroutine supplying data */
91826  SelectDest *pDest,      /* Where to send the data */
91827  int regReturn,          /* The return address register */
91828  int regPrev,            /* Previous result register.  No uniqueness if 0 */
91829  KeyInfo *pKeyInfo,      /* For comparing with previous entry */
91830  int p4type,             /* The p4 type for pKeyInfo */
91831  int iBreak              /* Jump here if we hit the LIMIT */
91832){
91833  Vdbe *v = pParse->pVdbe;
91834  int iContinue;
91835  int addr;
91836
91837  addr = sqlite3VdbeCurrentAddr(v);
91838  iContinue = sqlite3VdbeMakeLabel(v);
91839
91840  /* Suppress duplicates for UNION, EXCEPT, and INTERSECT
91841  */
91842  if( regPrev ){
91843    int j1, j2;
91844    j1 = sqlite3VdbeAddOp1(v, OP_IfNot, regPrev);
91845    j2 = sqlite3VdbeAddOp4(v, OP_Compare, pIn->iMem, regPrev+1, pIn->nMem,
91846                              (char*)pKeyInfo, p4type);
91847    sqlite3VdbeAddOp3(v, OP_Jump, j2+2, iContinue, j2+2);
91848    sqlite3VdbeJumpHere(v, j1);
91849    sqlite3ExprCodeCopy(pParse, pIn->iMem, regPrev+1, pIn->nMem);
91850    sqlite3VdbeAddOp2(v, OP_Integer, 1, regPrev);
91851  }
91852  if( pParse->db->mallocFailed ) return 0;
91853
91854  /* Suppress the the first OFFSET entries if there is an OFFSET clause
91855  */
91856  codeOffset(v, p, iContinue);
91857
91858  switch( pDest->eDest ){
91859    /* Store the result as data using a unique key.
91860    */
91861    case SRT_Table:
91862    case SRT_EphemTab: {
91863      int r1 = sqlite3GetTempReg(pParse);
91864      int r2 = sqlite3GetTempReg(pParse);
91865      testcase( pDest->eDest==SRT_Table );
91866      testcase( pDest->eDest==SRT_EphemTab );
91867      sqlite3VdbeAddOp3(v, OP_MakeRecord, pIn->iMem, pIn->nMem, r1);
91868      sqlite3VdbeAddOp2(v, OP_NewRowid, pDest->iParm, r2);
91869      sqlite3VdbeAddOp3(v, OP_Insert, pDest->iParm, r1, r2);
91870      sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
91871      sqlite3ReleaseTempReg(pParse, r2);
91872      sqlite3ReleaseTempReg(pParse, r1);
91873      break;
91874    }
91875
91876#ifndef SQLITE_OMIT_SUBQUERY
91877    /* If we are creating a set for an "expr IN (SELECT ...)" construct,
91878    ** then there should be a single item on the stack.  Write this
91879    ** item into the set table with bogus data.
91880    */
91881    case SRT_Set: {
91882      int r1;
91883      assert( pIn->nMem==1 );
91884      p->affinity =
91885         sqlite3CompareAffinity(p->pEList->a[0].pExpr, pDest->affinity);
91886      r1 = sqlite3GetTempReg(pParse);
91887      sqlite3VdbeAddOp4(v, OP_MakeRecord, pIn->iMem, 1, r1, &p->affinity, 1);
91888      sqlite3ExprCacheAffinityChange(pParse, pIn->iMem, 1);
91889      sqlite3VdbeAddOp2(v, OP_IdxInsert, pDest->iParm, r1);
91890      sqlite3ReleaseTempReg(pParse, r1);
91891      break;
91892    }
91893
91894#if 0  /* Never occurs on an ORDER BY query */
91895    /* If any row exist in the result set, record that fact and abort.
91896    */
91897    case SRT_Exists: {
91898      sqlite3VdbeAddOp2(v, OP_Integer, 1, pDest->iParm);
91899      /* The LIMIT clause will terminate the loop for us */
91900      break;
91901    }
91902#endif
91903
91904    /* If this is a scalar select that is part of an expression, then
91905    ** store the results in the appropriate memory cell and break out
91906    ** of the scan loop.
91907    */
91908    case SRT_Mem: {
91909      assert( pIn->nMem==1 );
91910      sqlite3ExprCodeMove(pParse, pIn->iMem, pDest->iParm, 1);
91911      /* The LIMIT clause will jump out of the loop for us */
91912      break;
91913    }
91914#endif /* #ifndef SQLITE_OMIT_SUBQUERY */
91915
91916    /* The results are stored in a sequence of registers
91917    ** starting at pDest->iMem.  Then the co-routine yields.
91918    */
91919    case SRT_Coroutine: {
91920      if( pDest->iMem==0 ){
91921        pDest->iMem = sqlite3GetTempRange(pParse, pIn->nMem);
91922        pDest->nMem = pIn->nMem;
91923      }
91924      sqlite3ExprCodeMove(pParse, pIn->iMem, pDest->iMem, pDest->nMem);
91925      sqlite3VdbeAddOp1(v, OP_Yield, pDest->iParm);
91926      break;
91927    }
91928
91929    /* If none of the above, then the result destination must be
91930    ** SRT_Output.  This routine is never called with any other
91931    ** destination other than the ones handled above or SRT_Output.
91932    **
91933    ** For SRT_Output, results are stored in a sequence of registers.
91934    ** Then the OP_ResultRow opcode is used to cause sqlite3_step() to
91935    ** return the next row of result.
91936    */
91937    default: {
91938      assert( pDest->eDest==SRT_Output );
91939      sqlite3VdbeAddOp2(v, OP_ResultRow, pIn->iMem, pIn->nMem);
91940      sqlite3ExprCacheAffinityChange(pParse, pIn->iMem, pIn->nMem);
91941      break;
91942    }
91943  }
91944
91945  /* Jump to the end of the loop if the LIMIT is reached.
91946  */
91947  if( p->iLimit ){
91948    sqlite3VdbeAddOp3(v, OP_IfZero, p->iLimit, iBreak, -1);
91949  }
91950
91951  /* Generate the subroutine return
91952  */
91953  sqlite3VdbeResolveLabel(v, iContinue);
91954  sqlite3VdbeAddOp1(v, OP_Return, regReturn);
91955
91956  return addr;
91957}
91958
91959/*
91960** Alternative compound select code generator for cases when there
91961** is an ORDER BY clause.
91962**
91963** We assume a query of the following form:
91964**
91965**      <selectA>  <operator>  <selectB>  ORDER BY <orderbylist>
91966**
91967** <operator> is one of UNION ALL, UNION, EXCEPT, or INTERSECT.  The idea
91968** is to code both <selectA> and <selectB> with the ORDER BY clause as
91969** co-routines.  Then run the co-routines in parallel and merge the results
91970** into the output.  In addition to the two coroutines (called selectA and
91971** selectB) there are 7 subroutines:
91972**
91973**    outA:    Move the output of the selectA coroutine into the output
91974**             of the compound query.
91975**
91976**    outB:    Move the output of the selectB coroutine into the output
91977**             of the compound query.  (Only generated for UNION and
91978**             UNION ALL.  EXCEPT and INSERTSECT never output a row that
91979**             appears only in B.)
91980**
91981**    AltB:    Called when there is data from both coroutines and A<B.
91982**
91983**    AeqB:    Called when there is data from both coroutines and A==B.
91984**
91985**    AgtB:    Called when there is data from both coroutines and A>B.
91986**
91987**    EofA:    Called when data is exhausted from selectA.
91988**
91989**    EofB:    Called when data is exhausted from selectB.
91990**
91991** The implementation of the latter five subroutines depend on which
91992** <operator> is used:
91993**
91994**
91995**             UNION ALL         UNION            EXCEPT          INTERSECT
91996**          -------------  -----------------  --------------  -----------------
91997**   AltB:   outA, nextA      outA, nextA       outA, nextA         nextA
91998**
91999**   AeqB:   outA, nextA         nextA             nextA         outA, nextA
92000**
92001**   AgtB:   outB, nextB      outB, nextB          nextB            nextB
92002**
92003**   EofA:   outB, nextB      outB, nextB          halt             halt
92004**
92005**   EofB:   outA, nextA      outA, nextA       outA, nextA         halt
92006**
92007** In the AltB, AeqB, and AgtB subroutines, an EOF on A following nextA
92008** causes an immediate jump to EofA and an EOF on B following nextB causes
92009** an immediate jump to EofB.  Within EofA and EofB, and EOF on entry or
92010** following nextX causes a jump to the end of the select processing.
92011**
92012** Duplicate removal in the UNION, EXCEPT, and INTERSECT cases is handled
92013** within the output subroutine.  The regPrev register set holds the previously
92014** output value.  A comparison is made against this value and the output
92015** is skipped if the next results would be the same as the previous.
92016**
92017** The implementation plan is to implement the two coroutines and seven
92018** subroutines first, then put the control logic at the bottom.  Like this:
92019**
92020**          goto Init
92021**     coA: coroutine for left query (A)
92022**     coB: coroutine for right query (B)
92023**    outA: output one row of A
92024**    outB: output one row of B (UNION and UNION ALL only)
92025**    EofA: ...
92026**    EofB: ...
92027**    AltB: ...
92028**    AeqB: ...
92029**    AgtB: ...
92030**    Init: initialize coroutine registers
92031**          yield coA
92032**          if eof(A) goto EofA
92033**          yield coB
92034**          if eof(B) goto EofB
92035**    Cmpr: Compare A, B
92036**          Jump AltB, AeqB, AgtB
92037**     End: ...
92038**
92039** We call AltB, AeqB, AgtB, EofA, and EofB "subroutines" but they are not
92040** actually called using Gosub and they do not Return.  EofA and EofB loop
92041** until all data is exhausted then jump to the "end" labe.  AltB, AeqB,
92042** and AgtB jump to either L2 or to one of EofA or EofB.
92043*/
92044#ifndef SQLITE_OMIT_COMPOUND_SELECT
92045static int multiSelectOrderBy(
92046  Parse *pParse,        /* Parsing context */
92047  Select *p,            /* The right-most of SELECTs to be coded */
92048  SelectDest *pDest     /* What to do with query results */
92049){
92050  int i, j;             /* Loop counters */
92051  Select *pPrior;       /* Another SELECT immediately to our left */
92052  Vdbe *v;              /* Generate code to this VDBE */
92053  SelectDest destA;     /* Destination for coroutine A */
92054  SelectDest destB;     /* Destination for coroutine B */
92055  int regAddrA;         /* Address register for select-A coroutine */
92056  int regEofA;          /* Flag to indicate when select-A is complete */
92057  int regAddrB;         /* Address register for select-B coroutine */
92058  int regEofB;          /* Flag to indicate when select-B is complete */
92059  int addrSelectA;      /* Address of the select-A coroutine */
92060  int addrSelectB;      /* Address of the select-B coroutine */
92061  int regOutA;          /* Address register for the output-A subroutine */
92062  int regOutB;          /* Address register for the output-B subroutine */
92063  int addrOutA;         /* Address of the output-A subroutine */
92064  int addrOutB = 0;     /* Address of the output-B subroutine */
92065  int addrEofA;         /* Address of the select-A-exhausted subroutine */
92066  int addrEofB;         /* Address of the select-B-exhausted subroutine */
92067  int addrAltB;         /* Address of the A<B subroutine */
92068  int addrAeqB;         /* Address of the A==B subroutine */
92069  int addrAgtB;         /* Address of the A>B subroutine */
92070  int regLimitA;        /* Limit register for select-A */
92071  int regLimitB;        /* Limit register for select-A */
92072  int regPrev;          /* A range of registers to hold previous output */
92073  int savedLimit;       /* Saved value of p->iLimit */
92074  int savedOffset;      /* Saved value of p->iOffset */
92075  int labelCmpr;        /* Label for the start of the merge algorithm */
92076  int labelEnd;         /* Label for the end of the overall SELECT stmt */
92077  int j1;               /* Jump instructions that get retargetted */
92078  int op;               /* One of TK_ALL, TK_UNION, TK_EXCEPT, TK_INTERSECT */
92079  KeyInfo *pKeyDup = 0; /* Comparison information for duplicate removal */
92080  KeyInfo *pKeyMerge;   /* Comparison information for merging rows */
92081  sqlite3 *db;          /* Database connection */
92082  ExprList *pOrderBy;   /* The ORDER BY clause */
92083  int nOrderBy;         /* Number of terms in the ORDER BY clause */
92084  int *aPermute;        /* Mapping from ORDER BY terms to result set columns */
92085#ifndef SQLITE_OMIT_EXPLAIN
92086  int iSub1;            /* EQP id of left-hand query */
92087  int iSub2;            /* EQP id of right-hand query */
92088#endif
92089
92090  assert( p->pOrderBy!=0 );
92091  assert( pKeyDup==0 ); /* "Managed" code needs this.  Ticket #3382. */
92092  db = pParse->db;
92093  v = pParse->pVdbe;
92094  assert( v!=0 );       /* Already thrown the error if VDBE alloc failed */
92095  labelEnd = sqlite3VdbeMakeLabel(v);
92096  labelCmpr = sqlite3VdbeMakeLabel(v);
92097
92098
92099  /* Patch up the ORDER BY clause
92100  */
92101  op = p->op;
92102  pPrior = p->pPrior;
92103  assert( pPrior->pOrderBy==0 );
92104  pOrderBy = p->pOrderBy;
92105  assert( pOrderBy );
92106  nOrderBy = pOrderBy->nExpr;
92107
92108  /* For operators other than UNION ALL we have to make sure that
92109  ** the ORDER BY clause covers every term of the result set.  Add
92110  ** terms to the ORDER BY clause as necessary.
92111  */
92112  if( op!=TK_ALL ){
92113    for(i=1; db->mallocFailed==0 && i<=p->pEList->nExpr; i++){
92114      struct ExprList_item *pItem;
92115      for(j=0, pItem=pOrderBy->a; j<nOrderBy; j++, pItem++){
92116        assert( pItem->iCol>0 );
92117        if( pItem->iCol==i ) break;
92118      }
92119      if( j==nOrderBy ){
92120        Expr *pNew = sqlite3Expr(db, TK_INTEGER, 0);
92121        if( pNew==0 ) return SQLITE_NOMEM;
92122        pNew->flags |= EP_IntValue;
92123        pNew->u.iValue = i;
92124        pOrderBy = sqlite3ExprListAppend(pParse, pOrderBy, pNew);
92125        pOrderBy->a[nOrderBy++].iCol = (u16)i;
92126      }
92127    }
92128  }
92129
92130  /* Compute the comparison permutation and keyinfo that is used with
92131  ** the permutation used to determine if the next
92132  ** row of results comes from selectA or selectB.  Also add explicit
92133  ** collations to the ORDER BY clause terms so that when the subqueries
92134  ** to the right and the left are evaluated, they use the correct
92135  ** collation.
92136  */
92137  aPermute = sqlite3DbMallocRaw(db, sizeof(int)*nOrderBy);
92138  if( aPermute ){
92139    struct ExprList_item *pItem;
92140    for(i=0, pItem=pOrderBy->a; i<nOrderBy; i++, pItem++){
92141      assert( pItem->iCol>0  && pItem->iCol<=p->pEList->nExpr );
92142      aPermute[i] = pItem->iCol - 1;
92143    }
92144    pKeyMerge =
92145      sqlite3DbMallocRaw(db, sizeof(*pKeyMerge)+nOrderBy*(sizeof(CollSeq*)+1));
92146    if( pKeyMerge ){
92147      pKeyMerge->aSortOrder = (u8*)&pKeyMerge->aColl[nOrderBy];
92148      pKeyMerge->nField = (u16)nOrderBy;
92149      pKeyMerge->enc = ENC(db);
92150      for(i=0; i<nOrderBy; i++){
92151        CollSeq *pColl;
92152        Expr *pTerm = pOrderBy->a[i].pExpr;
92153        if( pTerm->flags & EP_ExpCollate ){
92154          pColl = pTerm->pColl;
92155        }else{
92156          pColl = multiSelectCollSeq(pParse, p, aPermute[i]);
92157          pTerm->flags |= EP_ExpCollate;
92158          pTerm->pColl = pColl;
92159        }
92160        pKeyMerge->aColl[i] = pColl;
92161        pKeyMerge->aSortOrder[i] = pOrderBy->a[i].sortOrder;
92162      }
92163    }
92164  }else{
92165    pKeyMerge = 0;
92166  }
92167
92168  /* Reattach the ORDER BY clause to the query.
92169  */
92170  p->pOrderBy = pOrderBy;
92171  pPrior->pOrderBy = sqlite3ExprListDup(pParse->db, pOrderBy, 0);
92172
92173  /* Allocate a range of temporary registers and the KeyInfo needed
92174  ** for the logic that removes duplicate result rows when the
92175  ** operator is UNION, EXCEPT, or INTERSECT (but not UNION ALL).
92176  */
92177  if( op==TK_ALL ){
92178    regPrev = 0;
92179  }else{
92180    int nExpr = p->pEList->nExpr;
92181    assert( nOrderBy>=nExpr || db->mallocFailed );
92182    regPrev = sqlite3GetTempRange(pParse, nExpr+1);
92183    sqlite3VdbeAddOp2(v, OP_Integer, 0, regPrev);
92184    pKeyDup = sqlite3DbMallocZero(db,
92185                  sizeof(*pKeyDup) + nExpr*(sizeof(CollSeq*)+1) );
92186    if( pKeyDup ){
92187      pKeyDup->aSortOrder = (u8*)&pKeyDup->aColl[nExpr];
92188      pKeyDup->nField = (u16)nExpr;
92189      pKeyDup->enc = ENC(db);
92190      for(i=0; i<nExpr; i++){
92191        pKeyDup->aColl[i] = multiSelectCollSeq(pParse, p, i);
92192        pKeyDup->aSortOrder[i] = 0;
92193      }
92194    }
92195  }
92196
92197  /* Separate the left and the right query from one another
92198  */
92199  p->pPrior = 0;
92200  sqlite3ResolveOrderGroupBy(pParse, p, p->pOrderBy, "ORDER");
92201  if( pPrior->pPrior==0 ){
92202    sqlite3ResolveOrderGroupBy(pParse, pPrior, pPrior->pOrderBy, "ORDER");
92203  }
92204
92205  /* Compute the limit registers */
92206  computeLimitRegisters(pParse, p, labelEnd);
92207  if( p->iLimit && op==TK_ALL ){
92208    regLimitA = ++pParse->nMem;
92209    regLimitB = ++pParse->nMem;
92210    sqlite3VdbeAddOp2(v, OP_Copy, p->iOffset ? p->iOffset+1 : p->iLimit,
92211                                  regLimitA);
92212    sqlite3VdbeAddOp2(v, OP_Copy, regLimitA, regLimitB);
92213  }else{
92214    regLimitA = regLimitB = 0;
92215  }
92216  sqlite3ExprDelete(db, p->pLimit);
92217  p->pLimit = 0;
92218  sqlite3ExprDelete(db, p->pOffset);
92219  p->pOffset = 0;
92220
92221  regAddrA = ++pParse->nMem;
92222  regEofA = ++pParse->nMem;
92223  regAddrB = ++pParse->nMem;
92224  regEofB = ++pParse->nMem;
92225  regOutA = ++pParse->nMem;
92226  regOutB = ++pParse->nMem;
92227  sqlite3SelectDestInit(&destA, SRT_Coroutine, regAddrA);
92228  sqlite3SelectDestInit(&destB, SRT_Coroutine, regAddrB);
92229
92230  /* Jump past the various subroutines and coroutines to the main
92231  ** merge loop
92232  */
92233  j1 = sqlite3VdbeAddOp0(v, OP_Goto);
92234  addrSelectA = sqlite3VdbeCurrentAddr(v);
92235
92236
92237  /* Generate a coroutine to evaluate the SELECT statement to the
92238  ** left of the compound operator - the "A" select.
92239  */
92240  VdbeNoopComment((v, "Begin coroutine for left SELECT"));
92241  pPrior->iLimit = regLimitA;
92242  explainSetInteger(iSub1, pParse->iNextSelectId);
92243  sqlite3Select(pParse, pPrior, &destA);
92244  sqlite3VdbeAddOp2(v, OP_Integer, 1, regEofA);
92245  sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
92246  VdbeNoopComment((v, "End coroutine for left SELECT"));
92247
92248  /* Generate a coroutine to evaluate the SELECT statement on
92249  ** the right - the "B" select
92250  */
92251  addrSelectB = sqlite3VdbeCurrentAddr(v);
92252  VdbeNoopComment((v, "Begin coroutine for right SELECT"));
92253  savedLimit = p->iLimit;
92254  savedOffset = p->iOffset;
92255  p->iLimit = regLimitB;
92256  p->iOffset = 0;
92257  explainSetInteger(iSub2, pParse->iNextSelectId);
92258  sqlite3Select(pParse, p, &destB);
92259  p->iLimit = savedLimit;
92260  p->iOffset = savedOffset;
92261  sqlite3VdbeAddOp2(v, OP_Integer, 1, regEofB);
92262  sqlite3VdbeAddOp1(v, OP_Yield, regAddrB);
92263  VdbeNoopComment((v, "End coroutine for right SELECT"));
92264
92265  /* Generate a subroutine that outputs the current row of the A
92266  ** select as the next output row of the compound select.
92267  */
92268  VdbeNoopComment((v, "Output routine for A"));
92269  addrOutA = generateOutputSubroutine(pParse,
92270                 p, &destA, pDest, regOutA,
92271                 regPrev, pKeyDup, P4_KEYINFO_HANDOFF, labelEnd);
92272
92273  /* Generate a subroutine that outputs the current row of the B
92274  ** select as the next output row of the compound select.
92275  */
92276  if( op==TK_ALL || op==TK_UNION ){
92277    VdbeNoopComment((v, "Output routine for B"));
92278    addrOutB = generateOutputSubroutine(pParse,
92279                 p, &destB, pDest, regOutB,
92280                 regPrev, pKeyDup, P4_KEYINFO_STATIC, labelEnd);
92281  }
92282
92283  /* Generate a subroutine to run when the results from select A
92284  ** are exhausted and only data in select B remains.
92285  */
92286  VdbeNoopComment((v, "eof-A subroutine"));
92287  if( op==TK_EXCEPT || op==TK_INTERSECT ){
92288    addrEofA = sqlite3VdbeAddOp2(v, OP_Goto, 0, labelEnd);
92289  }else{
92290    addrEofA = sqlite3VdbeAddOp2(v, OP_If, regEofB, labelEnd);
92291    sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
92292    sqlite3VdbeAddOp1(v, OP_Yield, regAddrB);
92293    sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEofA);
92294    p->nSelectRow += pPrior->nSelectRow;
92295  }
92296
92297  /* Generate a subroutine to run when the results from select B
92298  ** are exhausted and only data in select A remains.
92299  */
92300  if( op==TK_INTERSECT ){
92301    addrEofB = addrEofA;
92302    if( p->nSelectRow > pPrior->nSelectRow ) p->nSelectRow = pPrior->nSelectRow;
92303  }else{
92304    VdbeNoopComment((v, "eof-B subroutine"));
92305    addrEofB = sqlite3VdbeAddOp2(v, OP_If, regEofA, labelEnd);
92306    sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
92307    sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
92308    sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEofB);
92309  }
92310
92311  /* Generate code to handle the case of A<B
92312  */
92313  VdbeNoopComment((v, "A-lt-B subroutine"));
92314  addrAltB = sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
92315  sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
92316  sqlite3VdbeAddOp2(v, OP_If, regEofA, addrEofA);
92317  sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
92318
92319  /* Generate code to handle the case of A==B
92320  */
92321  if( op==TK_ALL ){
92322    addrAeqB = addrAltB;
92323  }else if( op==TK_INTERSECT ){
92324    addrAeqB = addrAltB;
92325    addrAltB++;
92326  }else{
92327    VdbeNoopComment((v, "A-eq-B subroutine"));
92328    addrAeqB =
92329    sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
92330    sqlite3VdbeAddOp2(v, OP_If, regEofA, addrEofA);
92331    sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
92332  }
92333
92334  /* Generate code to handle the case of A>B
92335  */
92336  VdbeNoopComment((v, "A-gt-B subroutine"));
92337  addrAgtB = sqlite3VdbeCurrentAddr(v);
92338  if( op==TK_ALL || op==TK_UNION ){
92339    sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
92340  }
92341  sqlite3VdbeAddOp1(v, OP_Yield, regAddrB);
92342  sqlite3VdbeAddOp2(v, OP_If, regEofB, addrEofB);
92343  sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
92344
92345  /* This code runs once to initialize everything.
92346  */
92347  sqlite3VdbeJumpHere(v, j1);
92348  sqlite3VdbeAddOp2(v, OP_Integer, 0, regEofA);
92349  sqlite3VdbeAddOp2(v, OP_Integer, 0, regEofB);
92350  sqlite3VdbeAddOp2(v, OP_Gosub, regAddrA, addrSelectA);
92351  sqlite3VdbeAddOp2(v, OP_Gosub, regAddrB, addrSelectB);
92352  sqlite3VdbeAddOp2(v, OP_If, regEofA, addrEofA);
92353  sqlite3VdbeAddOp2(v, OP_If, regEofB, addrEofB);
92354
92355  /* Implement the main merge loop
92356  */
92357  sqlite3VdbeResolveLabel(v, labelCmpr);
92358  sqlite3VdbeAddOp4(v, OP_Permutation, 0, 0, 0, (char*)aPermute, P4_INTARRAY);
92359  sqlite3VdbeAddOp4(v, OP_Compare, destA.iMem, destB.iMem, nOrderBy,
92360                         (char*)pKeyMerge, P4_KEYINFO_HANDOFF);
92361  sqlite3VdbeAddOp3(v, OP_Jump, addrAltB, addrAeqB, addrAgtB);
92362
92363  /* Release temporary registers
92364  */
92365  if( regPrev ){
92366    sqlite3ReleaseTempRange(pParse, regPrev, nOrderBy+1);
92367  }
92368
92369  /* Jump to the this point in order to terminate the query.
92370  */
92371  sqlite3VdbeResolveLabel(v, labelEnd);
92372
92373  /* Set the number of output columns
92374  */
92375  if( pDest->eDest==SRT_Output ){
92376    Select *pFirst = pPrior;
92377    while( pFirst->pPrior ) pFirst = pFirst->pPrior;
92378    generateColumnNames(pParse, 0, pFirst->pEList);
92379  }
92380
92381  /* Reassembly the compound query so that it will be freed correctly
92382  ** by the calling function */
92383  if( p->pPrior ){
92384    sqlite3SelectDelete(db, p->pPrior);
92385  }
92386  p->pPrior = pPrior;
92387
92388  /*** TBD:  Insert subroutine calls to close cursors on incomplete
92389  **** subqueries ****/
92390  explainComposite(pParse, p->op, iSub1, iSub2, 0);
92391  return SQLITE_OK;
92392}
92393#endif
92394
92395#if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
92396/* Forward Declarations */
92397static void substExprList(sqlite3*, ExprList*, int, ExprList*);
92398static void substSelect(sqlite3*, Select *, int, ExprList *);
92399
92400/*
92401** Scan through the expression pExpr.  Replace every reference to
92402** a column in table number iTable with a copy of the iColumn-th
92403** entry in pEList.  (But leave references to the ROWID column
92404** unchanged.)
92405**
92406** This routine is part of the flattening procedure.  A subquery
92407** whose result set is defined by pEList appears as entry in the
92408** FROM clause of a SELECT such that the VDBE cursor assigned to that
92409** FORM clause entry is iTable.  This routine make the necessary
92410** changes to pExpr so that it refers directly to the source table
92411** of the subquery rather the result set of the subquery.
92412*/
92413static Expr *substExpr(
92414  sqlite3 *db,        /* Report malloc errors to this connection */
92415  Expr *pExpr,        /* Expr in which substitution occurs */
92416  int iTable,         /* Table to be substituted */
92417  ExprList *pEList    /* Substitute expressions */
92418){
92419  if( pExpr==0 ) return 0;
92420  if( pExpr->op==TK_COLUMN && pExpr->iTable==iTable ){
92421    if( pExpr->iColumn<0 ){
92422      pExpr->op = TK_NULL;
92423    }else{
92424      Expr *pNew;
92425      assert( pEList!=0 && pExpr->iColumn<pEList->nExpr );
92426      assert( pExpr->pLeft==0 && pExpr->pRight==0 );
92427      pNew = sqlite3ExprDup(db, pEList->a[pExpr->iColumn].pExpr, 0);
92428      if( pNew && pExpr->pColl ){
92429        pNew->pColl = pExpr->pColl;
92430      }
92431      sqlite3ExprDelete(db, pExpr);
92432      pExpr = pNew;
92433    }
92434  }else{
92435    pExpr->pLeft = substExpr(db, pExpr->pLeft, iTable, pEList);
92436    pExpr->pRight = substExpr(db, pExpr->pRight, iTable, pEList);
92437    if( ExprHasProperty(pExpr, EP_xIsSelect) ){
92438      substSelect(db, pExpr->x.pSelect, iTable, pEList);
92439    }else{
92440      substExprList(db, pExpr->x.pList, iTable, pEList);
92441    }
92442  }
92443  return pExpr;
92444}
92445static void substExprList(
92446  sqlite3 *db,         /* Report malloc errors here */
92447  ExprList *pList,     /* List to scan and in which to make substitutes */
92448  int iTable,          /* Table to be substituted */
92449  ExprList *pEList     /* Substitute values */
92450){
92451  int i;
92452  if( pList==0 ) return;
92453  for(i=0; i<pList->nExpr; i++){
92454    pList->a[i].pExpr = substExpr(db, pList->a[i].pExpr, iTable, pEList);
92455  }
92456}
92457static void substSelect(
92458  sqlite3 *db,         /* Report malloc errors here */
92459  Select *p,           /* SELECT statement in which to make substitutions */
92460  int iTable,          /* Table to be replaced */
92461  ExprList *pEList     /* Substitute values */
92462){
92463  SrcList *pSrc;
92464  struct SrcList_item *pItem;
92465  int i;
92466  if( !p ) return;
92467  substExprList(db, p->pEList, iTable, pEList);
92468  substExprList(db, p->pGroupBy, iTable, pEList);
92469  substExprList(db, p->pOrderBy, iTable, pEList);
92470  p->pHaving = substExpr(db, p->pHaving, iTable, pEList);
92471  p->pWhere = substExpr(db, p->pWhere, iTable, pEList);
92472  substSelect(db, p->pPrior, iTable, pEList);
92473  pSrc = p->pSrc;
92474  assert( pSrc );  /* Even for (SELECT 1) we have: pSrc!=0 but pSrc->nSrc==0 */
92475  if( ALWAYS(pSrc) ){
92476    for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){
92477      substSelect(db, pItem->pSelect, iTable, pEList);
92478    }
92479  }
92480}
92481#endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
92482
92483#if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
92484/*
92485** This routine attempts to flatten subqueries in order to speed
92486** execution.  It returns 1 if it makes changes and 0 if no flattening
92487** occurs.
92488**
92489** To understand the concept of flattening, consider the following
92490** query:
92491**
92492**     SELECT a FROM (SELECT x+y AS a FROM t1 WHERE z<100) WHERE a>5
92493**
92494** The default way of implementing this query is to execute the
92495** subquery first and store the results in a temporary table, then
92496** run the outer query on that temporary table.  This requires two
92497** passes over the data.  Furthermore, because the temporary table
92498** has no indices, the WHERE clause on the outer query cannot be
92499** optimized.
92500**
92501** This routine attempts to rewrite queries such as the above into
92502** a single flat select, like this:
92503**
92504**     SELECT x+y AS a FROM t1 WHERE z<100 AND a>5
92505**
92506** The code generated for this simpification gives the same result
92507** but only has to scan the data once.  And because indices might
92508** exist on the table t1, a complete scan of the data might be
92509** avoided.
92510**
92511** Flattening is only attempted if all of the following are true:
92512**
92513**   (1)  The subquery and the outer query do not both use aggregates.
92514**
92515**   (2)  The subquery is not an aggregate or the outer query is not a join.
92516**
92517**   (3)  The subquery is not the right operand of a left outer join
92518**        (Originally ticket #306.  Strengthened by ticket #3300)
92519**
92520**   (4)  The subquery is not DISTINCT.
92521**
92522**  (**)  At one point restrictions (4) and (5) defined a subset of DISTINCT
92523**        sub-queries that were excluded from this optimization. Restriction
92524**        (4) has since been expanded to exclude all DISTINCT subqueries.
92525**
92526**   (6)  The subquery does not use aggregates or the outer query is not
92527**        DISTINCT.
92528**
92529**   (7)  The subquery has a FROM clause.
92530**
92531**   (8)  The subquery does not use LIMIT or the outer query is not a join.
92532**
92533**   (9)  The subquery does not use LIMIT or the outer query does not use
92534**        aggregates.
92535**
92536**  (10)  The subquery does not use aggregates or the outer query does not
92537**        use LIMIT.
92538**
92539**  (11)  The subquery and the outer query do not both have ORDER BY clauses.
92540**
92541**  (**)  Not implemented.  Subsumed into restriction (3).  Was previously
92542**        a separate restriction deriving from ticket #350.
92543**
92544**  (13)  The subquery and outer query do not both use LIMIT.
92545**
92546**  (14)  The subquery does not use OFFSET.
92547**
92548**  (15)  The outer query is not part of a compound select or the
92549**        subquery does not have a LIMIT clause.
92550**        (See ticket #2339 and ticket [02a8e81d44]).
92551**
92552**  (16)  The outer query is not an aggregate or the subquery does
92553**        not contain ORDER BY.  (Ticket #2942)  This used to not matter
92554**        until we introduced the group_concat() function.
92555**
92556**  (17)  The sub-query is not a compound select, or it is a UNION ALL
92557**        compound clause made up entirely of non-aggregate queries, and
92558**        the parent query:
92559**
92560**          * is not itself part of a compound select,
92561**          * is not an aggregate or DISTINCT query, and
92562**          * has no other tables or sub-selects in the FROM clause.
92563**
92564**        The parent and sub-query may contain WHERE clauses. Subject to
92565**        rules (11), (13) and (14), they may also contain ORDER BY,
92566**        LIMIT and OFFSET clauses.
92567**
92568**  (18)  If the sub-query is a compound select, then all terms of the
92569**        ORDER by clause of the parent must be simple references to
92570**        columns of the sub-query.
92571**
92572**  (19)  The subquery does not use LIMIT or the outer query does not
92573**        have a WHERE clause.
92574**
92575**  (20)  If the sub-query is a compound select, then it must not use
92576**        an ORDER BY clause.  Ticket #3773.  We could relax this constraint
92577**        somewhat by saying that the terms of the ORDER BY clause must
92578**        appear as unmodified result columns in the outer query.  But
92579**        have other optimizations in mind to deal with that case.
92580**
92581**  (21)  The subquery does not use LIMIT or the outer query is not
92582**        DISTINCT.  (See ticket [752e1646fc]).
92583**
92584** In this routine, the "p" parameter is a pointer to the outer query.
92585** The subquery is p->pSrc->a[iFrom].  isAgg is true if the outer query
92586** uses aggregates and subqueryIsAgg is true if the subquery uses aggregates.
92587**
92588** If flattening is not attempted, this routine is a no-op and returns 0.
92589** If flattening is attempted this routine returns 1.
92590**
92591** All of the expression analysis must occur on both the outer query and
92592** the subquery before this routine runs.
92593*/
92594static int flattenSubquery(
92595  Parse *pParse,       /* Parsing context */
92596  Select *p,           /* The parent or outer SELECT statement */
92597  int iFrom,           /* Index in p->pSrc->a[] of the inner subquery */
92598  int isAgg,           /* True if outer SELECT uses aggregate functions */
92599  int subqueryIsAgg    /* True if the subquery uses aggregate functions */
92600){
92601  const char *zSavedAuthContext = pParse->zAuthContext;
92602  Select *pParent;
92603  Select *pSub;       /* The inner query or "subquery" */
92604  Select *pSub1;      /* Pointer to the rightmost select in sub-query */
92605  SrcList *pSrc;      /* The FROM clause of the outer query */
92606  SrcList *pSubSrc;   /* The FROM clause of the subquery */
92607  ExprList *pList;    /* The result set of the outer query */
92608  int iParent;        /* VDBE cursor number of the pSub result set temp table */
92609  int i;              /* Loop counter */
92610  Expr *pWhere;                    /* The WHERE clause */
92611  struct SrcList_item *pSubitem;   /* The subquery */
92612  sqlite3 *db = pParse->db;
92613
92614  /* Check to see if flattening is permitted.  Return 0 if not.
92615  */
92616  assert( p!=0 );
92617  assert( p->pPrior==0 );  /* Unable to flatten compound queries */
92618  if( db->flags & SQLITE_QueryFlattener ) return 0;
92619  pSrc = p->pSrc;
92620  assert( pSrc && iFrom>=0 && iFrom<pSrc->nSrc );
92621  pSubitem = &pSrc->a[iFrom];
92622  iParent = pSubitem->iCursor;
92623  pSub = pSubitem->pSelect;
92624  assert( pSub!=0 );
92625  if( isAgg && subqueryIsAgg ) return 0;                 /* Restriction (1)  */
92626  if( subqueryIsAgg && pSrc->nSrc>1 ) return 0;          /* Restriction (2)  */
92627  pSubSrc = pSub->pSrc;
92628  assert( pSubSrc );
92629  /* Prior to version 3.1.2, when LIMIT and OFFSET had to be simple constants,
92630  ** not arbitrary expresssions, we allowed some combining of LIMIT and OFFSET
92631  ** because they could be computed at compile-time.  But when LIMIT and OFFSET
92632  ** became arbitrary expressions, we were forced to add restrictions (13)
92633  ** and (14). */
92634  if( pSub->pLimit && p->pLimit ) return 0;              /* Restriction (13) */
92635  if( pSub->pOffset ) return 0;                          /* Restriction (14) */
92636  if( p->pRightmost && pSub->pLimit ){
92637    return 0;                                            /* Restriction (15) */
92638  }
92639  if( pSubSrc->nSrc==0 ) return 0;                       /* Restriction (7)  */
92640  if( pSub->selFlags & SF_Distinct ) return 0;           /* Restriction (5)  */
92641  if( pSub->pLimit && (pSrc->nSrc>1 || isAgg) ){
92642     return 0;         /* Restrictions (8)(9) */
92643  }
92644  if( (p->selFlags & SF_Distinct)!=0 && subqueryIsAgg ){
92645     return 0;         /* Restriction (6)  */
92646  }
92647  if( p->pOrderBy && pSub->pOrderBy ){
92648     return 0;                                           /* Restriction (11) */
92649  }
92650  if( isAgg && pSub->pOrderBy ) return 0;                /* Restriction (16) */
92651  if( pSub->pLimit && p->pWhere ) return 0;              /* Restriction (19) */
92652  if( pSub->pLimit && (p->selFlags & SF_Distinct)!=0 ){
92653     return 0;         /* Restriction (21) */
92654  }
92655
92656  /* OBSOLETE COMMENT 1:
92657  ** Restriction 3:  If the subquery is a join, make sure the subquery is
92658  ** not used as the right operand of an outer join.  Examples of why this
92659  ** is not allowed:
92660  **
92661  **         t1 LEFT OUTER JOIN (t2 JOIN t3)
92662  **
92663  ** If we flatten the above, we would get
92664  **
92665  **         (t1 LEFT OUTER JOIN t2) JOIN t3
92666  **
92667  ** which is not at all the same thing.
92668  **
92669  ** OBSOLETE COMMENT 2:
92670  ** Restriction 12:  If the subquery is the right operand of a left outer
92671  ** join, make sure the subquery has no WHERE clause.
92672  ** An examples of why this is not allowed:
92673  **
92674  **         t1 LEFT OUTER JOIN (SELECT * FROM t2 WHERE t2.x>0)
92675  **
92676  ** If we flatten the above, we would get
92677  **
92678  **         (t1 LEFT OUTER JOIN t2) WHERE t2.x>0
92679  **
92680  ** But the t2.x>0 test will always fail on a NULL row of t2, which
92681  ** effectively converts the OUTER JOIN into an INNER JOIN.
92682  **
92683  ** THIS OVERRIDES OBSOLETE COMMENTS 1 AND 2 ABOVE:
92684  ** Ticket #3300 shows that flattening the right term of a LEFT JOIN
92685  ** is fraught with danger.  Best to avoid the whole thing.  If the
92686  ** subquery is the right term of a LEFT JOIN, then do not flatten.
92687  */
92688  if( (pSubitem->jointype & JT_OUTER)!=0 ){
92689    return 0;
92690  }
92691
92692  /* Restriction 17: If the sub-query is a compound SELECT, then it must
92693  ** use only the UNION ALL operator. And none of the simple select queries
92694  ** that make up the compound SELECT are allowed to be aggregate or distinct
92695  ** queries.
92696  */
92697  if( pSub->pPrior ){
92698    if( pSub->pOrderBy ){
92699      return 0;  /* Restriction 20 */
92700    }
92701    if( isAgg || (p->selFlags & SF_Distinct)!=0 || pSrc->nSrc!=1 ){
92702      return 0;
92703    }
92704    for(pSub1=pSub; pSub1; pSub1=pSub1->pPrior){
92705      testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
92706      testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
92707      if( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))!=0
92708       || (pSub1->pPrior && pSub1->op!=TK_ALL)
92709       || NEVER(pSub1->pSrc==0) || pSub1->pSrc->nSrc!=1
92710      ){
92711        return 0;
92712      }
92713    }
92714
92715    /* Restriction 18. */
92716    if( p->pOrderBy ){
92717      int ii;
92718      for(ii=0; ii<p->pOrderBy->nExpr; ii++){
92719        if( p->pOrderBy->a[ii].iCol==0 ) return 0;
92720      }
92721    }
92722  }
92723
92724  /***** If we reach this point, flattening is permitted. *****/
92725
92726  /* Authorize the subquery */
92727  pParse->zAuthContext = pSubitem->zName;
92728  sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0);
92729  pParse->zAuthContext = zSavedAuthContext;
92730
92731  /* If the sub-query is a compound SELECT statement, then (by restrictions
92732  ** 17 and 18 above) it must be a UNION ALL and the parent query must
92733  ** be of the form:
92734  **
92735  **     SELECT <expr-list> FROM (<sub-query>) <where-clause>
92736  **
92737  ** followed by any ORDER BY, LIMIT and/or OFFSET clauses. This block
92738  ** creates N-1 copies of the parent query without any ORDER BY, LIMIT or
92739  ** OFFSET clauses and joins them to the left-hand-side of the original
92740  ** using UNION ALL operators. In this case N is the number of simple
92741  ** select statements in the compound sub-query.
92742  **
92743  ** Example:
92744  **
92745  **     SELECT a+1 FROM (
92746  **        SELECT x FROM tab
92747  **        UNION ALL
92748  **        SELECT y FROM tab
92749  **        UNION ALL
92750  **        SELECT abs(z*2) FROM tab2
92751  **     ) WHERE a!=5 ORDER BY 1
92752  **
92753  ** Transformed into:
92754  **
92755  **     SELECT x+1 FROM tab WHERE x+1!=5
92756  **     UNION ALL
92757  **     SELECT y+1 FROM tab WHERE y+1!=5
92758  **     UNION ALL
92759  **     SELECT abs(z*2)+1 FROM tab2 WHERE abs(z*2)+1!=5
92760  **     ORDER BY 1
92761  **
92762  ** We call this the "compound-subquery flattening".
92763  */
92764  for(pSub=pSub->pPrior; pSub; pSub=pSub->pPrior){
92765    Select *pNew;
92766    ExprList *pOrderBy = p->pOrderBy;
92767    Expr *pLimit = p->pLimit;
92768    Select *pPrior = p->pPrior;
92769    p->pOrderBy = 0;
92770    p->pSrc = 0;
92771    p->pPrior = 0;
92772    p->pLimit = 0;
92773    pNew = sqlite3SelectDup(db, p, 0);
92774    p->pLimit = pLimit;
92775    p->pOrderBy = pOrderBy;
92776    p->pSrc = pSrc;
92777    p->op = TK_ALL;
92778    p->pRightmost = 0;
92779    if( pNew==0 ){
92780      pNew = pPrior;
92781    }else{
92782      pNew->pPrior = pPrior;
92783      pNew->pRightmost = 0;
92784    }
92785    p->pPrior = pNew;
92786    if( db->mallocFailed ) return 1;
92787  }
92788
92789  /* Begin flattening the iFrom-th entry of the FROM clause
92790  ** in the outer query.
92791  */
92792  pSub = pSub1 = pSubitem->pSelect;
92793
92794  /* Delete the transient table structure associated with the
92795  ** subquery
92796  */
92797  sqlite3DbFree(db, pSubitem->zDatabase);
92798  sqlite3DbFree(db, pSubitem->zName);
92799  sqlite3DbFree(db, pSubitem->zAlias);
92800  pSubitem->zDatabase = 0;
92801  pSubitem->zName = 0;
92802  pSubitem->zAlias = 0;
92803  pSubitem->pSelect = 0;
92804
92805  /* Defer deleting the Table object associated with the
92806  ** subquery until code generation is
92807  ** complete, since there may still exist Expr.pTab entries that
92808  ** refer to the subquery even after flattening.  Ticket #3346.
92809  **
92810  ** pSubitem->pTab is always non-NULL by test restrictions and tests above.
92811  */
92812  if( ALWAYS(pSubitem->pTab!=0) ){
92813    Table *pTabToDel = pSubitem->pTab;
92814    if( pTabToDel->nRef==1 ){
92815      Parse *pToplevel = sqlite3ParseToplevel(pParse);
92816      pTabToDel->pNextZombie = pToplevel->pZombieTab;
92817      pToplevel->pZombieTab = pTabToDel;
92818    }else{
92819      pTabToDel->nRef--;
92820    }
92821    pSubitem->pTab = 0;
92822  }
92823
92824  /* The following loop runs once for each term in a compound-subquery
92825  ** flattening (as described above).  If we are doing a different kind
92826  ** of flattening - a flattening other than a compound-subquery flattening -
92827  ** then this loop only runs once.
92828  **
92829  ** This loop moves all of the FROM elements of the subquery into the
92830  ** the FROM clause of the outer query.  Before doing this, remember
92831  ** the cursor number for the original outer query FROM element in
92832  ** iParent.  The iParent cursor will never be used.  Subsequent code
92833  ** will scan expressions looking for iParent references and replace
92834  ** those references with expressions that resolve to the subquery FROM
92835  ** elements we are now copying in.
92836  */
92837  for(pParent=p; pParent; pParent=pParent->pPrior, pSub=pSub->pPrior){
92838    int nSubSrc;
92839    u8 jointype = 0;
92840    pSubSrc = pSub->pSrc;     /* FROM clause of subquery */
92841    nSubSrc = pSubSrc->nSrc;  /* Number of terms in subquery FROM clause */
92842    pSrc = pParent->pSrc;     /* FROM clause of the outer query */
92843
92844    if( pSrc ){
92845      assert( pParent==p );  /* First time through the loop */
92846      jointype = pSubitem->jointype;
92847    }else{
92848      assert( pParent!=p );  /* 2nd and subsequent times through the loop */
92849      pSrc = pParent->pSrc = sqlite3SrcListAppend(db, 0, 0, 0);
92850      if( pSrc==0 ){
92851        assert( db->mallocFailed );
92852        break;
92853      }
92854    }
92855
92856    /* The subquery uses a single slot of the FROM clause of the outer
92857    ** query.  If the subquery has more than one element in its FROM clause,
92858    ** then expand the outer query to make space for it to hold all elements
92859    ** of the subquery.
92860    **
92861    ** Example:
92862    **
92863    **    SELECT * FROM tabA, (SELECT * FROM sub1, sub2), tabB;
92864    **
92865    ** The outer query has 3 slots in its FROM clause.  One slot of the
92866    ** outer query (the middle slot) is used by the subquery.  The next
92867    ** block of code will expand the out query to 4 slots.  The middle
92868    ** slot is expanded to two slots in order to make space for the
92869    ** two elements in the FROM clause of the subquery.
92870    */
92871    if( nSubSrc>1 ){
92872      pParent->pSrc = pSrc = sqlite3SrcListEnlarge(db, pSrc, nSubSrc-1,iFrom+1);
92873      if( db->mallocFailed ){
92874        break;
92875      }
92876    }
92877
92878    /* Transfer the FROM clause terms from the subquery into the
92879    ** outer query.
92880    */
92881    for(i=0; i<nSubSrc; i++){
92882      sqlite3IdListDelete(db, pSrc->a[i+iFrom].pUsing);
92883      pSrc->a[i+iFrom] = pSubSrc->a[i];
92884      memset(&pSubSrc->a[i], 0, sizeof(pSubSrc->a[i]));
92885    }
92886    pSrc->a[iFrom].jointype = jointype;
92887
92888    /* Now begin substituting subquery result set expressions for
92889    ** references to the iParent in the outer query.
92890    **
92891    ** Example:
92892    **
92893    **   SELECT a+5, b*10 FROM (SELECT x*3 AS a, y+10 AS b FROM t1) WHERE a>b;
92894    **   \                     \_____________ subquery __________/          /
92895    **    \_____________________ outer query ______________________________/
92896    **
92897    ** We look at every expression in the outer query and every place we see
92898    ** "a" we substitute "x*3" and every place we see "b" we substitute "y+10".
92899    */
92900    pList = pParent->pEList;
92901    for(i=0; i<pList->nExpr; i++){
92902      if( pList->a[i].zName==0 ){
92903        const char *zSpan = pList->a[i].zSpan;
92904        if( ALWAYS(zSpan) ){
92905          pList->a[i].zName = sqlite3DbStrDup(db, zSpan);
92906        }
92907      }
92908    }
92909    substExprList(db, pParent->pEList, iParent, pSub->pEList);
92910    if( isAgg ){
92911      substExprList(db, pParent->pGroupBy, iParent, pSub->pEList);
92912      pParent->pHaving = substExpr(db, pParent->pHaving, iParent, pSub->pEList);
92913    }
92914    if( pSub->pOrderBy ){
92915      assert( pParent->pOrderBy==0 );
92916      pParent->pOrderBy = pSub->pOrderBy;
92917      pSub->pOrderBy = 0;
92918    }else if( pParent->pOrderBy ){
92919      substExprList(db, pParent->pOrderBy, iParent, pSub->pEList);
92920    }
92921    if( pSub->pWhere ){
92922      pWhere = sqlite3ExprDup(db, pSub->pWhere, 0);
92923    }else{
92924      pWhere = 0;
92925    }
92926    if( subqueryIsAgg ){
92927      assert( pParent->pHaving==0 );
92928      pParent->pHaving = pParent->pWhere;
92929      pParent->pWhere = pWhere;
92930      pParent->pHaving = substExpr(db, pParent->pHaving, iParent, pSub->pEList);
92931      pParent->pHaving = sqlite3ExprAnd(db, pParent->pHaving,
92932                                  sqlite3ExprDup(db, pSub->pHaving, 0));
92933      assert( pParent->pGroupBy==0 );
92934      pParent->pGroupBy = sqlite3ExprListDup(db, pSub->pGroupBy, 0);
92935    }else{
92936      pParent->pWhere = substExpr(db, pParent->pWhere, iParent, pSub->pEList);
92937      pParent->pWhere = sqlite3ExprAnd(db, pParent->pWhere, pWhere);
92938    }
92939
92940    /* The flattened query is distinct if either the inner or the
92941    ** outer query is distinct.
92942    */
92943    pParent->selFlags |= pSub->selFlags & SF_Distinct;
92944
92945    /*
92946    ** SELECT ... FROM (SELECT ... LIMIT a OFFSET b) LIMIT x OFFSET y;
92947    **
92948    ** One is tempted to try to add a and b to combine the limits.  But this
92949    ** does not work if either limit is negative.
92950    */
92951    if( pSub->pLimit ){
92952      pParent->pLimit = pSub->pLimit;
92953      pSub->pLimit = 0;
92954    }
92955  }
92956
92957  /* Finially, delete what is left of the subquery and return
92958  ** success.
92959  */
92960  sqlite3SelectDelete(db, pSub1);
92961
92962  return 1;
92963}
92964#endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
92965
92966/*
92967** Analyze the SELECT statement passed as an argument to see if it
92968** is a min() or max() query. Return WHERE_ORDERBY_MIN or WHERE_ORDERBY_MAX if
92969** it is, or 0 otherwise. At present, a query is considered to be
92970** a min()/max() query if:
92971**
92972**   1. There is a single object in the FROM clause.
92973**
92974**   2. There is a single expression in the result set, and it is
92975**      either min(x) or max(x), where x is a column reference.
92976*/
92977static u8 minMaxQuery(Select *p){
92978  Expr *pExpr;
92979  ExprList *pEList = p->pEList;
92980
92981  if( pEList->nExpr!=1 ) return WHERE_ORDERBY_NORMAL;
92982  pExpr = pEList->a[0].pExpr;
92983  if( pExpr->op!=TK_AGG_FUNCTION ) return 0;
92984  if( NEVER(ExprHasProperty(pExpr, EP_xIsSelect)) ) return 0;
92985  pEList = pExpr->x.pList;
92986  if( pEList==0 || pEList->nExpr!=1 ) return 0;
92987  if( pEList->a[0].pExpr->op!=TK_AGG_COLUMN ) return WHERE_ORDERBY_NORMAL;
92988  assert( !ExprHasProperty(pExpr, EP_IntValue) );
92989  if( sqlite3StrICmp(pExpr->u.zToken,"min")==0 ){
92990    return WHERE_ORDERBY_MIN;
92991  }else if( sqlite3StrICmp(pExpr->u.zToken,"max")==0 ){
92992    return WHERE_ORDERBY_MAX;
92993  }
92994  return WHERE_ORDERBY_NORMAL;
92995}
92996
92997/*
92998** The select statement passed as the first argument is an aggregate query.
92999** The second argment is the associated aggregate-info object. This
93000** function tests if the SELECT is of the form:
93001**
93002**   SELECT count(*) FROM <tbl>
93003**
93004** where table is a database table, not a sub-select or view. If the query
93005** does match this pattern, then a pointer to the Table object representing
93006** <tbl> is returned. Otherwise, 0 is returned.
93007*/
93008static Table *isSimpleCount(Select *p, AggInfo *pAggInfo){
93009  Table *pTab;
93010  Expr *pExpr;
93011
93012  assert( !p->pGroupBy );
93013
93014  if( p->pWhere || p->pEList->nExpr!=1
93015   || p->pSrc->nSrc!=1 || p->pSrc->a[0].pSelect
93016  ){
93017    return 0;
93018  }
93019  pTab = p->pSrc->a[0].pTab;
93020  pExpr = p->pEList->a[0].pExpr;
93021  assert( pTab && !pTab->pSelect && pExpr );
93022
93023  if( IsVirtual(pTab) ) return 0;
93024  if( pExpr->op!=TK_AGG_FUNCTION ) return 0;
93025  if( (pAggInfo->aFunc[0].pFunc->flags&SQLITE_FUNC_COUNT)==0 ) return 0;
93026  if( pExpr->flags&EP_Distinct ) return 0;
93027
93028  return pTab;
93029}
93030
93031/*
93032** If the source-list item passed as an argument was augmented with an
93033** INDEXED BY clause, then try to locate the specified index. If there
93034** was such a clause and the named index cannot be found, return
93035** SQLITE_ERROR and leave an error in pParse. Otherwise, populate
93036** pFrom->pIndex and return SQLITE_OK.
93037*/
93038SQLITE_PRIVATE int sqlite3IndexedByLookup(Parse *pParse, struct SrcList_item *pFrom){
93039  if( pFrom->pTab && pFrom->zIndex ){
93040    Table *pTab = pFrom->pTab;
93041    char *zIndex = pFrom->zIndex;
93042    Index *pIdx;
93043    for(pIdx=pTab->pIndex;
93044        pIdx && sqlite3StrICmp(pIdx->zName, zIndex);
93045        pIdx=pIdx->pNext
93046    );
93047    if( !pIdx ){
93048      sqlite3ErrorMsg(pParse, "no such index: %s", zIndex, 0);
93049      pParse->checkSchema = 1;
93050      return SQLITE_ERROR;
93051    }
93052    pFrom->pIndex = pIdx;
93053  }
93054  return SQLITE_OK;
93055}
93056
93057/*
93058** This routine is a Walker callback for "expanding" a SELECT statement.
93059** "Expanding" means to do the following:
93060**
93061**    (1)  Make sure VDBE cursor numbers have been assigned to every
93062**         element of the FROM clause.
93063**
93064**    (2)  Fill in the pTabList->a[].pTab fields in the SrcList that
93065**         defines FROM clause.  When views appear in the FROM clause,
93066**         fill pTabList->a[].pSelect with a copy of the SELECT statement
93067**         that implements the view.  A copy is made of the view's SELECT
93068**         statement so that we can freely modify or delete that statement
93069**         without worrying about messing up the presistent representation
93070**         of the view.
93071**
93072**    (3)  Add terms to the WHERE clause to accomodate the NATURAL keyword
93073**         on joins and the ON and USING clause of joins.
93074**
93075**    (4)  Scan the list of columns in the result set (pEList) looking
93076**         for instances of the "*" operator or the TABLE.* operator.
93077**         If found, expand each "*" to be every column in every table
93078**         and TABLE.* to be every column in TABLE.
93079**
93080*/
93081static int selectExpander(Walker *pWalker, Select *p){
93082  Parse *pParse = pWalker->pParse;
93083  int i, j, k;
93084  SrcList *pTabList;
93085  ExprList *pEList;
93086  struct SrcList_item *pFrom;
93087  sqlite3 *db = pParse->db;
93088
93089  if( db->mallocFailed  ){
93090    return WRC_Abort;
93091  }
93092  if( NEVER(p->pSrc==0) || (p->selFlags & SF_Expanded)!=0 ){
93093    return WRC_Prune;
93094  }
93095  p->selFlags |= SF_Expanded;
93096  pTabList = p->pSrc;
93097  pEList = p->pEList;
93098
93099  /* Make sure cursor numbers have been assigned to all entries in
93100  ** the FROM clause of the SELECT statement.
93101  */
93102  sqlite3SrcListAssignCursors(pParse, pTabList);
93103
93104  /* Look up every table named in the FROM clause of the select.  If
93105  ** an entry of the FROM clause is a subquery instead of a table or view,
93106  ** then create a transient table structure to describe the subquery.
93107  */
93108  for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
93109    Table *pTab;
93110    if( pFrom->pTab!=0 ){
93111      /* This statement has already been prepared.  There is no need
93112      ** to go further. */
93113      assert( i==0 );
93114      return WRC_Prune;
93115    }
93116    if( pFrom->zName==0 ){
93117#ifndef SQLITE_OMIT_SUBQUERY
93118      Select *pSel = pFrom->pSelect;
93119      /* A sub-query in the FROM clause of a SELECT */
93120      assert( pSel!=0 );
93121      assert( pFrom->pTab==0 );
93122      sqlite3WalkSelect(pWalker, pSel);
93123      pFrom->pTab = pTab = sqlite3DbMallocZero(db, sizeof(Table));
93124      if( pTab==0 ) return WRC_Abort;
93125      pTab->nRef = 1;
93126      pTab->zName = sqlite3MPrintf(db, "sqlite_subquery_%p_", (void*)pTab);
93127      while( pSel->pPrior ){ pSel = pSel->pPrior; }
93128      selectColumnsFromExprList(pParse, pSel->pEList, &pTab->nCol, &pTab->aCol);
93129      pTab->iPKey = -1;
93130      pTab->nRowEst = 1000000;
93131      pTab->tabFlags |= TF_Ephemeral;
93132#endif
93133    }else{
93134      /* An ordinary table or view name in the FROM clause */
93135      assert( pFrom->pTab==0 );
93136      pFrom->pTab = pTab =
93137        sqlite3LocateTable(pParse,0,pFrom->zName,pFrom->zDatabase);
93138      if( pTab==0 ) return WRC_Abort;
93139      pTab->nRef++;
93140#if !defined(SQLITE_OMIT_VIEW) || !defined (SQLITE_OMIT_VIRTUALTABLE)
93141      if( pTab->pSelect || IsVirtual(pTab) ){
93142        /* We reach here if the named table is a really a view */
93143        if( sqlite3ViewGetColumnNames(pParse, pTab) ) return WRC_Abort;
93144        assert( pFrom->pSelect==0 );
93145        pFrom->pSelect = sqlite3SelectDup(db, pTab->pSelect, 0);
93146        sqlite3WalkSelect(pWalker, pFrom->pSelect);
93147      }
93148#endif
93149    }
93150
93151    /* Locate the index named by the INDEXED BY clause, if any. */
93152    if( sqlite3IndexedByLookup(pParse, pFrom) ){
93153      return WRC_Abort;
93154    }
93155  }
93156
93157  /* Process NATURAL keywords, and ON and USING clauses of joins.
93158  */
93159  if( db->mallocFailed || sqliteProcessJoin(pParse, p) ){
93160    return WRC_Abort;
93161  }
93162
93163  /* For every "*" that occurs in the column list, insert the names of
93164  ** all columns in all tables.  And for every TABLE.* insert the names
93165  ** of all columns in TABLE.  The parser inserted a special expression
93166  ** with the TK_ALL operator for each "*" that it found in the column list.
93167  ** The following code just has to locate the TK_ALL expressions and expand
93168  ** each one to the list of all columns in all tables.
93169  **
93170  ** The first loop just checks to see if there are any "*" operators
93171  ** that need expanding.
93172  */
93173  for(k=0; k<pEList->nExpr; k++){
93174    Expr *pE = pEList->a[k].pExpr;
93175    if( pE->op==TK_ALL ) break;
93176    assert( pE->op!=TK_DOT || pE->pRight!=0 );
93177    assert( pE->op!=TK_DOT || (pE->pLeft!=0 && pE->pLeft->op==TK_ID) );
93178    if( pE->op==TK_DOT && pE->pRight->op==TK_ALL ) break;
93179  }
93180  if( k<pEList->nExpr ){
93181    /*
93182    ** If we get here it means the result set contains one or more "*"
93183    ** operators that need to be expanded.  Loop through each expression
93184    ** in the result set and expand them one by one.
93185    */
93186    struct ExprList_item *a = pEList->a;
93187    ExprList *pNew = 0;
93188    int flags = pParse->db->flags;
93189    int longNames = (flags & SQLITE_FullColNames)!=0
93190                      && (flags & SQLITE_ShortColNames)==0;
93191
93192    for(k=0; k<pEList->nExpr; k++){
93193      Expr *pE = a[k].pExpr;
93194      assert( pE->op!=TK_DOT || pE->pRight!=0 );
93195      if( pE->op!=TK_ALL && (pE->op!=TK_DOT || pE->pRight->op!=TK_ALL) ){
93196        /* This particular expression does not need to be expanded.
93197        */
93198        pNew = sqlite3ExprListAppend(pParse, pNew, a[k].pExpr);
93199        if( pNew ){
93200          pNew->a[pNew->nExpr-1].zName = a[k].zName;
93201          pNew->a[pNew->nExpr-1].zSpan = a[k].zSpan;
93202          a[k].zName = 0;
93203          a[k].zSpan = 0;
93204        }
93205        a[k].pExpr = 0;
93206      }else{
93207        /* This expression is a "*" or a "TABLE.*" and needs to be
93208        ** expanded. */
93209        int tableSeen = 0;      /* Set to 1 when TABLE matches */
93210        char *zTName;            /* text of name of TABLE */
93211        if( pE->op==TK_DOT ){
93212          assert( pE->pLeft!=0 );
93213          assert( !ExprHasProperty(pE->pLeft, EP_IntValue) );
93214          zTName = pE->pLeft->u.zToken;
93215        }else{
93216          zTName = 0;
93217        }
93218        for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
93219          Table *pTab = pFrom->pTab;
93220          char *zTabName = pFrom->zAlias;
93221          if( zTabName==0 ){
93222            zTabName = pTab->zName;
93223          }
93224          if( db->mallocFailed ) break;
93225          if( zTName && sqlite3StrICmp(zTName, zTabName)!=0 ){
93226            continue;
93227          }
93228          tableSeen = 1;
93229          for(j=0; j<pTab->nCol; j++){
93230            Expr *pExpr, *pRight;
93231            char *zName = pTab->aCol[j].zName;
93232            char *zColname;  /* The computed column name */
93233            char *zToFree;   /* Malloced string that needs to be freed */
93234            Token sColname;  /* Computed column name as a token */
93235
93236            /* If a column is marked as 'hidden' (currently only possible
93237            ** for virtual tables), do not include it in the expanded
93238            ** result-set list.
93239            */
93240            if( IsHiddenColumn(&pTab->aCol[j]) ){
93241              assert(IsVirtual(pTab));
93242              continue;
93243            }
93244
93245            if( i>0 && zTName==0 ){
93246              if( (pFrom->jointype & JT_NATURAL)!=0
93247                && tableAndColumnIndex(pTabList, i, zName, 0, 0)
93248              ){
93249                /* In a NATURAL join, omit the join columns from the
93250                ** table to the right of the join */
93251                continue;
93252              }
93253              if( sqlite3IdListIndex(pFrom->pUsing, zName)>=0 ){
93254                /* In a join with a USING clause, omit columns in the
93255                ** using clause from the table on the right. */
93256                continue;
93257              }
93258            }
93259            pRight = sqlite3Expr(db, TK_ID, zName);
93260            zColname = zName;
93261            zToFree = 0;
93262            if( longNames || pTabList->nSrc>1 ){
93263              Expr *pLeft;
93264              pLeft = sqlite3Expr(db, TK_ID, zTabName);
93265              pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight, 0);
93266              if( longNames ){
93267                zColname = sqlite3MPrintf(db, "%s.%s", zTabName, zName);
93268                zToFree = zColname;
93269              }
93270            }else{
93271              pExpr = pRight;
93272            }
93273            pNew = sqlite3ExprListAppend(pParse, pNew, pExpr);
93274            sColname.z = zColname;
93275            sColname.n = sqlite3Strlen30(zColname);
93276            sqlite3ExprListSetName(pParse, pNew, &sColname, 0);
93277            sqlite3DbFree(db, zToFree);
93278          }
93279        }
93280        if( !tableSeen ){
93281          if( zTName ){
93282            sqlite3ErrorMsg(pParse, "no such table: %s", zTName);
93283          }else{
93284            sqlite3ErrorMsg(pParse, "no tables specified");
93285          }
93286        }
93287      }
93288    }
93289    sqlite3ExprListDelete(db, pEList);
93290    p->pEList = pNew;
93291  }
93292#if SQLITE_MAX_COLUMN
93293  if( p->pEList && p->pEList->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
93294    sqlite3ErrorMsg(pParse, "too many columns in result set");
93295  }
93296#endif
93297  return WRC_Continue;
93298}
93299
93300/*
93301** No-op routine for the parse-tree walker.
93302**
93303** When this routine is the Walker.xExprCallback then expression trees
93304** are walked without any actions being taken at each node.  Presumably,
93305** when this routine is used for Walker.xExprCallback then
93306** Walker.xSelectCallback is set to do something useful for every
93307** subquery in the parser tree.
93308*/
93309static int exprWalkNoop(Walker *NotUsed, Expr *NotUsed2){
93310  UNUSED_PARAMETER2(NotUsed, NotUsed2);
93311  return WRC_Continue;
93312}
93313
93314/*
93315** This routine "expands" a SELECT statement and all of its subqueries.
93316** For additional information on what it means to "expand" a SELECT
93317** statement, see the comment on the selectExpand worker callback above.
93318**
93319** Expanding a SELECT statement is the first step in processing a
93320** SELECT statement.  The SELECT statement must be expanded before
93321** name resolution is performed.
93322**
93323** If anything goes wrong, an error message is written into pParse.
93324** The calling function can detect the problem by looking at pParse->nErr
93325** and/or pParse->db->mallocFailed.
93326*/
93327static void sqlite3SelectExpand(Parse *pParse, Select *pSelect){
93328  Walker w;
93329  w.xSelectCallback = selectExpander;
93330  w.xExprCallback = exprWalkNoop;
93331  w.pParse = pParse;
93332  sqlite3WalkSelect(&w, pSelect);
93333}
93334
93335
93336#ifndef SQLITE_OMIT_SUBQUERY
93337/*
93338** This is a Walker.xSelectCallback callback for the sqlite3SelectTypeInfo()
93339** interface.
93340**
93341** For each FROM-clause subquery, add Column.zType and Column.zColl
93342** information to the Table structure that represents the result set
93343** of that subquery.
93344**
93345** The Table structure that represents the result set was constructed
93346** by selectExpander() but the type and collation information was omitted
93347** at that point because identifiers had not yet been resolved.  This
93348** routine is called after identifier resolution.
93349*/
93350static int selectAddSubqueryTypeInfo(Walker *pWalker, Select *p){
93351  Parse *pParse;
93352  int i;
93353  SrcList *pTabList;
93354  struct SrcList_item *pFrom;
93355
93356  assert( p->selFlags & SF_Resolved );
93357  if( (p->selFlags & SF_HasTypeInfo)==0 ){
93358    p->selFlags |= SF_HasTypeInfo;
93359    pParse = pWalker->pParse;
93360    pTabList = p->pSrc;
93361    for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
93362      Table *pTab = pFrom->pTab;
93363      if( ALWAYS(pTab!=0) && (pTab->tabFlags & TF_Ephemeral)!=0 ){
93364        /* A sub-query in the FROM clause of a SELECT */
93365        Select *pSel = pFrom->pSelect;
93366        assert( pSel );
93367        while( pSel->pPrior ) pSel = pSel->pPrior;
93368        selectAddColumnTypeAndCollation(pParse, pTab->nCol, pTab->aCol, pSel);
93369      }
93370    }
93371  }
93372  return WRC_Continue;
93373}
93374#endif
93375
93376
93377/*
93378** This routine adds datatype and collating sequence information to
93379** the Table structures of all FROM-clause subqueries in a
93380** SELECT statement.
93381**
93382** Use this routine after name resolution.
93383*/
93384static void sqlite3SelectAddTypeInfo(Parse *pParse, Select *pSelect){
93385#ifndef SQLITE_OMIT_SUBQUERY
93386  Walker w;
93387  w.xSelectCallback = selectAddSubqueryTypeInfo;
93388  w.xExprCallback = exprWalkNoop;
93389  w.pParse = pParse;
93390  sqlite3WalkSelect(&w, pSelect);
93391#endif
93392}
93393
93394
93395/*
93396** This routine sets of a SELECT statement for processing.  The
93397** following is accomplished:
93398**
93399**     *  VDBE Cursor numbers are assigned to all FROM-clause terms.
93400**     *  Ephemeral Table objects are created for all FROM-clause subqueries.
93401**     *  ON and USING clauses are shifted into WHERE statements
93402**     *  Wildcards "*" and "TABLE.*" in result sets are expanded.
93403**     *  Identifiers in expression are matched to tables.
93404**
93405** This routine acts recursively on all subqueries within the SELECT.
93406*/
93407SQLITE_PRIVATE void sqlite3SelectPrep(
93408  Parse *pParse,         /* The parser context */
93409  Select *p,             /* The SELECT statement being coded. */
93410  NameContext *pOuterNC  /* Name context for container */
93411){
93412  sqlite3 *db;
93413  if( NEVER(p==0) ) return;
93414  db = pParse->db;
93415  if( p->selFlags & SF_HasTypeInfo ) return;
93416  sqlite3SelectExpand(pParse, p);
93417  if( pParse->nErr || db->mallocFailed ) return;
93418  sqlite3ResolveSelectNames(pParse, p, pOuterNC);
93419  if( pParse->nErr || db->mallocFailed ) return;
93420  sqlite3SelectAddTypeInfo(pParse, p);
93421}
93422
93423/*
93424** Reset the aggregate accumulator.
93425**
93426** The aggregate accumulator is a set of memory cells that hold
93427** intermediate results while calculating an aggregate.  This
93428** routine simply stores NULLs in all of those memory cells.
93429*/
93430static void resetAccumulator(Parse *pParse, AggInfo *pAggInfo){
93431  Vdbe *v = pParse->pVdbe;
93432  int i;
93433  struct AggInfo_func *pFunc;
93434  if( pAggInfo->nFunc+pAggInfo->nColumn==0 ){
93435    return;
93436  }
93437  for(i=0; i<pAggInfo->nColumn; i++){
93438    sqlite3VdbeAddOp2(v, OP_Null, 0, pAggInfo->aCol[i].iMem);
93439  }
93440  for(pFunc=pAggInfo->aFunc, i=0; i<pAggInfo->nFunc; i++, pFunc++){
93441    sqlite3VdbeAddOp2(v, OP_Null, 0, pFunc->iMem);
93442    if( pFunc->iDistinct>=0 ){
93443      Expr *pE = pFunc->pExpr;
93444      assert( !ExprHasProperty(pE, EP_xIsSelect) );
93445      if( pE->x.pList==0 || pE->x.pList->nExpr!=1 ){
93446        sqlite3ErrorMsg(pParse, "DISTINCT aggregates must have exactly one "
93447           "argument");
93448        pFunc->iDistinct = -1;
93449      }else{
93450        KeyInfo *pKeyInfo = keyInfoFromExprList(pParse, pE->x.pList);
93451        sqlite3VdbeAddOp4(v, OP_OpenEphemeral, pFunc->iDistinct, 0, 0,
93452                          (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
93453      }
93454    }
93455  }
93456}
93457
93458/*
93459** Invoke the OP_AggFinalize opcode for every aggregate function
93460** in the AggInfo structure.
93461*/
93462static void finalizeAggFunctions(Parse *pParse, AggInfo *pAggInfo){
93463  Vdbe *v = pParse->pVdbe;
93464  int i;
93465  struct AggInfo_func *pF;
93466  for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
93467    ExprList *pList = pF->pExpr->x.pList;
93468    assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) );
93469    sqlite3VdbeAddOp4(v, OP_AggFinal, pF->iMem, pList ? pList->nExpr : 0, 0,
93470                      (void*)pF->pFunc, P4_FUNCDEF);
93471  }
93472}
93473
93474/*
93475** Update the accumulator memory cells for an aggregate based on
93476** the current cursor position.
93477*/
93478static void updateAccumulator(Parse *pParse, AggInfo *pAggInfo){
93479  Vdbe *v = pParse->pVdbe;
93480  int i;
93481  struct AggInfo_func *pF;
93482  struct AggInfo_col *pC;
93483
93484  pAggInfo->directMode = 1;
93485  sqlite3ExprCacheClear(pParse);
93486  for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
93487    int nArg;
93488    int addrNext = 0;
93489    int regAgg;
93490    ExprList *pList = pF->pExpr->x.pList;
93491    assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) );
93492    if( pList ){
93493      nArg = pList->nExpr;
93494      regAgg = sqlite3GetTempRange(pParse, nArg);
93495      sqlite3ExprCodeExprList(pParse, pList, regAgg, 1);
93496    }else{
93497      nArg = 0;
93498      regAgg = 0;
93499    }
93500    if( pF->iDistinct>=0 ){
93501      addrNext = sqlite3VdbeMakeLabel(v);
93502      assert( nArg==1 );
93503      codeDistinct(pParse, pF->iDistinct, addrNext, 1, regAgg);
93504    }
93505    if( pF->pFunc->flags & SQLITE_FUNC_NEEDCOLL ){
93506      CollSeq *pColl = 0;
93507      struct ExprList_item *pItem;
93508      int j;
93509      assert( pList!=0 );  /* pList!=0 if pF->pFunc has NEEDCOLL */
93510      for(j=0, pItem=pList->a; !pColl && j<nArg; j++, pItem++){
93511        pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
93512      }
93513      if( !pColl ){
93514        pColl = pParse->db->pDfltColl;
93515      }
93516      sqlite3VdbeAddOp4(v, OP_CollSeq, 0, 0, 0, (char *)pColl, P4_COLLSEQ);
93517    }
93518    sqlite3VdbeAddOp4(v, OP_AggStep, 0, regAgg, pF->iMem,
93519                      (void*)pF->pFunc, P4_FUNCDEF);
93520    sqlite3VdbeChangeP5(v, (u8)nArg);
93521    sqlite3ExprCacheAffinityChange(pParse, regAgg, nArg);
93522    sqlite3ReleaseTempRange(pParse, regAgg, nArg);
93523    if( addrNext ){
93524      sqlite3VdbeResolveLabel(v, addrNext);
93525      sqlite3ExprCacheClear(pParse);
93526    }
93527  }
93528
93529  /* Before populating the accumulator registers, clear the column cache.
93530  ** Otherwise, if any of the required column values are already present
93531  ** in registers, sqlite3ExprCode() may use OP_SCopy to copy the value
93532  ** to pC->iMem. But by the time the value is used, the original register
93533  ** may have been used, invalidating the underlying buffer holding the
93534  ** text or blob value. See ticket [883034dcb5].
93535  **
93536  ** Another solution would be to change the OP_SCopy used to copy cached
93537  ** values to an OP_Copy.
93538  */
93539  sqlite3ExprCacheClear(pParse);
93540  for(i=0, pC=pAggInfo->aCol; i<pAggInfo->nAccumulator; i++, pC++){
93541    sqlite3ExprCode(pParse, pC->pExpr, pC->iMem);
93542  }
93543  pAggInfo->directMode = 0;
93544  sqlite3ExprCacheClear(pParse);
93545}
93546
93547/*
93548** Add a single OP_Explain instruction to the VDBE to explain a simple
93549** count(*) query ("SELECT count(*) FROM pTab").
93550*/
93551#ifndef SQLITE_OMIT_EXPLAIN
93552static void explainSimpleCount(
93553  Parse *pParse,                  /* Parse context */
93554  Table *pTab,                    /* Table being queried */
93555  Index *pIdx                     /* Index used to optimize scan, or NULL */
93556){
93557  if( pParse->explain==2 ){
93558    char *zEqp = sqlite3MPrintf(pParse->db, "SCAN TABLE %s %s%s(~%d rows)",
93559        pTab->zName,
93560        pIdx ? "USING COVERING INDEX " : "",
93561        pIdx ? pIdx->zName : "",
93562        pTab->nRowEst
93563    );
93564    sqlite3VdbeAddOp4(
93565        pParse->pVdbe, OP_Explain, pParse->iSelectId, 0, 0, zEqp, P4_DYNAMIC
93566    );
93567  }
93568}
93569#else
93570# define explainSimpleCount(a,b,c)
93571#endif
93572
93573/*
93574** Generate code for the SELECT statement given in the p argument.
93575**
93576** The results are distributed in various ways depending on the
93577** contents of the SelectDest structure pointed to by argument pDest
93578** as follows:
93579**
93580**     pDest->eDest    Result
93581**     ------------    -------------------------------------------
93582**     SRT_Output      Generate a row of output (using the OP_ResultRow
93583**                     opcode) for each row in the result set.
93584**
93585**     SRT_Mem         Only valid if the result is a single column.
93586**                     Store the first column of the first result row
93587**                     in register pDest->iParm then abandon the rest
93588**                     of the query.  This destination implies "LIMIT 1".
93589**
93590**     SRT_Set         The result must be a single column.  Store each
93591**                     row of result as the key in table pDest->iParm.
93592**                     Apply the affinity pDest->affinity before storing
93593**                     results.  Used to implement "IN (SELECT ...)".
93594**
93595**     SRT_Union       Store results as a key in a temporary table pDest->iParm.
93596**
93597**     SRT_Except      Remove results from the temporary table pDest->iParm.
93598**
93599**     SRT_Table       Store results in temporary table pDest->iParm.
93600**                     This is like SRT_EphemTab except that the table
93601**                     is assumed to already be open.
93602**
93603**     SRT_EphemTab    Create an temporary table pDest->iParm and store
93604**                     the result there. The cursor is left open after
93605**                     returning.  This is like SRT_Table except that
93606**                     this destination uses OP_OpenEphemeral to create
93607**                     the table first.
93608**
93609**     SRT_Coroutine   Generate a co-routine that returns a new row of
93610**                     results each time it is invoked.  The entry point
93611**                     of the co-routine is stored in register pDest->iParm.
93612**
93613**     SRT_Exists      Store a 1 in memory cell pDest->iParm if the result
93614**                     set is not empty.
93615**
93616**     SRT_Discard     Throw the results away.  This is used by SELECT
93617**                     statements within triggers whose only purpose is
93618**                     the side-effects of functions.
93619**
93620** This routine returns the number of errors.  If any errors are
93621** encountered, then an appropriate error message is left in
93622** pParse->zErrMsg.
93623**
93624** This routine does NOT free the Select structure passed in.  The
93625** calling function needs to do that.
93626*/
93627SQLITE_PRIVATE int sqlite3Select(
93628  Parse *pParse,         /* The parser context */
93629  Select *p,             /* The SELECT statement being coded. */
93630  SelectDest *pDest      /* What to do with the query results */
93631){
93632  int i, j;              /* Loop counters */
93633  WhereInfo *pWInfo;     /* Return from sqlite3WhereBegin() */
93634  Vdbe *v;               /* The virtual machine under construction */
93635  int isAgg;             /* True for select lists like "count(*)" */
93636  ExprList *pEList;      /* List of columns to extract. */
93637  SrcList *pTabList;     /* List of tables to select from */
93638  Expr *pWhere;          /* The WHERE clause.  May be NULL */
93639  ExprList *pOrderBy;    /* The ORDER BY clause.  May be NULL */
93640  ExprList *pGroupBy;    /* The GROUP BY clause.  May be NULL */
93641  Expr *pHaving;         /* The HAVING clause.  May be NULL */
93642  int isDistinct;        /* True if the DISTINCT keyword is present */
93643  int distinct;          /* Table to use for the distinct set */
93644  int rc = 1;            /* Value to return from this function */
93645  int addrSortIndex;     /* Address of an OP_OpenEphemeral instruction */
93646  AggInfo sAggInfo;      /* Information used by aggregate queries */
93647  int iEnd;              /* Address of the end of the query */
93648  sqlite3 *db;           /* The database connection */
93649
93650#ifndef SQLITE_OMIT_EXPLAIN
93651  int iRestoreSelectId = pParse->iSelectId;
93652  pParse->iSelectId = pParse->iNextSelectId++;
93653#endif
93654
93655  db = pParse->db;
93656  if( p==0 || db->mallocFailed || pParse->nErr ){
93657    return 1;
93658  }
93659  if( sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0) ) return 1;
93660  memset(&sAggInfo, 0, sizeof(sAggInfo));
93661
93662  if( IgnorableOrderby(pDest) ){
93663    assert(pDest->eDest==SRT_Exists || pDest->eDest==SRT_Union ||
93664           pDest->eDest==SRT_Except || pDest->eDest==SRT_Discard);
93665    /* If ORDER BY makes no difference in the output then neither does
93666    ** DISTINCT so it can be removed too. */
93667    sqlite3ExprListDelete(db, p->pOrderBy);
93668    p->pOrderBy = 0;
93669    p->selFlags &= ~SF_Distinct;
93670  }
93671  sqlite3SelectPrep(pParse, p, 0);
93672  pOrderBy = p->pOrderBy;
93673  pTabList = p->pSrc;
93674  pEList = p->pEList;
93675  if( pParse->nErr || db->mallocFailed ){
93676    goto select_end;
93677  }
93678  isAgg = (p->selFlags & SF_Aggregate)!=0;
93679  assert( pEList!=0 );
93680
93681  /* Begin generating code.
93682  */
93683  v = sqlite3GetVdbe(pParse);
93684  if( v==0 ) goto select_end;
93685
93686  /* If writing to memory or generating a set
93687  ** only a single column may be output.
93688  */
93689#ifndef SQLITE_OMIT_SUBQUERY
93690  if( checkForMultiColumnSelectError(pParse, pDest, pEList->nExpr) ){
93691    goto select_end;
93692  }
93693#endif
93694
93695  /* Generate code for all sub-queries in the FROM clause
93696  */
93697#if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
93698  for(i=0; !p->pPrior && i<pTabList->nSrc; i++){
93699    struct SrcList_item *pItem = &pTabList->a[i];
93700    SelectDest dest;
93701    Select *pSub = pItem->pSelect;
93702    int isAggSub;
93703
93704    if( pSub==0 || pItem->isPopulated ) continue;
93705
93706    /* Increment Parse.nHeight by the height of the largest expression
93707    ** tree refered to by this, the parent select. The child select
93708    ** may contain expression trees of at most
93709    ** (SQLITE_MAX_EXPR_DEPTH-Parse.nHeight) height. This is a bit
93710    ** more conservative than necessary, but much easier than enforcing
93711    ** an exact limit.
93712    */
93713    pParse->nHeight += sqlite3SelectExprHeight(p);
93714
93715    /* Check to see if the subquery can be absorbed into the parent. */
93716    isAggSub = (pSub->selFlags & SF_Aggregate)!=0;
93717    if( flattenSubquery(pParse, p, i, isAgg, isAggSub) ){
93718      if( isAggSub ){
93719        isAgg = 1;
93720        p->selFlags |= SF_Aggregate;
93721      }
93722      i = -1;
93723    }else{
93724      sqlite3SelectDestInit(&dest, SRT_EphemTab, pItem->iCursor);
93725      assert( pItem->isPopulated==0 );
93726      explainSetInteger(pItem->iSelectId, (u8)pParse->iNextSelectId);
93727      sqlite3Select(pParse, pSub, &dest);
93728      pItem->isPopulated = 1;
93729      pItem->pTab->nRowEst = (unsigned)pSub->nSelectRow;
93730    }
93731    if( /*pParse->nErr ||*/ db->mallocFailed ){
93732      goto select_end;
93733    }
93734    pParse->nHeight -= sqlite3SelectExprHeight(p);
93735    pTabList = p->pSrc;
93736    if( !IgnorableOrderby(pDest) ){
93737      pOrderBy = p->pOrderBy;
93738    }
93739  }
93740  pEList = p->pEList;
93741#endif
93742  pWhere = p->pWhere;
93743  pGroupBy = p->pGroupBy;
93744  pHaving = p->pHaving;
93745  isDistinct = (p->selFlags & SF_Distinct)!=0;
93746
93747#ifndef SQLITE_OMIT_COMPOUND_SELECT
93748  /* If there is are a sequence of queries, do the earlier ones first.
93749  */
93750  if( p->pPrior ){
93751    if( p->pRightmost==0 ){
93752      Select *pLoop, *pRight = 0;
93753      int cnt = 0;
93754      int mxSelect;
93755      for(pLoop=p; pLoop; pLoop=pLoop->pPrior, cnt++){
93756        pLoop->pRightmost = p;
93757        pLoop->pNext = pRight;
93758        pRight = pLoop;
93759      }
93760      mxSelect = db->aLimit[SQLITE_LIMIT_COMPOUND_SELECT];
93761      if( mxSelect && cnt>mxSelect ){
93762        sqlite3ErrorMsg(pParse, "too many terms in compound SELECT");
93763        goto select_end;
93764      }
93765    }
93766    rc = multiSelect(pParse, p, pDest);
93767    explainSetInteger(pParse->iSelectId, iRestoreSelectId);
93768    return rc;
93769  }
93770#endif
93771
93772  /* If possible, rewrite the query to use GROUP BY instead of DISTINCT.
93773  ** GROUP BY might use an index, DISTINCT never does.
93774  */
93775  assert( p->pGroupBy==0 || (p->selFlags & SF_Aggregate)!=0 );
93776  if( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct ){
93777    p->pGroupBy = sqlite3ExprListDup(db, p->pEList, 0);
93778    pGroupBy = p->pGroupBy;
93779    p->selFlags &= ~SF_Distinct;
93780  }
93781
93782  /* If there is both a GROUP BY and an ORDER BY clause and they are
93783  ** identical, then disable the ORDER BY clause since the GROUP BY
93784  ** will cause elements to come out in the correct order.  This is
93785  ** an optimization - the correct answer should result regardless.
93786  ** Use the SQLITE_GroupByOrder flag with SQLITE_TESTCTRL_OPTIMIZER
93787  ** to disable this optimization for testing purposes.
93788  */
93789  if( sqlite3ExprListCompare(p->pGroupBy, pOrderBy)==0
93790         && (db->flags & SQLITE_GroupByOrder)==0 ){
93791    pOrderBy = 0;
93792  }
93793
93794  /* If there is an ORDER BY clause, then this sorting
93795  ** index might end up being unused if the data can be
93796  ** extracted in pre-sorted order.  If that is the case, then the
93797  ** OP_OpenEphemeral instruction will be changed to an OP_Noop once
93798  ** we figure out that the sorting index is not needed.  The addrSortIndex
93799  ** variable is used to facilitate that change.
93800  */
93801  if( pOrderBy ){
93802    KeyInfo *pKeyInfo;
93803    pKeyInfo = keyInfoFromExprList(pParse, pOrderBy);
93804    pOrderBy->iECursor = pParse->nTab++;
93805    p->addrOpenEphm[2] = addrSortIndex =
93806      sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
93807                           pOrderBy->iECursor, pOrderBy->nExpr+2, 0,
93808                           (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
93809  }else{
93810    addrSortIndex = -1;
93811  }
93812
93813  /* If the output is destined for a temporary table, open that table.
93814  */
93815  if( pDest->eDest==SRT_EphemTab ){
93816    sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pDest->iParm, pEList->nExpr);
93817  }
93818
93819  /* Set the limiter.
93820  */
93821  iEnd = sqlite3VdbeMakeLabel(v);
93822  p->nSelectRow = (double)LARGEST_INT64;
93823  computeLimitRegisters(pParse, p, iEnd);
93824
93825  /* Open a virtual index to use for the distinct set.
93826  */
93827  if( p->selFlags & SF_Distinct ){
93828    KeyInfo *pKeyInfo;
93829    assert( isAgg || pGroupBy );
93830    distinct = pParse->nTab++;
93831    pKeyInfo = keyInfoFromExprList(pParse, p->pEList);
93832    sqlite3VdbeAddOp4(v, OP_OpenEphemeral, distinct, 0, 0,
93833                        (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
93834    sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
93835  }else{
93836    distinct = -1;
93837  }
93838
93839  /* Aggregate and non-aggregate queries are handled differently */
93840  if( !isAgg && pGroupBy==0 ){
93841    /* This case is for non-aggregate queries
93842    ** Begin the database scan
93843    */
93844    pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pOrderBy, 0);
93845    if( pWInfo==0 ) goto select_end;
93846    if( pWInfo->nRowOut < p->nSelectRow ) p->nSelectRow = pWInfo->nRowOut;
93847
93848    /* If sorting index that was created by a prior OP_OpenEphemeral
93849    ** instruction ended up not being needed, then change the OP_OpenEphemeral
93850    ** into an OP_Noop.
93851    */
93852    if( addrSortIndex>=0 && pOrderBy==0 ){
93853      sqlite3VdbeChangeToNoop(v, addrSortIndex, 1);
93854      p->addrOpenEphm[2] = -1;
93855    }
93856
93857    /* Use the standard inner loop
93858    */
93859    assert(!isDistinct);
93860    selectInnerLoop(pParse, p, pEList, 0, 0, pOrderBy, -1, pDest,
93861                    pWInfo->iContinue, pWInfo->iBreak);
93862
93863    /* End the database scan loop.
93864    */
93865    sqlite3WhereEnd(pWInfo);
93866  }else{
93867    /* This is the processing for aggregate queries */
93868    NameContext sNC;    /* Name context for processing aggregate information */
93869    int iAMem;          /* First Mem address for storing current GROUP BY */
93870    int iBMem;          /* First Mem address for previous GROUP BY */
93871    int iUseFlag;       /* Mem address holding flag indicating that at least
93872                        ** one row of the input to the aggregator has been
93873                        ** processed */
93874    int iAbortFlag;     /* Mem address which causes query abort if positive */
93875    int groupBySort;    /* Rows come from source in GROUP BY order */
93876    int addrEnd;        /* End of processing for this SELECT */
93877
93878    /* Remove any and all aliases between the result set and the
93879    ** GROUP BY clause.
93880    */
93881    if( pGroupBy ){
93882      int k;                        /* Loop counter */
93883      struct ExprList_item *pItem;  /* For looping over expression in a list */
93884
93885      for(k=p->pEList->nExpr, pItem=p->pEList->a; k>0; k--, pItem++){
93886        pItem->iAlias = 0;
93887      }
93888      for(k=pGroupBy->nExpr, pItem=pGroupBy->a; k>0; k--, pItem++){
93889        pItem->iAlias = 0;
93890      }
93891      if( p->nSelectRow>(double)100 ) p->nSelectRow = (double)100;
93892    }else{
93893      p->nSelectRow = (double)1;
93894    }
93895
93896
93897    /* Create a label to jump to when we want to abort the query */
93898    addrEnd = sqlite3VdbeMakeLabel(v);
93899
93900    /* Convert TK_COLUMN nodes into TK_AGG_COLUMN and make entries in
93901    ** sAggInfo for all TK_AGG_FUNCTION nodes in expressions of the
93902    ** SELECT statement.
93903    */
93904    memset(&sNC, 0, sizeof(sNC));
93905    sNC.pParse = pParse;
93906    sNC.pSrcList = pTabList;
93907    sNC.pAggInfo = &sAggInfo;
93908    sAggInfo.nSortingColumn = pGroupBy ? pGroupBy->nExpr+1 : 0;
93909    sAggInfo.pGroupBy = pGroupBy;
93910    sqlite3ExprAnalyzeAggList(&sNC, pEList);
93911    sqlite3ExprAnalyzeAggList(&sNC, pOrderBy);
93912    if( pHaving ){
93913      sqlite3ExprAnalyzeAggregates(&sNC, pHaving);
93914    }
93915    sAggInfo.nAccumulator = sAggInfo.nColumn;
93916    for(i=0; i<sAggInfo.nFunc; i++){
93917      assert( !ExprHasProperty(sAggInfo.aFunc[i].pExpr, EP_xIsSelect) );
93918      sqlite3ExprAnalyzeAggList(&sNC, sAggInfo.aFunc[i].pExpr->x.pList);
93919    }
93920    if( db->mallocFailed ) goto select_end;
93921
93922    /* Processing for aggregates with GROUP BY is very different and
93923    ** much more complex than aggregates without a GROUP BY.
93924    */
93925    if( pGroupBy ){
93926      KeyInfo *pKeyInfo;  /* Keying information for the group by clause */
93927      int j1;             /* A-vs-B comparision jump */
93928      int addrOutputRow;  /* Start of subroutine that outputs a result row */
93929      int regOutputRow;   /* Return address register for output subroutine */
93930      int addrSetAbort;   /* Set the abort flag and return */
93931      int addrTopOfLoop;  /* Top of the input loop */
93932      int addrSortingIdx; /* The OP_OpenEphemeral for the sorting index */
93933      int addrReset;      /* Subroutine for resetting the accumulator */
93934      int regReset;       /* Return address register for reset subroutine */
93935
93936      /* If there is a GROUP BY clause we might need a sorting index to
93937      ** implement it.  Allocate that sorting index now.  If it turns out
93938      ** that we do not need it after all, the OpenEphemeral instruction
93939      ** will be converted into a Noop.
93940      */
93941      sAggInfo.sortingIdx = pParse->nTab++;
93942      pKeyInfo = keyInfoFromExprList(pParse, pGroupBy);
93943      addrSortingIdx = sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
93944          sAggInfo.sortingIdx, sAggInfo.nSortingColumn,
93945          0, (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
93946
93947      /* Initialize memory locations used by GROUP BY aggregate processing
93948      */
93949      iUseFlag = ++pParse->nMem;
93950      iAbortFlag = ++pParse->nMem;
93951      regOutputRow = ++pParse->nMem;
93952      addrOutputRow = sqlite3VdbeMakeLabel(v);
93953      regReset = ++pParse->nMem;
93954      addrReset = sqlite3VdbeMakeLabel(v);
93955      iAMem = pParse->nMem + 1;
93956      pParse->nMem += pGroupBy->nExpr;
93957      iBMem = pParse->nMem + 1;
93958      pParse->nMem += pGroupBy->nExpr;
93959      sqlite3VdbeAddOp2(v, OP_Integer, 0, iAbortFlag);
93960      VdbeComment((v, "clear abort flag"));
93961      sqlite3VdbeAddOp2(v, OP_Integer, 0, iUseFlag);
93962      VdbeComment((v, "indicate accumulator empty"));
93963
93964      /* Begin a loop that will extract all source rows in GROUP BY order.
93965      ** This might involve two separate loops with an OP_Sort in between, or
93966      ** it might be a single loop that uses an index to extract information
93967      ** in the right order to begin with.
93968      */
93969      sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
93970      pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pGroupBy, 0);
93971      if( pWInfo==0 ) goto select_end;
93972      if( pGroupBy==0 ){
93973        /* The optimizer is able to deliver rows in group by order so
93974        ** we do not have to sort.  The OP_OpenEphemeral table will be
93975        ** cancelled later because we still need to use the pKeyInfo
93976        */
93977        pGroupBy = p->pGroupBy;
93978        groupBySort = 0;
93979      }else{
93980        /* Rows are coming out in undetermined order.  We have to push
93981        ** each row into a sorting index, terminate the first loop,
93982        ** then loop over the sorting index in order to get the output
93983        ** in sorted order
93984        */
93985        int regBase;
93986        int regRecord;
93987        int nCol;
93988        int nGroupBy;
93989
93990        explainTempTable(pParse,
93991            isDistinct && !(p->selFlags&SF_Distinct)?"DISTINCT":"GROUP BY");
93992
93993        groupBySort = 1;
93994        nGroupBy = pGroupBy->nExpr;
93995        nCol = nGroupBy + 1;
93996        j = nGroupBy+1;
93997        for(i=0; i<sAggInfo.nColumn; i++){
93998          if( sAggInfo.aCol[i].iSorterColumn>=j ){
93999            nCol++;
94000            j++;
94001          }
94002        }
94003        regBase = sqlite3GetTempRange(pParse, nCol);
94004        sqlite3ExprCacheClear(pParse);
94005        sqlite3ExprCodeExprList(pParse, pGroupBy, regBase, 0);
94006        sqlite3VdbeAddOp2(v, OP_Sequence, sAggInfo.sortingIdx,regBase+nGroupBy);
94007        j = nGroupBy+1;
94008        for(i=0; i<sAggInfo.nColumn; i++){
94009          struct AggInfo_col *pCol = &sAggInfo.aCol[i];
94010          if( pCol->iSorterColumn>=j ){
94011            int r1 = j + regBase;
94012            int r2;
94013
94014            r2 = sqlite3ExprCodeGetColumn(pParse,
94015                               pCol->pTab, pCol->iColumn, pCol->iTable, r1);
94016            if( r1!=r2 ){
94017              sqlite3VdbeAddOp2(v, OP_SCopy, r2, r1);
94018            }
94019            j++;
94020          }
94021        }
94022        regRecord = sqlite3GetTempReg(pParse);
94023        sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol, regRecord);
94024        sqlite3VdbeAddOp2(v, OP_IdxInsert, sAggInfo.sortingIdx, regRecord);
94025        sqlite3ReleaseTempReg(pParse, regRecord);
94026        sqlite3ReleaseTempRange(pParse, regBase, nCol);
94027        sqlite3WhereEnd(pWInfo);
94028        sqlite3VdbeAddOp2(v, OP_Sort, sAggInfo.sortingIdx, addrEnd);
94029        VdbeComment((v, "GROUP BY sort"));
94030        sAggInfo.useSortingIdx = 1;
94031        sqlite3ExprCacheClear(pParse);
94032      }
94033
94034      /* Evaluate the current GROUP BY terms and store in b0, b1, b2...
94035      ** (b0 is memory location iBMem+0, b1 is iBMem+1, and so forth)
94036      ** Then compare the current GROUP BY terms against the GROUP BY terms
94037      ** from the previous row currently stored in a0, a1, a2...
94038      */
94039      addrTopOfLoop = sqlite3VdbeCurrentAddr(v);
94040      sqlite3ExprCacheClear(pParse);
94041      for(j=0; j<pGroupBy->nExpr; j++){
94042        if( groupBySort ){
94043          sqlite3VdbeAddOp3(v, OP_Column, sAggInfo.sortingIdx, j, iBMem+j);
94044        }else{
94045          sAggInfo.directMode = 1;
94046          sqlite3ExprCode(pParse, pGroupBy->a[j].pExpr, iBMem+j);
94047        }
94048      }
94049      sqlite3VdbeAddOp4(v, OP_Compare, iAMem, iBMem, pGroupBy->nExpr,
94050                          (char*)pKeyInfo, P4_KEYINFO);
94051      j1 = sqlite3VdbeCurrentAddr(v);
94052      sqlite3VdbeAddOp3(v, OP_Jump, j1+1, 0, j1+1);
94053
94054      /* Generate code that runs whenever the GROUP BY changes.
94055      ** Changes in the GROUP BY are detected by the previous code
94056      ** block.  If there were no changes, this block is skipped.
94057      **
94058      ** This code copies current group by terms in b0,b1,b2,...
94059      ** over to a0,a1,a2.  It then calls the output subroutine
94060      ** and resets the aggregate accumulator registers in preparation
94061      ** for the next GROUP BY batch.
94062      */
94063      sqlite3ExprCodeMove(pParse, iBMem, iAMem, pGroupBy->nExpr);
94064      sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
94065      VdbeComment((v, "output one row"));
94066      sqlite3VdbeAddOp2(v, OP_IfPos, iAbortFlag, addrEnd);
94067      VdbeComment((v, "check abort flag"));
94068      sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
94069      VdbeComment((v, "reset accumulator"));
94070
94071      /* Update the aggregate accumulators based on the content of
94072      ** the current row
94073      */
94074      sqlite3VdbeJumpHere(v, j1);
94075      updateAccumulator(pParse, &sAggInfo);
94076      sqlite3VdbeAddOp2(v, OP_Integer, 1, iUseFlag);
94077      VdbeComment((v, "indicate data in accumulator"));
94078
94079      /* End of the loop
94080      */
94081      if( groupBySort ){
94082        sqlite3VdbeAddOp2(v, OP_Next, sAggInfo.sortingIdx, addrTopOfLoop);
94083      }else{
94084        sqlite3WhereEnd(pWInfo);
94085        sqlite3VdbeChangeToNoop(v, addrSortingIdx, 1);
94086      }
94087
94088      /* Output the final row of result
94089      */
94090      sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
94091      VdbeComment((v, "output final row"));
94092
94093      /* Jump over the subroutines
94094      */
94095      sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEnd);
94096
94097      /* Generate a subroutine that outputs a single row of the result
94098      ** set.  This subroutine first looks at the iUseFlag.  If iUseFlag
94099      ** is less than or equal to zero, the subroutine is a no-op.  If
94100      ** the processing calls for the query to abort, this subroutine
94101      ** increments the iAbortFlag memory location before returning in
94102      ** order to signal the caller to abort.
94103      */
94104      addrSetAbort = sqlite3VdbeCurrentAddr(v);
94105      sqlite3VdbeAddOp2(v, OP_Integer, 1, iAbortFlag);
94106      VdbeComment((v, "set abort flag"));
94107      sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
94108      sqlite3VdbeResolveLabel(v, addrOutputRow);
94109      addrOutputRow = sqlite3VdbeCurrentAddr(v);
94110      sqlite3VdbeAddOp2(v, OP_IfPos, iUseFlag, addrOutputRow+2);
94111      VdbeComment((v, "Groupby result generator entry point"));
94112      sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
94113      finalizeAggFunctions(pParse, &sAggInfo);
94114      sqlite3ExprIfFalse(pParse, pHaving, addrOutputRow+1, SQLITE_JUMPIFNULL);
94115      selectInnerLoop(pParse, p, p->pEList, 0, 0, pOrderBy,
94116                      distinct, pDest,
94117                      addrOutputRow+1, addrSetAbort);
94118      sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
94119      VdbeComment((v, "end groupby result generator"));
94120
94121      /* Generate a subroutine that will reset the group-by accumulator
94122      */
94123      sqlite3VdbeResolveLabel(v, addrReset);
94124      resetAccumulator(pParse, &sAggInfo);
94125      sqlite3VdbeAddOp1(v, OP_Return, regReset);
94126
94127    } /* endif pGroupBy.  Begin aggregate queries without GROUP BY: */
94128    else {
94129      ExprList *pDel = 0;
94130#ifndef SQLITE_OMIT_BTREECOUNT
94131      Table *pTab;
94132      if( (pTab = isSimpleCount(p, &sAggInfo))!=0 ){
94133        /* If isSimpleCount() returns a pointer to a Table structure, then
94134        ** the SQL statement is of the form:
94135        **
94136        **   SELECT count(*) FROM <tbl>
94137        **
94138        ** where the Table structure returned represents table <tbl>.
94139        **
94140        ** This statement is so common that it is optimized specially. The
94141        ** OP_Count instruction is executed either on the intkey table that
94142        ** contains the data for table <tbl> or on one of its indexes. It
94143        ** is better to execute the op on an index, as indexes are almost
94144        ** always spread across less pages than their corresponding tables.
94145        */
94146        const int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
94147        const int iCsr = pParse->nTab++;     /* Cursor to scan b-tree */
94148        Index *pIdx;                         /* Iterator variable */
94149        KeyInfo *pKeyInfo = 0;               /* Keyinfo for scanned index */
94150        Index *pBest = 0;                    /* Best index found so far */
94151        int iRoot = pTab->tnum;              /* Root page of scanned b-tree */
94152
94153        sqlite3CodeVerifySchema(pParse, iDb);
94154        sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
94155
94156        /* Search for the index that has the least amount of columns. If
94157        ** there is such an index, and it has less columns than the table
94158        ** does, then we can assume that it consumes less space on disk and
94159        ** will therefore be cheaper to scan to determine the query result.
94160        ** In this case set iRoot to the root page number of the index b-tree
94161        ** and pKeyInfo to the KeyInfo structure required to navigate the
94162        ** index.
94163        **
94164        ** In practice the KeyInfo structure will not be used. It is only
94165        ** passed to keep OP_OpenRead happy.
94166        */
94167        for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
94168          if( !pBest || pIdx->nColumn<pBest->nColumn ){
94169            pBest = pIdx;
94170          }
94171        }
94172        if( pBest && pBest->nColumn<pTab->nCol ){
94173          iRoot = pBest->tnum;
94174          pKeyInfo = sqlite3IndexKeyinfo(pParse, pBest);
94175        }
94176
94177        /* Open a read-only cursor, execute the OP_Count, close the cursor. */
94178        sqlite3VdbeAddOp3(v, OP_OpenRead, iCsr, iRoot, iDb);
94179        if( pKeyInfo ){
94180          sqlite3VdbeChangeP4(v, -1, (char *)pKeyInfo, P4_KEYINFO_HANDOFF);
94181        }
94182        sqlite3VdbeAddOp2(v, OP_Count, iCsr, sAggInfo.aFunc[0].iMem);
94183        sqlite3VdbeAddOp1(v, OP_Close, iCsr);
94184        explainSimpleCount(pParse, pTab, pBest);
94185      }else
94186#endif /* SQLITE_OMIT_BTREECOUNT */
94187      {
94188        /* Check if the query is of one of the following forms:
94189        **
94190        **   SELECT min(x) FROM ...
94191        **   SELECT max(x) FROM ...
94192        **
94193        ** If it is, then ask the code in where.c to attempt to sort results
94194        ** as if there was an "ORDER ON x" or "ORDER ON x DESC" clause.
94195        ** If where.c is able to produce results sorted in this order, then
94196        ** add vdbe code to break out of the processing loop after the
94197        ** first iteration (since the first iteration of the loop is
94198        ** guaranteed to operate on the row with the minimum or maximum
94199        ** value of x, the only row required).
94200        **
94201        ** A special flag must be passed to sqlite3WhereBegin() to slightly
94202        ** modify behaviour as follows:
94203        **
94204        **   + If the query is a "SELECT min(x)", then the loop coded by
94205        **     where.c should not iterate over any values with a NULL value
94206        **     for x.
94207        **
94208        **   + The optimizer code in where.c (the thing that decides which
94209        **     index or indices to use) should place a different priority on
94210        **     satisfying the 'ORDER BY' clause than it does in other cases.
94211        **     Refer to code and comments in where.c for details.
94212        */
94213        ExprList *pMinMax = 0;
94214        u8 flag = minMaxQuery(p);
94215        if( flag ){
94216          assert( !ExprHasProperty(p->pEList->a[0].pExpr, EP_xIsSelect) );
94217          pMinMax = sqlite3ExprListDup(db, p->pEList->a[0].pExpr->x.pList,0);
94218          pDel = pMinMax;
94219          if( pMinMax && !db->mallocFailed ){
94220            pMinMax->a[0].sortOrder = flag!=WHERE_ORDERBY_MIN ?1:0;
94221            pMinMax->a[0].pExpr->op = TK_COLUMN;
94222          }
94223        }
94224
94225        /* This case runs if the aggregate has no GROUP BY clause.  The
94226        ** processing is much simpler since there is only a single row
94227        ** of output.
94228        */
94229        resetAccumulator(pParse, &sAggInfo);
94230        pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pMinMax, flag);
94231        if( pWInfo==0 ){
94232          sqlite3ExprListDelete(db, pDel);
94233          goto select_end;
94234        }
94235        updateAccumulator(pParse, &sAggInfo);
94236        if( !pMinMax && flag ){
94237          sqlite3VdbeAddOp2(v, OP_Goto, 0, pWInfo->iBreak);
94238          VdbeComment((v, "%s() by index",
94239                (flag==WHERE_ORDERBY_MIN?"min":"max")));
94240        }
94241        sqlite3WhereEnd(pWInfo);
94242        finalizeAggFunctions(pParse, &sAggInfo);
94243      }
94244
94245      pOrderBy = 0;
94246      sqlite3ExprIfFalse(pParse, pHaving, addrEnd, SQLITE_JUMPIFNULL);
94247      selectInnerLoop(pParse, p, p->pEList, 0, 0, 0, -1,
94248                      pDest, addrEnd, addrEnd);
94249      sqlite3ExprListDelete(db, pDel);
94250    }
94251    sqlite3VdbeResolveLabel(v, addrEnd);
94252
94253  } /* endif aggregate query */
94254
94255  if( distinct>=0 ){
94256    explainTempTable(pParse, "DISTINCT");
94257  }
94258
94259  /* If there is an ORDER BY clause, then we need to sort the results
94260  ** and send them to the callback one by one.
94261  */
94262  if( pOrderBy ){
94263    explainTempTable(pParse, "ORDER BY");
94264    generateSortTail(pParse, p, v, pEList->nExpr, pDest);
94265  }
94266
94267  /* Jump here to skip this query
94268  */
94269  sqlite3VdbeResolveLabel(v, iEnd);
94270
94271  /* The SELECT was successfully coded.   Set the return code to 0
94272  ** to indicate no errors.
94273  */
94274  rc = 0;
94275
94276  /* Control jumps to here if an error is encountered above, or upon
94277  ** successful coding of the SELECT.
94278  */
94279select_end:
94280  explainSetInteger(pParse->iSelectId, iRestoreSelectId);
94281
94282  /* Identify column names if results of the SELECT are to be output.
94283  */
94284  if( rc==SQLITE_OK && pDest->eDest==SRT_Output ){
94285    generateColumnNames(pParse, pTabList, pEList);
94286  }
94287
94288  sqlite3DbFree(db, sAggInfo.aCol);
94289  sqlite3DbFree(db, sAggInfo.aFunc);
94290  return rc;
94291}
94292
94293#if defined(SQLITE_DEBUG)
94294/*
94295*******************************************************************************
94296** The following code is used for testing and debugging only.  The code
94297** that follows does not appear in normal builds.
94298**
94299** These routines are used to print out the content of all or part of a
94300** parse structures such as Select or Expr.  Such printouts are useful
94301** for helping to understand what is happening inside the code generator
94302** during the execution of complex SELECT statements.
94303**
94304** These routine are not called anywhere from within the normal
94305** code base.  Then are intended to be called from within the debugger
94306** or from temporary "printf" statements inserted for debugging.
94307*/
94308SQLITE_PRIVATE void sqlite3PrintExpr(Expr *p){
94309  if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
94310    sqlite3DebugPrintf("(%s", p->u.zToken);
94311  }else{
94312    sqlite3DebugPrintf("(%d", p->op);
94313  }
94314  if( p->pLeft ){
94315    sqlite3DebugPrintf(" ");
94316    sqlite3PrintExpr(p->pLeft);
94317  }
94318  if( p->pRight ){
94319    sqlite3DebugPrintf(" ");
94320    sqlite3PrintExpr(p->pRight);
94321  }
94322  sqlite3DebugPrintf(")");
94323}
94324SQLITE_PRIVATE void sqlite3PrintExprList(ExprList *pList){
94325  int i;
94326  for(i=0; i<pList->nExpr; i++){
94327    sqlite3PrintExpr(pList->a[i].pExpr);
94328    if( i<pList->nExpr-1 ){
94329      sqlite3DebugPrintf(", ");
94330    }
94331  }
94332}
94333SQLITE_PRIVATE void sqlite3PrintSelect(Select *p, int indent){
94334  sqlite3DebugPrintf("%*sSELECT(%p) ", indent, "", p);
94335  sqlite3PrintExprList(p->pEList);
94336  sqlite3DebugPrintf("\n");
94337  if( p->pSrc ){
94338    char *zPrefix;
94339    int i;
94340    zPrefix = "FROM";
94341    for(i=0; i<p->pSrc->nSrc; i++){
94342      struct SrcList_item *pItem = &p->pSrc->a[i];
94343      sqlite3DebugPrintf("%*s ", indent+6, zPrefix);
94344      zPrefix = "";
94345      if( pItem->pSelect ){
94346        sqlite3DebugPrintf("(\n");
94347        sqlite3PrintSelect(pItem->pSelect, indent+10);
94348        sqlite3DebugPrintf("%*s)", indent+8, "");
94349      }else if( pItem->zName ){
94350        sqlite3DebugPrintf("%s", pItem->zName);
94351      }
94352      if( pItem->pTab ){
94353        sqlite3DebugPrintf("(table: %s)", pItem->pTab->zName);
94354      }
94355      if( pItem->zAlias ){
94356        sqlite3DebugPrintf(" AS %s", pItem->zAlias);
94357      }
94358      if( i<p->pSrc->nSrc-1 ){
94359        sqlite3DebugPrintf(",");
94360      }
94361      sqlite3DebugPrintf("\n");
94362    }
94363  }
94364  if( p->pWhere ){
94365    sqlite3DebugPrintf("%*s WHERE ", indent, "");
94366    sqlite3PrintExpr(p->pWhere);
94367    sqlite3DebugPrintf("\n");
94368  }
94369  if( p->pGroupBy ){
94370    sqlite3DebugPrintf("%*s GROUP BY ", indent, "");
94371    sqlite3PrintExprList(p->pGroupBy);
94372    sqlite3DebugPrintf("\n");
94373  }
94374  if( p->pHaving ){
94375    sqlite3DebugPrintf("%*s HAVING ", indent, "");
94376    sqlite3PrintExpr(p->pHaving);
94377    sqlite3DebugPrintf("\n");
94378  }
94379  if( p->pOrderBy ){
94380    sqlite3DebugPrintf("%*s ORDER BY ", indent, "");
94381    sqlite3PrintExprList(p->pOrderBy);
94382    sqlite3DebugPrintf("\n");
94383  }
94384}
94385/* End of the structure debug printing code
94386*****************************************************************************/
94387#endif /* defined(SQLITE_TEST) || defined(SQLITE_DEBUG) */
94388
94389/************** End of select.c **********************************************/
94390/************** Begin file table.c *******************************************/
94391/*
94392** 2001 September 15
94393**
94394** The author disclaims copyright to this source code.  In place of
94395** a legal notice, here is a blessing:
94396**
94397**    May you do good and not evil.
94398**    May you find forgiveness for yourself and forgive others.
94399**    May you share freely, never taking more than you give.
94400**
94401*************************************************************************
94402** This file contains the sqlite3_get_table() and sqlite3_free_table()
94403** interface routines.  These are just wrappers around the main
94404** interface routine of sqlite3_exec().
94405**
94406** These routines are in a separate files so that they will not be linked
94407** if they are not used.
94408*/
94409
94410#ifndef SQLITE_OMIT_GET_TABLE
94411
94412/*
94413** This structure is used to pass data from sqlite3_get_table() through
94414** to the callback function is uses to build the result.
94415*/
94416typedef struct TabResult {
94417  char **azResult;   /* Accumulated output */
94418  char *zErrMsg;     /* Error message text, if an error occurs */
94419  int nAlloc;        /* Slots allocated for azResult[] */
94420  int nRow;          /* Number of rows in the result */
94421  int nColumn;       /* Number of columns in the result */
94422  int nData;         /* Slots used in azResult[].  (nRow+1)*nColumn */
94423  int rc;            /* Return code from sqlite3_exec() */
94424} TabResult;
94425
94426/*
94427** This routine is called once for each row in the result table.  Its job
94428** is to fill in the TabResult structure appropriately, allocating new
94429** memory as necessary.
94430*/
94431static int sqlite3_get_table_cb(void *pArg, int nCol, char **argv, char **colv){
94432  TabResult *p = (TabResult*)pArg;  /* Result accumulator */
94433  int need;                         /* Slots needed in p->azResult[] */
94434  int i;                            /* Loop counter */
94435  char *z;                          /* A single column of result */
94436
94437  /* Make sure there is enough space in p->azResult to hold everything
94438  ** we need to remember from this invocation of the callback.
94439  */
94440  if( p->nRow==0 && argv!=0 ){
94441    need = nCol*2;
94442  }else{
94443    need = nCol;
94444  }
94445  if( p->nData + need > p->nAlloc ){
94446    char **azNew;
94447    p->nAlloc = p->nAlloc*2 + need;
94448    azNew = sqlite3_realloc( p->azResult, sizeof(char*)*p->nAlloc );
94449    if( azNew==0 ) goto malloc_failed;
94450    p->azResult = azNew;
94451  }
94452
94453  /* If this is the first row, then generate an extra row containing
94454  ** the names of all columns.
94455  */
94456  if( p->nRow==0 ){
94457    p->nColumn = nCol;
94458    for(i=0; i<nCol; i++){
94459      z = sqlite3_mprintf("%s", colv[i]);
94460      if( z==0 ) goto malloc_failed;
94461      p->azResult[p->nData++] = z;
94462    }
94463  }else if( p->nColumn!=nCol ){
94464    sqlite3_free(p->zErrMsg);
94465    p->zErrMsg = sqlite3_mprintf(
94466       "sqlite3_get_table() called with two or more incompatible queries"
94467    );
94468    p->rc = SQLITE_ERROR;
94469    return 1;
94470  }
94471
94472  /* Copy over the row data
94473  */
94474  if( argv!=0 ){
94475    for(i=0; i<nCol; i++){
94476      if( argv[i]==0 ){
94477        z = 0;
94478      }else{
94479        int n = sqlite3Strlen30(argv[i])+1;
94480        z = sqlite3_malloc( n );
94481        if( z==0 ) goto malloc_failed;
94482        memcpy(z, argv[i], n);
94483      }
94484      p->azResult[p->nData++] = z;
94485    }
94486    p->nRow++;
94487  }
94488  return 0;
94489
94490malloc_failed:
94491  p->rc = SQLITE_NOMEM;
94492  return 1;
94493}
94494
94495/*
94496** Query the database.  But instead of invoking a callback for each row,
94497** malloc() for space to hold the result and return the entire results
94498** at the conclusion of the call.
94499**
94500** The result that is written to ***pazResult is held in memory obtained
94501** from malloc().  But the caller cannot free this memory directly.
94502** Instead, the entire table should be passed to sqlite3_free_table() when
94503** the calling procedure is finished using it.
94504*/
94505SQLITE_API int sqlite3_get_table(
94506  sqlite3 *db,                /* The database on which the SQL executes */
94507  const char *zSql,           /* The SQL to be executed */
94508  char ***pazResult,          /* Write the result table here */
94509  int *pnRow,                 /* Write the number of rows in the result here */
94510  int *pnColumn,              /* Write the number of columns of result here */
94511  char **pzErrMsg             /* Write error messages here */
94512){
94513  int rc;
94514  TabResult res;
94515
94516  *pazResult = 0;
94517  if( pnColumn ) *pnColumn = 0;
94518  if( pnRow ) *pnRow = 0;
94519  if( pzErrMsg ) *pzErrMsg = 0;
94520  res.zErrMsg = 0;
94521  res.nRow = 0;
94522  res.nColumn = 0;
94523  res.nData = 1;
94524  res.nAlloc = 20;
94525  res.rc = SQLITE_OK;
94526  res.azResult = sqlite3_malloc(sizeof(char*)*res.nAlloc );
94527  if( res.azResult==0 ){
94528     db->errCode = SQLITE_NOMEM;
94529     return SQLITE_NOMEM;
94530  }
94531  res.azResult[0] = 0;
94532  rc = sqlite3_exec(db, zSql, sqlite3_get_table_cb, &res, pzErrMsg);
94533  assert( sizeof(res.azResult[0])>= sizeof(res.nData) );
94534  res.azResult[0] = SQLITE_INT_TO_PTR(res.nData);
94535  if( (rc&0xff)==SQLITE_ABORT ){
94536    sqlite3_free_table(&res.azResult[1]);
94537    if( res.zErrMsg ){
94538      if( pzErrMsg ){
94539        sqlite3_free(*pzErrMsg);
94540        *pzErrMsg = sqlite3_mprintf("%s",res.zErrMsg);
94541      }
94542      sqlite3_free(res.zErrMsg);
94543    }
94544    db->errCode = res.rc;  /* Assume 32-bit assignment is atomic */
94545    return res.rc;
94546  }
94547  sqlite3_free(res.zErrMsg);
94548  if( rc!=SQLITE_OK ){
94549    sqlite3_free_table(&res.azResult[1]);
94550    return rc;
94551  }
94552  if( res.nAlloc>res.nData ){
94553    char **azNew;
94554    azNew = sqlite3_realloc( res.azResult, sizeof(char*)*res.nData );
94555    if( azNew==0 ){
94556      sqlite3_free_table(&res.azResult[1]);
94557      db->errCode = SQLITE_NOMEM;
94558      return SQLITE_NOMEM;
94559    }
94560    res.azResult = azNew;
94561  }
94562  *pazResult = &res.azResult[1];
94563  if( pnColumn ) *pnColumn = res.nColumn;
94564  if( pnRow ) *pnRow = res.nRow;
94565  return rc;
94566}
94567
94568/*
94569** This routine frees the space the sqlite3_get_table() malloced.
94570*/
94571SQLITE_API void sqlite3_free_table(
94572  char **azResult            /* Result returned from from sqlite3_get_table() */
94573){
94574  if( azResult ){
94575    int i, n;
94576    azResult--;
94577    assert( azResult!=0 );
94578    n = SQLITE_PTR_TO_INT(azResult[0]);
94579    for(i=1; i<n; i++){ if( azResult[i] ) sqlite3_free(azResult[i]); }
94580    sqlite3_free(azResult);
94581  }
94582}
94583
94584#endif /* SQLITE_OMIT_GET_TABLE */
94585
94586/************** End of table.c ***********************************************/
94587/************** Begin file trigger.c *****************************************/
94588/*
94589**
94590** The author disclaims copyright to this source code.  In place of
94591** a legal notice, here is a blessing:
94592**
94593**    May you do good and not evil.
94594**    May you find forgiveness for yourself and forgive others.
94595**    May you share freely, never taking more than you give.
94596**
94597*************************************************************************
94598** This file contains the implementation for TRIGGERs
94599*/
94600
94601#ifndef SQLITE_OMIT_TRIGGER
94602/*
94603** Delete a linked list of TriggerStep structures.
94604*/
94605SQLITE_PRIVATE void sqlite3DeleteTriggerStep(sqlite3 *db, TriggerStep *pTriggerStep){
94606  while( pTriggerStep ){
94607    TriggerStep * pTmp = pTriggerStep;
94608    pTriggerStep = pTriggerStep->pNext;
94609
94610    sqlite3ExprDelete(db, pTmp->pWhere);
94611    sqlite3ExprListDelete(db, pTmp->pExprList);
94612    sqlite3SelectDelete(db, pTmp->pSelect);
94613    sqlite3IdListDelete(db, pTmp->pIdList);
94614
94615    sqlite3DbFree(db, pTmp);
94616  }
94617}
94618
94619/*
94620** Given table pTab, return a list of all the triggers attached to
94621** the table. The list is connected by Trigger.pNext pointers.
94622**
94623** All of the triggers on pTab that are in the same database as pTab
94624** are already attached to pTab->pTrigger.  But there might be additional
94625** triggers on pTab in the TEMP schema.  This routine prepends all
94626** TEMP triggers on pTab to the beginning of the pTab->pTrigger list
94627** and returns the combined list.
94628**
94629** To state it another way:  This routine returns a list of all triggers
94630** that fire off of pTab.  The list will include any TEMP triggers on
94631** pTab as well as the triggers lised in pTab->pTrigger.
94632*/
94633SQLITE_PRIVATE Trigger *sqlite3TriggerList(Parse *pParse, Table *pTab){
94634  Schema * const pTmpSchema = pParse->db->aDb[1].pSchema;
94635  Trigger *pList = 0;                  /* List of triggers to return */
94636
94637  if( pParse->disableTriggers ){
94638    return 0;
94639  }
94640
94641  if( pTmpSchema!=pTab->pSchema ){
94642    HashElem *p;
94643    assert( sqlite3SchemaMutexHeld(pParse->db, 0, pTmpSchema) );
94644    for(p=sqliteHashFirst(&pTmpSchema->trigHash); p; p=sqliteHashNext(p)){
94645      Trigger *pTrig = (Trigger *)sqliteHashData(p);
94646      if( pTrig->pTabSchema==pTab->pSchema
94647       && 0==sqlite3StrICmp(pTrig->table, pTab->zName)
94648      ){
94649        pTrig->pNext = (pList ? pList : pTab->pTrigger);
94650        pList = pTrig;
94651      }
94652    }
94653  }
94654
94655  return (pList ? pList : pTab->pTrigger);
94656}
94657
94658/*
94659** This is called by the parser when it sees a CREATE TRIGGER statement
94660** up to the point of the BEGIN before the trigger actions.  A Trigger
94661** structure is generated based on the information available and stored
94662** in pParse->pNewTrigger.  After the trigger actions have been parsed, the
94663** sqlite3FinishTrigger() function is called to complete the trigger
94664** construction process.
94665*/
94666SQLITE_PRIVATE void sqlite3BeginTrigger(
94667  Parse *pParse,      /* The parse context of the CREATE TRIGGER statement */
94668  Token *pName1,      /* The name of the trigger */
94669  Token *pName2,      /* The name of the trigger */
94670  int tr_tm,          /* One of TK_BEFORE, TK_AFTER, TK_INSTEAD */
94671  int op,             /* One of TK_INSERT, TK_UPDATE, TK_DELETE */
94672  IdList *pColumns,   /* column list if this is an UPDATE OF trigger */
94673  SrcList *pTableName,/* The name of the table/view the trigger applies to */
94674  Expr *pWhen,        /* WHEN clause */
94675  int isTemp,         /* True if the TEMPORARY keyword is present */
94676  int noErr           /* Suppress errors if the trigger already exists */
94677){
94678  Trigger *pTrigger = 0;  /* The new trigger */
94679  Table *pTab;            /* Table that the trigger fires off of */
94680  char *zName = 0;        /* Name of the trigger */
94681  sqlite3 *db = pParse->db;  /* The database connection */
94682  int iDb;                /* The database to store the trigger in */
94683  Token *pName;           /* The unqualified db name */
94684  DbFixer sFix;           /* State vector for the DB fixer */
94685  int iTabDb;             /* Index of the database holding pTab */
94686
94687  assert( pName1!=0 );   /* pName1->z might be NULL, but not pName1 itself */
94688  assert( pName2!=0 );
94689  assert( op==TK_INSERT || op==TK_UPDATE || op==TK_DELETE );
94690  assert( op>0 && op<0xff );
94691  if( isTemp ){
94692    /* If TEMP was specified, then the trigger name may not be qualified. */
94693    if( pName2->n>0 ){
94694      sqlite3ErrorMsg(pParse, "temporary trigger may not have qualified name");
94695      goto trigger_cleanup;
94696    }
94697    iDb = 1;
94698    pName = pName1;
94699  }else{
94700    /* Figure out the db that the the trigger will be created in */
94701    iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
94702    if( iDb<0 ){
94703      goto trigger_cleanup;
94704    }
94705  }
94706
94707  /* If the trigger name was unqualified, and the table is a temp table,
94708  ** then set iDb to 1 to create the trigger in the temporary database.
94709  ** If sqlite3SrcListLookup() returns 0, indicating the table does not
94710  ** exist, the error is caught by the block below.
94711  */
94712  if( !pTableName || db->mallocFailed ){
94713    goto trigger_cleanup;
94714  }
94715  pTab = sqlite3SrcListLookup(pParse, pTableName);
94716  if( db->init.busy==0 && pName2->n==0 && pTab
94717        && pTab->pSchema==db->aDb[1].pSchema ){
94718    iDb = 1;
94719  }
94720
94721  /* Ensure the table name matches database name and that the table exists */
94722  if( db->mallocFailed ) goto trigger_cleanup;
94723  assert( pTableName->nSrc==1 );
94724  if( sqlite3FixInit(&sFix, pParse, iDb, "trigger", pName) &&
94725      sqlite3FixSrcList(&sFix, pTableName) ){
94726    goto trigger_cleanup;
94727  }
94728  pTab = sqlite3SrcListLookup(pParse, pTableName);
94729  if( !pTab ){
94730    /* The table does not exist. */
94731    if( db->init.iDb==1 ){
94732      /* Ticket #3810.
94733      ** Normally, whenever a table is dropped, all associated triggers are
94734      ** dropped too.  But if a TEMP trigger is created on a non-TEMP table
94735      ** and the table is dropped by a different database connection, the
94736      ** trigger is not visible to the database connection that does the
94737      ** drop so the trigger cannot be dropped.  This results in an
94738      ** "orphaned trigger" - a trigger whose associated table is missing.
94739      */
94740      db->init.orphanTrigger = 1;
94741    }
94742    goto trigger_cleanup;
94743  }
94744  if( IsVirtual(pTab) ){
94745    sqlite3ErrorMsg(pParse, "cannot create triggers on virtual tables");
94746    goto trigger_cleanup;
94747  }
94748
94749  /* Check that the trigger name is not reserved and that no trigger of the
94750  ** specified name exists */
94751  zName = sqlite3NameFromToken(db, pName);
94752  if( !zName || SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
94753    goto trigger_cleanup;
94754  }
94755  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
94756  if( sqlite3HashFind(&(db->aDb[iDb].pSchema->trigHash),
94757                      zName, sqlite3Strlen30(zName)) ){
94758    if( !noErr ){
94759      sqlite3ErrorMsg(pParse, "trigger %T already exists", pName);
94760    }else{
94761      assert( !db->init.busy );
94762      sqlite3CodeVerifySchema(pParse, iDb);
94763    }
94764    goto trigger_cleanup;
94765  }
94766
94767  /* Do not create a trigger on a system table */
94768  if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 ){
94769    sqlite3ErrorMsg(pParse, "cannot create trigger on system table");
94770    pParse->nErr++;
94771    goto trigger_cleanup;
94772  }
94773
94774  /* INSTEAD of triggers are only for views and views only support INSTEAD
94775  ** of triggers.
94776  */
94777  if( pTab->pSelect && tr_tm!=TK_INSTEAD ){
94778    sqlite3ErrorMsg(pParse, "cannot create %s trigger on view: %S",
94779        (tr_tm == TK_BEFORE)?"BEFORE":"AFTER", pTableName, 0);
94780    goto trigger_cleanup;
94781  }
94782  if( !pTab->pSelect && tr_tm==TK_INSTEAD ){
94783    sqlite3ErrorMsg(pParse, "cannot create INSTEAD OF"
94784        " trigger on table: %S", pTableName, 0);
94785    goto trigger_cleanup;
94786  }
94787  iTabDb = sqlite3SchemaToIndex(db, pTab->pSchema);
94788
94789#ifndef SQLITE_OMIT_AUTHORIZATION
94790  {
94791    int code = SQLITE_CREATE_TRIGGER;
94792    const char *zDb = db->aDb[iTabDb].zName;
94793    const char *zDbTrig = isTemp ? db->aDb[1].zName : zDb;
94794    if( iTabDb==1 || isTemp ) code = SQLITE_CREATE_TEMP_TRIGGER;
94795    if( sqlite3AuthCheck(pParse, code, zName, pTab->zName, zDbTrig) ){
94796      goto trigger_cleanup;
94797    }
94798    if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iTabDb),0,zDb)){
94799      goto trigger_cleanup;
94800    }
94801  }
94802#endif
94803
94804  /* INSTEAD OF triggers can only appear on views and BEFORE triggers
94805  ** cannot appear on views.  So we might as well translate every
94806  ** INSTEAD OF trigger into a BEFORE trigger.  It simplifies code
94807  ** elsewhere.
94808  */
94809  if (tr_tm == TK_INSTEAD){
94810    tr_tm = TK_BEFORE;
94811  }
94812
94813  /* Build the Trigger object */
94814  pTrigger = (Trigger*)sqlite3DbMallocZero(db, sizeof(Trigger));
94815  if( pTrigger==0 ) goto trigger_cleanup;
94816  pTrigger->zName = zName;
94817  zName = 0;
94818  pTrigger->table = sqlite3DbStrDup(db, pTableName->a[0].zName);
94819  pTrigger->pSchema = db->aDb[iDb].pSchema;
94820  pTrigger->pTabSchema = pTab->pSchema;
94821  pTrigger->op = (u8)op;
94822  pTrigger->tr_tm = tr_tm==TK_BEFORE ? TRIGGER_BEFORE : TRIGGER_AFTER;
94823  pTrigger->pWhen = sqlite3ExprDup(db, pWhen, EXPRDUP_REDUCE);
94824  pTrigger->pColumns = sqlite3IdListDup(db, pColumns);
94825  assert( pParse->pNewTrigger==0 );
94826  pParse->pNewTrigger = pTrigger;
94827
94828trigger_cleanup:
94829  sqlite3DbFree(db, zName);
94830  sqlite3SrcListDelete(db, pTableName);
94831  sqlite3IdListDelete(db, pColumns);
94832  sqlite3ExprDelete(db, pWhen);
94833  if( !pParse->pNewTrigger ){
94834    sqlite3DeleteTrigger(db, pTrigger);
94835  }else{
94836    assert( pParse->pNewTrigger==pTrigger );
94837  }
94838}
94839
94840/*
94841** This routine is called after all of the trigger actions have been parsed
94842** in order to complete the process of building the trigger.
94843*/
94844SQLITE_PRIVATE void sqlite3FinishTrigger(
94845  Parse *pParse,          /* Parser context */
94846  TriggerStep *pStepList, /* The triggered program */
94847  Token *pAll             /* Token that describes the complete CREATE TRIGGER */
94848){
94849  Trigger *pTrig = pParse->pNewTrigger;   /* Trigger being finished */
94850  char *zName;                            /* Name of trigger */
94851  sqlite3 *db = pParse->db;               /* The database */
94852  DbFixer sFix;                           /* Fixer object */
94853  int iDb;                                /* Database containing the trigger */
94854  Token nameToken;                        /* Trigger name for error reporting */
94855
94856  pParse->pNewTrigger = 0;
94857  if( NEVER(pParse->nErr) || !pTrig ) goto triggerfinish_cleanup;
94858  zName = pTrig->zName;
94859  iDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema);
94860  pTrig->step_list = pStepList;
94861  while( pStepList ){
94862    pStepList->pTrig = pTrig;
94863    pStepList = pStepList->pNext;
94864  }
94865  nameToken.z = pTrig->zName;
94866  nameToken.n = sqlite3Strlen30(nameToken.z);
94867  if( sqlite3FixInit(&sFix, pParse, iDb, "trigger", &nameToken)
94868          && sqlite3FixTriggerStep(&sFix, pTrig->step_list) ){
94869    goto triggerfinish_cleanup;
94870  }
94871
94872  /* if we are not initializing,
94873  ** build the sqlite_master entry
94874  */
94875  if( !db->init.busy ){
94876    Vdbe *v;
94877    char *z;
94878
94879    /* Make an entry in the sqlite_master table */
94880    v = sqlite3GetVdbe(pParse);
94881    if( v==0 ) goto triggerfinish_cleanup;
94882    sqlite3BeginWriteOperation(pParse, 0, iDb);
94883    z = sqlite3DbStrNDup(db, (char*)pAll->z, pAll->n);
94884    sqlite3NestedParse(pParse,
94885       "INSERT INTO %Q.%s VALUES('trigger',%Q,%Q,0,'CREATE TRIGGER %q')",
94886       db->aDb[iDb].zName, SCHEMA_TABLE(iDb), zName,
94887       pTrig->table, z);
94888    sqlite3DbFree(db, z);
94889    sqlite3ChangeCookie(pParse, iDb);
94890    sqlite3VdbeAddOp4(v, OP_ParseSchema, iDb, 0, 0, sqlite3MPrintf(
94891        db, "type='trigger' AND name='%q'", zName), P4_DYNAMIC
94892    );
94893  }
94894
94895  if( db->init.busy ){
94896    Trigger *pLink = pTrig;
94897    Hash *pHash = &db->aDb[iDb].pSchema->trigHash;
94898    assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
94899    pTrig = sqlite3HashInsert(pHash, zName, sqlite3Strlen30(zName), pTrig);
94900    if( pTrig ){
94901      db->mallocFailed = 1;
94902    }else if( pLink->pSchema==pLink->pTabSchema ){
94903      Table *pTab;
94904      int n = sqlite3Strlen30(pLink->table);
94905      pTab = sqlite3HashFind(&pLink->pTabSchema->tblHash, pLink->table, n);
94906      assert( pTab!=0 );
94907      pLink->pNext = pTab->pTrigger;
94908      pTab->pTrigger = pLink;
94909    }
94910  }
94911
94912triggerfinish_cleanup:
94913  sqlite3DeleteTrigger(db, pTrig);
94914  assert( !pParse->pNewTrigger );
94915  sqlite3DeleteTriggerStep(db, pStepList);
94916}
94917
94918/*
94919** Turn a SELECT statement (that the pSelect parameter points to) into
94920** a trigger step.  Return a pointer to a TriggerStep structure.
94921**
94922** The parser calls this routine when it finds a SELECT statement in
94923** body of a TRIGGER.
94924*/
94925SQLITE_PRIVATE TriggerStep *sqlite3TriggerSelectStep(sqlite3 *db, Select *pSelect){
94926  TriggerStep *pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep));
94927  if( pTriggerStep==0 ) {
94928    sqlite3SelectDelete(db, pSelect);
94929    return 0;
94930  }
94931  pTriggerStep->op = TK_SELECT;
94932  pTriggerStep->pSelect = pSelect;
94933  pTriggerStep->orconf = OE_Default;
94934  return pTriggerStep;
94935}
94936
94937/*
94938** Allocate space to hold a new trigger step.  The allocated space
94939** holds both the TriggerStep object and the TriggerStep.target.z string.
94940**
94941** If an OOM error occurs, NULL is returned and db->mallocFailed is set.
94942*/
94943static TriggerStep *triggerStepAllocate(
94944  sqlite3 *db,                /* Database connection */
94945  u8 op,                      /* Trigger opcode */
94946  Token *pName                /* The target name */
94947){
94948  TriggerStep *pTriggerStep;
94949
94950  pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep) + pName->n);
94951  if( pTriggerStep ){
94952    char *z = (char*)&pTriggerStep[1];
94953    memcpy(z, pName->z, pName->n);
94954    pTriggerStep->target.z = z;
94955    pTriggerStep->target.n = pName->n;
94956    pTriggerStep->op = op;
94957  }
94958  return pTriggerStep;
94959}
94960
94961/*
94962** Build a trigger step out of an INSERT statement.  Return a pointer
94963** to the new trigger step.
94964**
94965** The parser calls this routine when it sees an INSERT inside the
94966** body of a trigger.
94967*/
94968SQLITE_PRIVATE TriggerStep *sqlite3TriggerInsertStep(
94969  sqlite3 *db,        /* The database connection */
94970  Token *pTableName,  /* Name of the table into which we insert */
94971  IdList *pColumn,    /* List of columns in pTableName to insert into */
94972  ExprList *pEList,   /* The VALUE clause: a list of values to be inserted */
94973  Select *pSelect,    /* A SELECT statement that supplies values */
94974  u8 orconf           /* The conflict algorithm (OE_Abort, OE_Replace, etc.) */
94975){
94976  TriggerStep *pTriggerStep;
94977
94978  assert(pEList == 0 || pSelect == 0);
94979  assert(pEList != 0 || pSelect != 0 || db->mallocFailed);
94980
94981  pTriggerStep = triggerStepAllocate(db, TK_INSERT, pTableName);
94982  if( pTriggerStep ){
94983    pTriggerStep->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
94984    pTriggerStep->pIdList = pColumn;
94985    pTriggerStep->pExprList = sqlite3ExprListDup(db, pEList, EXPRDUP_REDUCE);
94986    pTriggerStep->orconf = orconf;
94987  }else{
94988    sqlite3IdListDelete(db, pColumn);
94989  }
94990  sqlite3ExprListDelete(db, pEList);
94991  sqlite3SelectDelete(db, pSelect);
94992
94993  return pTriggerStep;
94994}
94995
94996/*
94997** Construct a trigger step that implements an UPDATE statement and return
94998** a pointer to that trigger step.  The parser calls this routine when it
94999** sees an UPDATE statement inside the body of a CREATE TRIGGER.
95000*/
95001SQLITE_PRIVATE TriggerStep *sqlite3TriggerUpdateStep(
95002  sqlite3 *db,         /* The database connection */
95003  Token *pTableName,   /* Name of the table to be updated */
95004  ExprList *pEList,    /* The SET clause: list of column and new values */
95005  Expr *pWhere,        /* The WHERE clause */
95006  u8 orconf            /* The conflict algorithm. (OE_Abort, OE_Ignore, etc) */
95007){
95008  TriggerStep *pTriggerStep;
95009
95010  pTriggerStep = triggerStepAllocate(db, TK_UPDATE, pTableName);
95011  if( pTriggerStep ){
95012    pTriggerStep->pExprList = sqlite3ExprListDup(db, pEList, EXPRDUP_REDUCE);
95013    pTriggerStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
95014    pTriggerStep->orconf = orconf;
95015  }
95016  sqlite3ExprListDelete(db, pEList);
95017  sqlite3ExprDelete(db, pWhere);
95018  return pTriggerStep;
95019}
95020
95021/*
95022** Construct a trigger step that implements a DELETE statement and return
95023** a pointer to that trigger step.  The parser calls this routine when it
95024** sees a DELETE statement inside the body of a CREATE TRIGGER.
95025*/
95026SQLITE_PRIVATE TriggerStep *sqlite3TriggerDeleteStep(
95027  sqlite3 *db,            /* Database connection */
95028  Token *pTableName,      /* The table from which rows are deleted */
95029  Expr *pWhere            /* The WHERE clause */
95030){
95031  TriggerStep *pTriggerStep;
95032
95033  pTriggerStep = triggerStepAllocate(db, TK_DELETE, pTableName);
95034  if( pTriggerStep ){
95035    pTriggerStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
95036    pTriggerStep->orconf = OE_Default;
95037  }
95038  sqlite3ExprDelete(db, pWhere);
95039  return pTriggerStep;
95040}
95041
95042/*
95043** Recursively delete a Trigger structure
95044*/
95045SQLITE_PRIVATE void sqlite3DeleteTrigger(sqlite3 *db, Trigger *pTrigger){
95046  if( pTrigger==0 ) return;
95047  sqlite3DeleteTriggerStep(db, pTrigger->step_list);
95048  sqlite3DbFree(db, pTrigger->zName);
95049  sqlite3DbFree(db, pTrigger->table);
95050  sqlite3ExprDelete(db, pTrigger->pWhen);
95051  sqlite3IdListDelete(db, pTrigger->pColumns);
95052  sqlite3DbFree(db, pTrigger);
95053}
95054
95055/*
95056** This function is called to drop a trigger from the database schema.
95057**
95058** This may be called directly from the parser and therefore identifies
95059** the trigger by name.  The sqlite3DropTriggerPtr() routine does the
95060** same job as this routine except it takes a pointer to the trigger
95061** instead of the trigger name.
95062**/
95063SQLITE_PRIVATE void sqlite3DropTrigger(Parse *pParse, SrcList *pName, int noErr){
95064  Trigger *pTrigger = 0;
95065  int i;
95066  const char *zDb;
95067  const char *zName;
95068  int nName;
95069  sqlite3 *db = pParse->db;
95070
95071  if( db->mallocFailed ) goto drop_trigger_cleanup;
95072  if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
95073    goto drop_trigger_cleanup;
95074  }
95075
95076  assert( pName->nSrc==1 );
95077  zDb = pName->a[0].zDatabase;
95078  zName = pName->a[0].zName;
95079  nName = sqlite3Strlen30(zName);
95080  assert( zDb!=0 || sqlite3BtreeHoldsAllMutexes(db) );
95081  for(i=OMIT_TEMPDB; i<db->nDb; i++){
95082    int j = (i<2) ? i^1 : i;  /* Search TEMP before MAIN */
95083    if( zDb && sqlite3StrICmp(db->aDb[j].zName, zDb) ) continue;
95084    assert( sqlite3SchemaMutexHeld(db, j, 0) );
95085    pTrigger = sqlite3HashFind(&(db->aDb[j].pSchema->trigHash), zName, nName);
95086    if( pTrigger ) break;
95087  }
95088  if( !pTrigger ){
95089    if( !noErr ){
95090      sqlite3ErrorMsg(pParse, "no such trigger: %S", pName, 0);
95091    }else{
95092      sqlite3CodeVerifyNamedSchema(pParse, zDb);
95093    }
95094    pParse->checkSchema = 1;
95095    goto drop_trigger_cleanup;
95096  }
95097  sqlite3DropTriggerPtr(pParse, pTrigger);
95098
95099drop_trigger_cleanup:
95100  sqlite3SrcListDelete(db, pName);
95101}
95102
95103/*
95104** Return a pointer to the Table structure for the table that a trigger
95105** is set on.
95106*/
95107static Table *tableOfTrigger(Trigger *pTrigger){
95108  int n = sqlite3Strlen30(pTrigger->table);
95109  return sqlite3HashFind(&pTrigger->pTabSchema->tblHash, pTrigger->table, n);
95110}
95111
95112
95113/*
95114** Drop a trigger given a pointer to that trigger.
95115*/
95116SQLITE_PRIVATE void sqlite3DropTriggerPtr(Parse *pParse, Trigger *pTrigger){
95117  Table   *pTable;
95118  Vdbe *v;
95119  sqlite3 *db = pParse->db;
95120  int iDb;
95121
95122  iDb = sqlite3SchemaToIndex(pParse->db, pTrigger->pSchema);
95123  assert( iDb>=0 && iDb<db->nDb );
95124  pTable = tableOfTrigger(pTrigger);
95125  assert( pTable );
95126  assert( pTable->pSchema==pTrigger->pSchema || iDb==1 );
95127#ifndef SQLITE_OMIT_AUTHORIZATION
95128  {
95129    int code = SQLITE_DROP_TRIGGER;
95130    const char *zDb = db->aDb[iDb].zName;
95131    const char *zTab = SCHEMA_TABLE(iDb);
95132    if( iDb==1 ) code = SQLITE_DROP_TEMP_TRIGGER;
95133    if( sqlite3AuthCheck(pParse, code, pTrigger->zName, pTable->zName, zDb) ||
95134      sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
95135      return;
95136    }
95137  }
95138#endif
95139
95140  /* Generate code to destroy the database record of the trigger.
95141  */
95142  assert( pTable!=0 );
95143  if( (v = sqlite3GetVdbe(pParse))!=0 ){
95144    int base;
95145    static const VdbeOpList dropTrigger[] = {
95146      { OP_Rewind,     0, ADDR(9),  0},
95147      { OP_String8,    0, 1,        0}, /* 1 */
95148      { OP_Column,     0, 1,        2},
95149      { OP_Ne,         2, ADDR(8),  1},
95150      { OP_String8,    0, 1,        0}, /* 4: "trigger" */
95151      { OP_Column,     0, 0,        2},
95152      { OP_Ne,         2, ADDR(8),  1},
95153      { OP_Delete,     0, 0,        0},
95154      { OP_Next,       0, ADDR(1),  0}, /* 8 */
95155    };
95156
95157    sqlite3BeginWriteOperation(pParse, 0, iDb);
95158    sqlite3OpenMasterTable(pParse, iDb);
95159    base = sqlite3VdbeAddOpList(v,  ArraySize(dropTrigger), dropTrigger);
95160    sqlite3VdbeChangeP4(v, base+1, pTrigger->zName, P4_TRANSIENT);
95161    sqlite3VdbeChangeP4(v, base+4, "trigger", P4_STATIC);
95162    sqlite3ChangeCookie(pParse, iDb);
95163    sqlite3VdbeAddOp2(v, OP_Close, 0, 0);
95164    sqlite3VdbeAddOp4(v, OP_DropTrigger, iDb, 0, 0, pTrigger->zName, 0);
95165    if( pParse->nMem<3 ){
95166      pParse->nMem = 3;
95167    }
95168  }
95169}
95170
95171/*
95172** Remove a trigger from the hash tables of the sqlite* pointer.
95173*/
95174SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTrigger(sqlite3 *db, int iDb, const char *zName){
95175  Trigger *pTrigger;
95176  Hash *pHash;
95177
95178  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
95179  pHash = &(db->aDb[iDb].pSchema->trigHash);
95180  pTrigger = sqlite3HashInsert(pHash, zName, sqlite3Strlen30(zName), 0);
95181  if( ALWAYS(pTrigger) ){
95182    if( pTrigger->pSchema==pTrigger->pTabSchema ){
95183      Table *pTab = tableOfTrigger(pTrigger);
95184      Trigger **pp;
95185      for(pp=&pTab->pTrigger; *pp!=pTrigger; pp=&((*pp)->pNext));
95186      *pp = (*pp)->pNext;
95187    }
95188    sqlite3DeleteTrigger(db, pTrigger);
95189    db->flags |= SQLITE_InternChanges;
95190  }
95191}
95192
95193/*
95194** pEList is the SET clause of an UPDATE statement.  Each entry
95195** in pEList is of the format <id>=<expr>.  If any of the entries
95196** in pEList have an <id> which matches an identifier in pIdList,
95197** then return TRUE.  If pIdList==NULL, then it is considered a
95198** wildcard that matches anything.  Likewise if pEList==NULL then
95199** it matches anything so always return true.  Return false only
95200** if there is no match.
95201*/
95202static int checkColumnOverlap(IdList *pIdList, ExprList *pEList){
95203  int e;
95204  if( pIdList==0 || NEVER(pEList==0) ) return 1;
95205  for(e=0; e<pEList->nExpr; e++){
95206    if( sqlite3IdListIndex(pIdList, pEList->a[e].zName)>=0 ) return 1;
95207  }
95208  return 0;
95209}
95210
95211/*
95212** Return a list of all triggers on table pTab if there exists at least
95213** one trigger that must be fired when an operation of type 'op' is
95214** performed on the table, and, if that operation is an UPDATE, if at
95215** least one of the columns in pChanges is being modified.
95216*/
95217SQLITE_PRIVATE Trigger *sqlite3TriggersExist(
95218  Parse *pParse,          /* Parse context */
95219  Table *pTab,            /* The table the contains the triggers */
95220  int op,                 /* one of TK_DELETE, TK_INSERT, TK_UPDATE */
95221  ExprList *pChanges,     /* Columns that change in an UPDATE statement */
95222  int *pMask              /* OUT: Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
95223){
95224  int mask = 0;
95225  Trigger *pList = 0;
95226  Trigger *p;
95227
95228  if( (pParse->db->flags & SQLITE_EnableTrigger)!=0 ){
95229    pList = sqlite3TriggerList(pParse, pTab);
95230  }
95231  assert( pList==0 || IsVirtual(pTab)==0 );
95232  for(p=pList; p; p=p->pNext){
95233    if( p->op==op && checkColumnOverlap(p->pColumns, pChanges) ){
95234      mask |= p->tr_tm;
95235    }
95236  }
95237  if( pMask ){
95238    *pMask = mask;
95239  }
95240  return (mask ? pList : 0);
95241}
95242
95243/*
95244** Convert the pStep->target token into a SrcList and return a pointer
95245** to that SrcList.
95246**
95247** This routine adds a specific database name, if needed, to the target when
95248** forming the SrcList.  This prevents a trigger in one database from
95249** referring to a target in another database.  An exception is when the
95250** trigger is in TEMP in which case it can refer to any other database it
95251** wants.
95252*/
95253static SrcList *targetSrcList(
95254  Parse *pParse,       /* The parsing context */
95255  TriggerStep *pStep   /* The trigger containing the target token */
95256){
95257  int iDb;             /* Index of the database to use */
95258  SrcList *pSrc;       /* SrcList to be returned */
95259
95260  pSrc = sqlite3SrcListAppend(pParse->db, 0, &pStep->target, 0);
95261  if( pSrc ){
95262    assert( pSrc->nSrc>0 );
95263    assert( pSrc->a!=0 );
95264    iDb = sqlite3SchemaToIndex(pParse->db, pStep->pTrig->pSchema);
95265    if( iDb==0 || iDb>=2 ){
95266      sqlite3 *db = pParse->db;
95267      assert( iDb<pParse->db->nDb );
95268      pSrc->a[pSrc->nSrc-1].zDatabase = sqlite3DbStrDup(db, db->aDb[iDb].zName);
95269    }
95270  }
95271  return pSrc;
95272}
95273
95274/*
95275** Generate VDBE code for the statements inside the body of a single
95276** trigger.
95277*/
95278static int codeTriggerProgram(
95279  Parse *pParse,            /* The parser context */
95280  TriggerStep *pStepList,   /* List of statements inside the trigger body */
95281  int orconf                /* Conflict algorithm. (OE_Abort, etc) */
95282){
95283  TriggerStep *pStep;
95284  Vdbe *v = pParse->pVdbe;
95285  sqlite3 *db = pParse->db;
95286
95287  assert( pParse->pTriggerTab && pParse->pToplevel );
95288  assert( pStepList );
95289  assert( v!=0 );
95290  for(pStep=pStepList; pStep; pStep=pStep->pNext){
95291    /* Figure out the ON CONFLICT policy that will be used for this step
95292    ** of the trigger program. If the statement that caused this trigger
95293    ** to fire had an explicit ON CONFLICT, then use it. Otherwise, use
95294    ** the ON CONFLICT policy that was specified as part of the trigger
95295    ** step statement. Example:
95296    **
95297    **   CREATE TRIGGER AFTER INSERT ON t1 BEGIN;
95298    **     INSERT OR REPLACE INTO t2 VALUES(new.a, new.b);
95299    **   END;
95300    **
95301    **   INSERT INTO t1 ... ;            -- insert into t2 uses REPLACE policy
95302    **   INSERT OR IGNORE INTO t1 ... ;  -- insert into t2 uses IGNORE policy
95303    */
95304    pParse->eOrconf = (orconf==OE_Default)?pStep->orconf:(u8)orconf;
95305
95306    switch( pStep->op ){
95307      case TK_UPDATE: {
95308        sqlite3Update(pParse,
95309          targetSrcList(pParse, pStep),
95310          sqlite3ExprListDup(db, pStep->pExprList, 0),
95311          sqlite3ExprDup(db, pStep->pWhere, 0),
95312          pParse->eOrconf
95313        );
95314        break;
95315      }
95316      case TK_INSERT: {
95317        sqlite3Insert(pParse,
95318          targetSrcList(pParse, pStep),
95319          sqlite3ExprListDup(db, pStep->pExprList, 0),
95320          sqlite3SelectDup(db, pStep->pSelect, 0),
95321          sqlite3IdListDup(db, pStep->pIdList),
95322          pParse->eOrconf
95323        );
95324        break;
95325      }
95326      case TK_DELETE: {
95327        sqlite3DeleteFrom(pParse,
95328          targetSrcList(pParse, pStep),
95329          sqlite3ExprDup(db, pStep->pWhere, 0)
95330        );
95331        break;
95332      }
95333      default: assert( pStep->op==TK_SELECT ); {
95334        SelectDest sDest;
95335        Select *pSelect = sqlite3SelectDup(db, pStep->pSelect, 0);
95336        sqlite3SelectDestInit(&sDest, SRT_Discard, 0);
95337        sqlite3Select(pParse, pSelect, &sDest);
95338        sqlite3SelectDelete(db, pSelect);
95339        break;
95340      }
95341    }
95342    if( pStep->op!=TK_SELECT ){
95343      sqlite3VdbeAddOp0(v, OP_ResetCount);
95344    }
95345  }
95346
95347  return 0;
95348}
95349
95350#ifdef SQLITE_DEBUG
95351/*
95352** This function is used to add VdbeComment() annotations to a VDBE
95353** program. It is not used in production code, only for debugging.
95354*/
95355static const char *onErrorText(int onError){
95356  switch( onError ){
95357    case OE_Abort:    return "abort";
95358    case OE_Rollback: return "rollback";
95359    case OE_Fail:     return "fail";
95360    case OE_Replace:  return "replace";
95361    case OE_Ignore:   return "ignore";
95362    case OE_Default:  return "default";
95363  }
95364  return "n/a";
95365}
95366#endif
95367
95368/*
95369** Parse context structure pFrom has just been used to create a sub-vdbe
95370** (trigger program). If an error has occurred, transfer error information
95371** from pFrom to pTo.
95372*/
95373static void transferParseError(Parse *pTo, Parse *pFrom){
95374  assert( pFrom->zErrMsg==0 || pFrom->nErr );
95375  assert( pTo->zErrMsg==0 || pTo->nErr );
95376  if( pTo->nErr==0 ){
95377    pTo->zErrMsg = pFrom->zErrMsg;
95378    pTo->nErr = pFrom->nErr;
95379  }else{
95380    sqlite3DbFree(pFrom->db, pFrom->zErrMsg);
95381  }
95382}
95383
95384/*
95385** Create and populate a new TriggerPrg object with a sub-program
95386** implementing trigger pTrigger with ON CONFLICT policy orconf.
95387*/
95388static TriggerPrg *codeRowTrigger(
95389  Parse *pParse,       /* Current parse context */
95390  Trigger *pTrigger,   /* Trigger to code */
95391  Table *pTab,         /* The table pTrigger is attached to */
95392  int orconf           /* ON CONFLICT policy to code trigger program with */
95393){
95394  Parse *pTop = sqlite3ParseToplevel(pParse);
95395  sqlite3 *db = pParse->db;   /* Database handle */
95396  TriggerPrg *pPrg;           /* Value to return */
95397  Expr *pWhen = 0;            /* Duplicate of trigger WHEN expression */
95398  Vdbe *v;                    /* Temporary VM */
95399  NameContext sNC;            /* Name context for sub-vdbe */
95400  SubProgram *pProgram = 0;   /* Sub-vdbe for trigger program */
95401  Parse *pSubParse;           /* Parse context for sub-vdbe */
95402  int iEndTrigger = 0;        /* Label to jump to if WHEN is false */
95403
95404  assert( pTrigger->zName==0 || pTab==tableOfTrigger(pTrigger) );
95405  assert( pTop->pVdbe );
95406
95407  /* Allocate the TriggerPrg and SubProgram objects. To ensure that they
95408  ** are freed if an error occurs, link them into the Parse.pTriggerPrg
95409  ** list of the top-level Parse object sooner rather than later.  */
95410  pPrg = sqlite3DbMallocZero(db, sizeof(TriggerPrg));
95411  if( !pPrg ) return 0;
95412  pPrg->pNext = pTop->pTriggerPrg;
95413  pTop->pTriggerPrg = pPrg;
95414  pPrg->pProgram = pProgram = sqlite3DbMallocZero(db, sizeof(SubProgram));
95415  if( !pProgram ) return 0;
95416  sqlite3VdbeLinkSubProgram(pTop->pVdbe, pProgram);
95417  pPrg->pTrigger = pTrigger;
95418  pPrg->orconf = orconf;
95419  pPrg->aColmask[0] = 0xffffffff;
95420  pPrg->aColmask[1] = 0xffffffff;
95421
95422  /* Allocate and populate a new Parse context to use for coding the
95423  ** trigger sub-program.  */
95424  pSubParse = sqlite3StackAllocZero(db, sizeof(Parse));
95425  if( !pSubParse ) return 0;
95426  memset(&sNC, 0, sizeof(sNC));
95427  sNC.pParse = pSubParse;
95428  pSubParse->db = db;
95429  pSubParse->pTriggerTab = pTab;
95430  pSubParse->pToplevel = pTop;
95431  pSubParse->zAuthContext = pTrigger->zName;
95432  pSubParse->eTriggerOp = pTrigger->op;
95433  pSubParse->nQueryLoop = pParse->nQueryLoop;
95434
95435  v = sqlite3GetVdbe(pSubParse);
95436  if( v ){
95437    VdbeComment((v, "Start: %s.%s (%s %s%s%s ON %s)",
95438      pTrigger->zName, onErrorText(orconf),
95439      (pTrigger->tr_tm==TRIGGER_BEFORE ? "BEFORE" : "AFTER"),
95440        (pTrigger->op==TK_UPDATE ? "UPDATE" : ""),
95441        (pTrigger->op==TK_INSERT ? "INSERT" : ""),
95442        (pTrigger->op==TK_DELETE ? "DELETE" : ""),
95443      pTab->zName
95444    ));
95445#ifndef SQLITE_OMIT_TRACE
95446    sqlite3VdbeChangeP4(v, -1,
95447      sqlite3MPrintf(db, "-- TRIGGER %s", pTrigger->zName), P4_DYNAMIC
95448    );
95449#endif
95450
95451    /* If one was specified, code the WHEN clause. If it evaluates to false
95452    ** (or NULL) the sub-vdbe is immediately halted by jumping to the
95453    ** OP_Halt inserted at the end of the program.  */
95454    if( pTrigger->pWhen ){
95455      pWhen = sqlite3ExprDup(db, pTrigger->pWhen, 0);
95456      if( SQLITE_OK==sqlite3ResolveExprNames(&sNC, pWhen)
95457       && db->mallocFailed==0
95458      ){
95459        iEndTrigger = sqlite3VdbeMakeLabel(v);
95460        sqlite3ExprIfFalse(pSubParse, pWhen, iEndTrigger, SQLITE_JUMPIFNULL);
95461      }
95462      sqlite3ExprDelete(db, pWhen);
95463    }
95464
95465    /* Code the trigger program into the sub-vdbe. */
95466    codeTriggerProgram(pSubParse, pTrigger->step_list, orconf);
95467
95468    /* Insert an OP_Halt at the end of the sub-program. */
95469    if( iEndTrigger ){
95470      sqlite3VdbeResolveLabel(v, iEndTrigger);
95471    }
95472    sqlite3VdbeAddOp0(v, OP_Halt);
95473    VdbeComment((v, "End: %s.%s", pTrigger->zName, onErrorText(orconf)));
95474
95475    transferParseError(pParse, pSubParse);
95476    if( db->mallocFailed==0 ){
95477      pProgram->aOp = sqlite3VdbeTakeOpArray(v, &pProgram->nOp, &pTop->nMaxArg);
95478    }
95479    pProgram->nMem = pSubParse->nMem;
95480    pProgram->nCsr = pSubParse->nTab;
95481    pProgram->token = (void *)pTrigger;
95482    pPrg->aColmask[0] = pSubParse->oldmask;
95483    pPrg->aColmask[1] = pSubParse->newmask;
95484    sqlite3VdbeDelete(v);
95485  }
95486
95487  assert( !pSubParse->pAinc       && !pSubParse->pZombieTab );
95488  assert( !pSubParse->pTriggerPrg && !pSubParse->nMaxArg );
95489  sqlite3StackFree(db, pSubParse);
95490
95491  return pPrg;
95492}
95493
95494/*
95495** Return a pointer to a TriggerPrg object containing the sub-program for
95496** trigger pTrigger with default ON CONFLICT algorithm orconf. If no such
95497** TriggerPrg object exists, a new object is allocated and populated before
95498** being returned.
95499*/
95500static TriggerPrg *getRowTrigger(
95501  Parse *pParse,       /* Current parse context */
95502  Trigger *pTrigger,   /* Trigger to code */
95503  Table *pTab,         /* The table trigger pTrigger is attached to */
95504  int orconf           /* ON CONFLICT algorithm. */
95505){
95506  Parse *pRoot = sqlite3ParseToplevel(pParse);
95507  TriggerPrg *pPrg;
95508
95509  assert( pTrigger->zName==0 || pTab==tableOfTrigger(pTrigger) );
95510
95511  /* It may be that this trigger has already been coded (or is in the
95512  ** process of being coded). If this is the case, then an entry with
95513  ** a matching TriggerPrg.pTrigger field will be present somewhere
95514  ** in the Parse.pTriggerPrg list. Search for such an entry.  */
95515  for(pPrg=pRoot->pTriggerPrg;
95516      pPrg && (pPrg->pTrigger!=pTrigger || pPrg->orconf!=orconf);
95517      pPrg=pPrg->pNext
95518  );
95519
95520  /* If an existing TriggerPrg could not be located, create a new one. */
95521  if( !pPrg ){
95522    pPrg = codeRowTrigger(pParse, pTrigger, pTab, orconf);
95523  }
95524
95525  return pPrg;
95526}
95527
95528/*
95529** Generate code for the trigger program associated with trigger p on
95530** table pTab. The reg, orconf and ignoreJump parameters passed to this
95531** function are the same as those described in the header function for
95532** sqlite3CodeRowTrigger()
95533*/
95534SQLITE_PRIVATE void sqlite3CodeRowTriggerDirect(
95535  Parse *pParse,       /* Parse context */
95536  Trigger *p,          /* Trigger to code */
95537  Table *pTab,         /* The table to code triggers from */
95538  int reg,             /* Reg array containing OLD.* and NEW.* values */
95539  int orconf,          /* ON CONFLICT policy */
95540  int ignoreJump       /* Instruction to jump to for RAISE(IGNORE) */
95541){
95542  Vdbe *v = sqlite3GetVdbe(pParse); /* Main VM */
95543  TriggerPrg *pPrg;
95544  pPrg = getRowTrigger(pParse, p, pTab, orconf);
95545  assert( pPrg || pParse->nErr || pParse->db->mallocFailed );
95546
95547  /* Code the OP_Program opcode in the parent VDBE. P4 of the OP_Program
95548  ** is a pointer to the sub-vdbe containing the trigger program.  */
95549  if( pPrg ){
95550    int bRecursive = (p->zName && 0==(pParse->db->flags&SQLITE_RecTriggers));
95551
95552    sqlite3VdbeAddOp3(v, OP_Program, reg, ignoreJump, ++pParse->nMem);
95553    sqlite3VdbeChangeP4(v, -1, (const char *)pPrg->pProgram, P4_SUBPROGRAM);
95554    VdbeComment(
95555        (v, "Call: %s.%s", (p->zName?p->zName:"fkey"), onErrorText(orconf)));
95556
95557    /* Set the P5 operand of the OP_Program instruction to non-zero if
95558    ** recursive invocation of this trigger program is disallowed. Recursive
95559    ** invocation is disallowed if (a) the sub-program is really a trigger,
95560    ** not a foreign key action, and (b) the flag to enable recursive triggers
95561    ** is clear.  */
95562    sqlite3VdbeChangeP5(v, (u8)bRecursive);
95563  }
95564}
95565
95566/*
95567** This is called to code the required FOR EACH ROW triggers for an operation
95568** on table pTab. The operation to code triggers for (INSERT, UPDATE or DELETE)
95569** is given by the op paramater. The tr_tm parameter determines whether the
95570** BEFORE or AFTER triggers are coded. If the operation is an UPDATE, then
95571** parameter pChanges is passed the list of columns being modified.
95572**
95573** If there are no triggers that fire at the specified time for the specified
95574** operation on pTab, this function is a no-op.
95575**
95576** The reg argument is the address of the first in an array of registers
95577** that contain the values substituted for the new.* and old.* references
95578** in the trigger program. If N is the number of columns in table pTab
95579** (a copy of pTab->nCol), then registers are populated as follows:
95580**
95581**   Register       Contains
95582**   ------------------------------------------------------
95583**   reg+0          OLD.rowid
95584**   reg+1          OLD.* value of left-most column of pTab
95585**   ...            ...
95586**   reg+N          OLD.* value of right-most column of pTab
95587**   reg+N+1        NEW.rowid
95588**   reg+N+2        OLD.* value of left-most column of pTab
95589**   ...            ...
95590**   reg+N+N+1      NEW.* value of right-most column of pTab
95591**
95592** For ON DELETE triggers, the registers containing the NEW.* values will
95593** never be accessed by the trigger program, so they are not allocated or
95594** populated by the caller (there is no data to populate them with anyway).
95595** Similarly, for ON INSERT triggers the values stored in the OLD.* registers
95596** are never accessed, and so are not allocated by the caller. So, for an
95597** ON INSERT trigger, the value passed to this function as parameter reg
95598** is not a readable register, although registers (reg+N) through
95599** (reg+N+N+1) are.
95600**
95601** Parameter orconf is the default conflict resolution algorithm for the
95602** trigger program to use (REPLACE, IGNORE etc.). Parameter ignoreJump
95603** is the instruction that control should jump to if a trigger program
95604** raises an IGNORE exception.
95605*/
95606SQLITE_PRIVATE void sqlite3CodeRowTrigger(
95607  Parse *pParse,       /* Parse context */
95608  Trigger *pTrigger,   /* List of triggers on table pTab */
95609  int op,              /* One of TK_UPDATE, TK_INSERT, TK_DELETE */
95610  ExprList *pChanges,  /* Changes list for any UPDATE OF triggers */
95611  int tr_tm,           /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
95612  Table *pTab,         /* The table to code triggers from */
95613  int reg,             /* The first in an array of registers (see above) */
95614  int orconf,          /* ON CONFLICT policy */
95615  int ignoreJump       /* Instruction to jump to for RAISE(IGNORE) */
95616){
95617  Trigger *p;          /* Used to iterate through pTrigger list */
95618
95619  assert( op==TK_UPDATE || op==TK_INSERT || op==TK_DELETE );
95620  assert( tr_tm==TRIGGER_BEFORE || tr_tm==TRIGGER_AFTER );
95621  assert( (op==TK_UPDATE)==(pChanges!=0) );
95622
95623  for(p=pTrigger; p; p=p->pNext){
95624
95625    /* Sanity checking:  The schema for the trigger and for the table are
95626    ** always defined.  The trigger must be in the same schema as the table
95627    ** or else it must be a TEMP trigger. */
95628    assert( p->pSchema!=0 );
95629    assert( p->pTabSchema!=0 );
95630    assert( p->pSchema==p->pTabSchema
95631         || p->pSchema==pParse->db->aDb[1].pSchema );
95632
95633    /* Determine whether we should code this trigger */
95634    if( p->op==op
95635     && p->tr_tm==tr_tm
95636     && checkColumnOverlap(p->pColumns, pChanges)
95637    ){
95638      sqlite3CodeRowTriggerDirect(pParse, p, pTab, reg, orconf, ignoreJump);
95639    }
95640  }
95641}
95642
95643/*
95644** Triggers may access values stored in the old.* or new.* pseudo-table.
95645** This function returns a 32-bit bitmask indicating which columns of the
95646** old.* or new.* tables actually are used by triggers. This information
95647** may be used by the caller, for example, to avoid having to load the entire
95648** old.* record into memory when executing an UPDATE or DELETE command.
95649**
95650** Bit 0 of the returned mask is set if the left-most column of the
95651** table may be accessed using an [old|new].<col> reference. Bit 1 is set if
95652** the second leftmost column value is required, and so on. If there
95653** are more than 32 columns in the table, and at least one of the columns
95654** with an index greater than 32 may be accessed, 0xffffffff is returned.
95655**
95656** It is not possible to determine if the old.rowid or new.rowid column is
95657** accessed by triggers. The caller must always assume that it is.
95658**
95659** Parameter isNew must be either 1 or 0. If it is 0, then the mask returned
95660** applies to the old.* table. If 1, the new.* table.
95661**
95662** Parameter tr_tm must be a mask with one or both of the TRIGGER_BEFORE
95663** and TRIGGER_AFTER bits set. Values accessed by BEFORE triggers are only
95664** included in the returned mask if the TRIGGER_BEFORE bit is set in the
95665** tr_tm parameter. Similarly, values accessed by AFTER triggers are only
95666** included in the returned mask if the TRIGGER_AFTER bit is set in tr_tm.
95667*/
95668SQLITE_PRIVATE u32 sqlite3TriggerColmask(
95669  Parse *pParse,       /* Parse context */
95670  Trigger *pTrigger,   /* List of triggers on table pTab */
95671  ExprList *pChanges,  /* Changes list for any UPDATE OF triggers */
95672  int isNew,           /* 1 for new.* ref mask, 0 for old.* ref mask */
95673  int tr_tm,           /* Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
95674  Table *pTab,         /* The table to code triggers from */
95675  int orconf           /* Default ON CONFLICT policy for trigger steps */
95676){
95677  const int op = pChanges ? TK_UPDATE : TK_DELETE;
95678  u32 mask = 0;
95679  Trigger *p;
95680
95681  assert( isNew==1 || isNew==0 );
95682  for(p=pTrigger; p; p=p->pNext){
95683    if( p->op==op && (tr_tm&p->tr_tm)
95684     && checkColumnOverlap(p->pColumns,pChanges)
95685    ){
95686      TriggerPrg *pPrg;
95687      pPrg = getRowTrigger(pParse, p, pTab, orconf);
95688      if( pPrg ){
95689        mask |= pPrg->aColmask[isNew];
95690      }
95691    }
95692  }
95693
95694  return mask;
95695}
95696
95697#endif /* !defined(SQLITE_OMIT_TRIGGER) */
95698
95699/************** End of trigger.c *********************************************/
95700/************** Begin file update.c ******************************************/
95701/*
95702** 2001 September 15
95703**
95704** The author disclaims copyright to this source code.  In place of
95705** a legal notice, here is a blessing:
95706**
95707**    May you do good and not evil.
95708**    May you find forgiveness for yourself and forgive others.
95709**    May you share freely, never taking more than you give.
95710**
95711*************************************************************************
95712** This file contains C code routines that are called by the parser
95713** to handle UPDATE statements.
95714*/
95715
95716#ifndef SQLITE_OMIT_VIRTUALTABLE
95717/* Forward declaration */
95718static void updateVirtualTable(
95719  Parse *pParse,       /* The parsing context */
95720  SrcList *pSrc,       /* The virtual table to be modified */
95721  Table *pTab,         /* The virtual table */
95722  ExprList *pChanges,  /* The columns to change in the UPDATE statement */
95723  Expr *pRowidExpr,    /* Expression used to recompute the rowid */
95724  int *aXRef,          /* Mapping from columns of pTab to entries in pChanges */
95725  Expr *pWhere         /* WHERE clause of the UPDATE statement */
95726);
95727#endif /* SQLITE_OMIT_VIRTUALTABLE */
95728
95729/*
95730** The most recently coded instruction was an OP_Column to retrieve the
95731** i-th column of table pTab. This routine sets the P4 parameter of the
95732** OP_Column to the default value, if any.
95733**
95734** The default value of a column is specified by a DEFAULT clause in the
95735** column definition. This was either supplied by the user when the table
95736** was created, or added later to the table definition by an ALTER TABLE
95737** command. If the latter, then the row-records in the table btree on disk
95738** may not contain a value for the column and the default value, taken
95739** from the P4 parameter of the OP_Column instruction, is returned instead.
95740** If the former, then all row-records are guaranteed to include a value
95741** for the column and the P4 value is not required.
95742**
95743** Column definitions created by an ALTER TABLE command may only have
95744** literal default values specified: a number, null or a string. (If a more
95745** complicated default expression value was provided, it is evaluated
95746** when the ALTER TABLE is executed and one of the literal values written
95747** into the sqlite_master table.)
95748**
95749** Therefore, the P4 parameter is only required if the default value for
95750** the column is a literal number, string or null. The sqlite3ValueFromExpr()
95751** function is capable of transforming these types of expressions into
95752** sqlite3_value objects.
95753**
95754** If parameter iReg is not negative, code an OP_RealAffinity instruction
95755** on register iReg. This is used when an equivalent integer value is
95756** stored in place of an 8-byte floating point value in order to save
95757** space.
95758*/
95759SQLITE_PRIVATE void sqlite3ColumnDefault(Vdbe *v, Table *pTab, int i, int iReg){
95760  assert( pTab!=0 );
95761  if( !pTab->pSelect ){
95762    sqlite3_value *pValue;
95763    u8 enc = ENC(sqlite3VdbeDb(v));
95764    Column *pCol = &pTab->aCol[i];
95765    VdbeComment((v, "%s.%s", pTab->zName, pCol->zName));
95766    assert( i<pTab->nCol );
95767    sqlite3ValueFromExpr(sqlite3VdbeDb(v), pCol->pDflt, enc,
95768                         pCol->affinity, &pValue);
95769    if( pValue ){
95770      sqlite3VdbeChangeP4(v, -1, (const char *)pValue, P4_MEM);
95771    }
95772#ifndef SQLITE_OMIT_FLOATING_POINT
95773    if( iReg>=0 && pTab->aCol[i].affinity==SQLITE_AFF_REAL ){
95774      sqlite3VdbeAddOp1(v, OP_RealAffinity, iReg);
95775    }
95776#endif
95777  }
95778}
95779
95780/*
95781** Process an UPDATE statement.
95782**
95783**   UPDATE OR IGNORE table_wxyz SET a=b, c=d WHERE e<5 AND f NOT NULL;
95784**          \_______/ \________/     \______/       \________________/
95785*            onError   pTabList      pChanges             pWhere
95786*/
95787SQLITE_PRIVATE void sqlite3Update(
95788  Parse *pParse,         /* The parser context */
95789  SrcList *pTabList,     /* The table in which we should change things */
95790  ExprList *pChanges,    /* Things to be changed */
95791  Expr *pWhere,          /* The WHERE clause.  May be null */
95792  int onError            /* How to handle constraint errors */
95793){
95794  int i, j;              /* Loop counters */
95795  Table *pTab;           /* The table to be updated */
95796  int addr = 0;          /* VDBE instruction address of the start of the loop */
95797  WhereInfo *pWInfo;     /* Information about the WHERE clause */
95798  Vdbe *v;               /* The virtual database engine */
95799  Index *pIdx;           /* For looping over indices */
95800  int nIdx;              /* Number of indices that need updating */
95801  int iCur;              /* VDBE Cursor number of pTab */
95802  sqlite3 *db;           /* The database structure */
95803  int *aRegIdx = 0;      /* One register assigned to each index to be updated */
95804  int *aXRef = 0;        /* aXRef[i] is the index in pChanges->a[] of the
95805                         ** an expression for the i-th column of the table.
95806                         ** aXRef[i]==-1 if the i-th column is not changed. */
95807  int chngRowid;         /* True if the record number is being changed */
95808  Expr *pRowidExpr = 0;  /* Expression defining the new record number */
95809  int openAll = 0;       /* True if all indices need to be opened */
95810  AuthContext sContext;  /* The authorization context */
95811  NameContext sNC;       /* The name-context to resolve expressions in */
95812  int iDb;               /* Database containing the table being updated */
95813  int okOnePass;         /* True for one-pass algorithm without the FIFO */
95814  int hasFK;             /* True if foreign key processing is required */
95815
95816#ifndef SQLITE_OMIT_TRIGGER
95817  int isView;            /* True when updating a view (INSTEAD OF trigger) */
95818  Trigger *pTrigger;     /* List of triggers on pTab, if required */
95819  int tmask;             /* Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
95820#endif
95821  int newmask;           /* Mask of NEW.* columns accessed by BEFORE triggers */
95822
95823  /* Register Allocations */
95824  int regRowCount = 0;   /* A count of rows changed */
95825  int regOldRowid;       /* The old rowid */
95826  int regNewRowid;       /* The new rowid */
95827  int regNew;
95828  int regOld = 0;
95829  int regRowSet = 0;     /* Rowset of rows to be updated */
95830
95831  memset(&sContext, 0, sizeof(sContext));
95832  db = pParse->db;
95833  if( pParse->nErr || db->mallocFailed ){
95834    goto update_cleanup;
95835  }
95836  assert( pTabList->nSrc==1 );
95837
95838  /* Locate the table which we want to update.
95839  */
95840  pTab = sqlite3SrcListLookup(pParse, pTabList);
95841  if( pTab==0 ) goto update_cleanup;
95842  iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
95843
95844  /* Figure out if we have any triggers and if the table being
95845  ** updated is a view.
95846  */
95847#ifndef SQLITE_OMIT_TRIGGER
95848  pTrigger = sqlite3TriggersExist(pParse, pTab, TK_UPDATE, pChanges, &tmask);
95849  isView = pTab->pSelect!=0;
95850  assert( pTrigger || tmask==0 );
95851#else
95852# define pTrigger 0
95853# define isView 0
95854# define tmask 0
95855#endif
95856#ifdef SQLITE_OMIT_VIEW
95857# undef isView
95858# define isView 0
95859#endif
95860
95861  if( sqlite3ViewGetColumnNames(pParse, pTab) ){
95862    goto update_cleanup;
95863  }
95864  if( sqlite3IsReadOnly(pParse, pTab, tmask) ){
95865    goto update_cleanup;
95866  }
95867  aXRef = sqlite3DbMallocRaw(db, sizeof(int) * pTab->nCol );
95868  if( aXRef==0 ) goto update_cleanup;
95869  for(i=0; i<pTab->nCol; i++) aXRef[i] = -1;
95870
95871  /* Allocate a cursors for the main database table and for all indices.
95872  ** The index cursors might not be used, but if they are used they
95873  ** need to occur right after the database cursor.  So go ahead and
95874  ** allocate enough space, just in case.
95875  */
95876  pTabList->a[0].iCursor = iCur = pParse->nTab++;
95877  for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
95878    pParse->nTab++;
95879  }
95880
95881  /* Initialize the name-context */
95882  memset(&sNC, 0, sizeof(sNC));
95883  sNC.pParse = pParse;
95884  sNC.pSrcList = pTabList;
95885
95886  /* Resolve the column names in all the expressions of the
95887  ** of the UPDATE statement.  Also find the column index
95888  ** for each column to be updated in the pChanges array.  For each
95889  ** column to be updated, make sure we have authorization to change
95890  ** that column.
95891  */
95892  chngRowid = 0;
95893  for(i=0; i<pChanges->nExpr; i++){
95894    if( sqlite3ResolveExprNames(&sNC, pChanges->a[i].pExpr) ){
95895      goto update_cleanup;
95896    }
95897    for(j=0; j<pTab->nCol; j++){
95898      if( sqlite3StrICmp(pTab->aCol[j].zName, pChanges->a[i].zName)==0 ){
95899        if( j==pTab->iPKey ){
95900          chngRowid = 1;
95901          pRowidExpr = pChanges->a[i].pExpr;
95902        }
95903        aXRef[j] = i;
95904        break;
95905      }
95906    }
95907    if( j>=pTab->nCol ){
95908      if( sqlite3IsRowid(pChanges->a[i].zName) ){
95909        chngRowid = 1;
95910        pRowidExpr = pChanges->a[i].pExpr;
95911      }else{
95912        sqlite3ErrorMsg(pParse, "no such column: %s", pChanges->a[i].zName);
95913        pParse->checkSchema = 1;
95914        goto update_cleanup;
95915      }
95916    }
95917#ifndef SQLITE_OMIT_AUTHORIZATION
95918    {
95919      int rc;
95920      rc = sqlite3AuthCheck(pParse, SQLITE_UPDATE, pTab->zName,
95921                           pTab->aCol[j].zName, db->aDb[iDb].zName);
95922      if( rc==SQLITE_DENY ){
95923        goto update_cleanup;
95924      }else if( rc==SQLITE_IGNORE ){
95925        aXRef[j] = -1;
95926      }
95927    }
95928#endif
95929  }
95930
95931  hasFK = sqlite3FkRequired(pParse, pTab, aXRef, chngRowid);
95932
95933  /* Allocate memory for the array aRegIdx[].  There is one entry in the
95934  ** array for each index associated with table being updated.  Fill in
95935  ** the value with a register number for indices that are to be used
95936  ** and with zero for unused indices.
95937  */
95938  for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){}
95939  if( nIdx>0 ){
95940    aRegIdx = sqlite3DbMallocRaw(db, sizeof(Index*) * nIdx );
95941    if( aRegIdx==0 ) goto update_cleanup;
95942  }
95943  for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
95944    int reg;
95945    if( chngRowid ){
95946      reg = ++pParse->nMem;
95947    }else{
95948      reg = 0;
95949      for(i=0; i<pIdx->nColumn; i++){
95950        if( aXRef[pIdx->aiColumn[i]]>=0 ){
95951          reg = ++pParse->nMem;
95952          break;
95953        }
95954      }
95955    }
95956    aRegIdx[j] = reg;
95957  }
95958
95959  /* Begin generating code. */
95960  v = sqlite3GetVdbe(pParse);
95961  if( v==0 ) goto update_cleanup;
95962  if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
95963  sqlite3BeginWriteOperation(pParse, 1, iDb);
95964
95965#ifndef SQLITE_OMIT_VIRTUALTABLE
95966  /* Virtual tables must be handled separately */
95967  if( IsVirtual(pTab) ){
95968    updateVirtualTable(pParse, pTabList, pTab, pChanges, pRowidExpr, aXRef,
95969                       pWhere);
95970    pWhere = 0;
95971    pTabList = 0;
95972    goto update_cleanup;
95973  }
95974#endif
95975
95976  /* Allocate required registers. */
95977  regOldRowid = regNewRowid = ++pParse->nMem;
95978  if( pTrigger || hasFK ){
95979    regOld = pParse->nMem + 1;
95980    pParse->nMem += pTab->nCol;
95981  }
95982  if( chngRowid || pTrigger || hasFK ){
95983    regNewRowid = ++pParse->nMem;
95984  }
95985  regNew = pParse->nMem + 1;
95986  pParse->nMem += pTab->nCol;
95987
95988  /* Start the view context. */
95989  if( isView ){
95990    sqlite3AuthContextPush(pParse, &sContext, pTab->zName);
95991  }
95992
95993  /* If we are trying to update a view, realize that view into
95994  ** a ephemeral table.
95995  */
95996#if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
95997  if( isView ){
95998    sqlite3MaterializeView(pParse, pTab, pWhere, iCur);
95999  }
96000#endif
96001
96002  /* Resolve the column names in all the expressions in the
96003  ** WHERE clause.
96004  */
96005  if( sqlite3ResolveExprNames(&sNC, pWhere) ){
96006    goto update_cleanup;
96007  }
96008
96009  /* Begin the database scan
96010  */
96011  sqlite3VdbeAddOp2(v, OP_Null, 0, regOldRowid);
96012  pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere,0, WHERE_ONEPASS_DESIRED);
96013  if( pWInfo==0 ) goto update_cleanup;
96014  okOnePass = pWInfo->okOnePass;
96015
96016  /* Remember the rowid of every item to be updated.
96017  */
96018  sqlite3VdbeAddOp2(v, OP_Rowid, iCur, regOldRowid);
96019  if( !okOnePass ){
96020    regRowSet = ++pParse->nMem;
96021    sqlite3VdbeAddOp2(v, OP_RowSetAdd, regRowSet, regOldRowid);
96022  }
96023
96024  /* End the database scan loop.
96025  */
96026  sqlite3WhereEnd(pWInfo);
96027
96028  /* Initialize the count of updated rows
96029  */
96030  if( (db->flags & SQLITE_CountRows) && !pParse->pTriggerTab ){
96031    regRowCount = ++pParse->nMem;
96032    sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
96033  }
96034
96035  if( !isView ){
96036    /*
96037    ** Open every index that needs updating.  Note that if any
96038    ** index could potentially invoke a REPLACE conflict resolution
96039    ** action, then we need to open all indices because we might need
96040    ** to be deleting some records.
96041    */
96042    if( !okOnePass ) sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenWrite);
96043    if( onError==OE_Replace ){
96044      openAll = 1;
96045    }else{
96046      openAll = 0;
96047      for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
96048        if( pIdx->onError==OE_Replace ){
96049          openAll = 1;
96050          break;
96051        }
96052      }
96053    }
96054    for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
96055      if( openAll || aRegIdx[i]>0 ){
96056        KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
96057        sqlite3VdbeAddOp4(v, OP_OpenWrite, iCur+i+1, pIdx->tnum, iDb,
96058                       (char*)pKey, P4_KEYINFO_HANDOFF);
96059        assert( pParse->nTab>iCur+i+1 );
96060      }
96061    }
96062  }
96063
96064  /* Top of the update loop */
96065  if( okOnePass ){
96066    int a1 = sqlite3VdbeAddOp1(v, OP_NotNull, regOldRowid);
96067    addr = sqlite3VdbeAddOp0(v, OP_Goto);
96068    sqlite3VdbeJumpHere(v, a1);
96069  }else{
96070    addr = sqlite3VdbeAddOp3(v, OP_RowSetRead, regRowSet, 0, regOldRowid);
96071  }
96072
96073  /* Make cursor iCur point to the record that is being updated. If
96074  ** this record does not exist for some reason (deleted by a trigger,
96075  ** for example, then jump to the next iteration of the RowSet loop.  */
96076  sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addr, regOldRowid);
96077
96078  /* If the record number will change, set register regNewRowid to
96079  ** contain the new value. If the record number is not being modified,
96080  ** then regNewRowid is the same register as regOldRowid, which is
96081  ** already populated.  */
96082  assert( chngRowid || pTrigger || hasFK || regOldRowid==regNewRowid );
96083  if( chngRowid ){
96084    sqlite3ExprCode(pParse, pRowidExpr, regNewRowid);
96085    sqlite3VdbeAddOp1(v, OP_MustBeInt, regNewRowid);
96086  }
96087
96088  /* If there are triggers on this table, populate an array of registers
96089  ** with the required old.* column data.  */
96090  if( hasFK || pTrigger ){
96091    u32 oldmask = (hasFK ? sqlite3FkOldmask(pParse, pTab) : 0);
96092    oldmask |= sqlite3TriggerColmask(pParse,
96093        pTrigger, pChanges, 0, TRIGGER_BEFORE|TRIGGER_AFTER, pTab, onError
96094    );
96095    for(i=0; i<pTab->nCol; i++){
96096      if( aXRef[i]<0 || oldmask==0xffffffff || (i<32 && (oldmask & (1<<i))) ){
96097        sqlite3ExprCodeGetColumnOfTable(v, pTab, iCur, i, regOld+i);
96098      }else{
96099        sqlite3VdbeAddOp2(v, OP_Null, 0, regOld+i);
96100      }
96101    }
96102    if( chngRowid==0 ){
96103      sqlite3VdbeAddOp2(v, OP_Copy, regOldRowid, regNewRowid);
96104    }
96105  }
96106
96107  /* Populate the array of registers beginning at regNew with the new
96108  ** row data. This array is used to check constaints, create the new
96109  ** table and index records, and as the values for any new.* references
96110  ** made by triggers.
96111  **
96112  ** If there are one or more BEFORE triggers, then do not populate the
96113  ** registers associated with columns that are (a) not modified by
96114  ** this UPDATE statement and (b) not accessed by new.* references. The
96115  ** values for registers not modified by the UPDATE must be reloaded from
96116  ** the database after the BEFORE triggers are fired anyway (as the trigger
96117  ** may have modified them). So not loading those that are not going to
96118  ** be used eliminates some redundant opcodes.
96119  */
96120  newmask = sqlite3TriggerColmask(
96121      pParse, pTrigger, pChanges, 1, TRIGGER_BEFORE, pTab, onError
96122  );
96123  for(i=0; i<pTab->nCol; i++){
96124    if( i==pTab->iPKey ){
96125      sqlite3VdbeAddOp2(v, OP_Null, 0, regNew+i);
96126    }else{
96127      j = aXRef[i];
96128      if( j>=0 ){
96129        sqlite3ExprCode(pParse, pChanges->a[j].pExpr, regNew+i);
96130      }else if( 0==(tmask&TRIGGER_BEFORE) || i>31 || (newmask&(1<<i)) ){
96131        /* This branch loads the value of a column that will not be changed
96132        ** into a register. This is done if there are no BEFORE triggers, or
96133        ** if there are one or more BEFORE triggers that use this value via
96134        ** a new.* reference in a trigger program.
96135        */
96136        testcase( i==31 );
96137        testcase( i==32 );
96138        sqlite3VdbeAddOp3(v, OP_Column, iCur, i, regNew+i);
96139        sqlite3ColumnDefault(v, pTab, i, regNew+i);
96140      }
96141    }
96142  }
96143
96144  /* Fire any BEFORE UPDATE triggers. This happens before constraints are
96145  ** verified. One could argue that this is wrong.
96146  */
96147  if( tmask&TRIGGER_BEFORE ){
96148    sqlite3VdbeAddOp2(v, OP_Affinity, regNew, pTab->nCol);
96149    sqlite3TableAffinityStr(v, pTab);
96150    sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges,
96151        TRIGGER_BEFORE, pTab, regOldRowid, onError, addr);
96152
96153    /* The row-trigger may have deleted the row being updated. In this
96154    ** case, jump to the next row. No updates or AFTER triggers are
96155    ** required. This behaviour - what happens when the row being updated
96156    ** is deleted or renamed by a BEFORE trigger - is left undefined in the
96157    ** documentation.
96158    */
96159    sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addr, regOldRowid);
96160
96161    /* If it did not delete it, the row-trigger may still have modified
96162    ** some of the columns of the row being updated. Load the values for
96163    ** all columns not modified by the update statement into their
96164    ** registers in case this has happened.
96165    */
96166    for(i=0; i<pTab->nCol; i++){
96167      if( aXRef[i]<0 && i!=pTab->iPKey ){
96168        sqlite3VdbeAddOp3(v, OP_Column, iCur, i, regNew+i);
96169        sqlite3ColumnDefault(v, pTab, i, regNew+i);
96170      }
96171    }
96172  }
96173
96174  if( !isView ){
96175    int j1;                       /* Address of jump instruction */
96176
96177    /* Do constraint checks. */
96178    sqlite3GenerateConstraintChecks(pParse, pTab, iCur, regNewRowid,
96179        aRegIdx, (chngRowid?regOldRowid:0), 1, onError, addr, 0);
96180
96181    /* Do FK constraint checks. */
96182    if( hasFK ){
96183      sqlite3FkCheck(pParse, pTab, regOldRowid, 0);
96184    }
96185
96186    /* Delete the index entries associated with the current record.  */
96187    j1 = sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, regOldRowid);
96188    sqlite3GenerateRowIndexDelete(pParse, pTab, iCur, aRegIdx);
96189
96190    /* If changing the record number, delete the old record.  */
96191    if( hasFK || chngRowid ){
96192      sqlite3VdbeAddOp2(v, OP_Delete, iCur, 0);
96193    }
96194    sqlite3VdbeJumpHere(v, j1);
96195
96196    if( hasFK ){
96197      sqlite3FkCheck(pParse, pTab, 0, regNewRowid);
96198    }
96199
96200    /* Insert the new index entries and the new record. */
96201    sqlite3CompleteInsertion(pParse, pTab, iCur, regNewRowid, aRegIdx, 1, 0, 0);
96202
96203    /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to
96204    ** handle rows (possibly in other tables) that refer via a foreign key
96205    ** to the row just updated. */
96206    if( hasFK ){
96207      sqlite3FkActions(pParse, pTab, pChanges, regOldRowid);
96208    }
96209  }
96210
96211  /* Increment the row counter
96212  */
96213  if( (db->flags & SQLITE_CountRows) && !pParse->pTriggerTab){
96214    sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
96215  }
96216
96217  sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges,
96218      TRIGGER_AFTER, pTab, regOldRowid, onError, addr);
96219
96220  /* Repeat the above with the next record to be updated, until
96221  ** all record selected by the WHERE clause have been updated.
96222  */
96223  sqlite3VdbeAddOp2(v, OP_Goto, 0, addr);
96224  sqlite3VdbeJumpHere(v, addr);
96225
96226  /* Close all tables */
96227  for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
96228    if( openAll || aRegIdx[i]>0 ){
96229      sqlite3VdbeAddOp2(v, OP_Close, iCur+i+1, 0);
96230    }
96231  }
96232  sqlite3VdbeAddOp2(v, OP_Close, iCur, 0);
96233
96234  /* Update the sqlite_sequence table by storing the content of the
96235  ** maximum rowid counter values recorded while inserting into
96236  ** autoincrement tables.
96237  */
96238  if( pParse->nested==0 && pParse->pTriggerTab==0 ){
96239    sqlite3AutoincrementEnd(pParse);
96240  }
96241
96242  /*
96243  ** Return the number of rows that were changed. If this routine is
96244  ** generating code because of a call to sqlite3NestedParse(), do not
96245  ** invoke the callback function.
96246  */
96247  if( (db->flags&SQLITE_CountRows) && !pParse->pTriggerTab && !pParse->nested ){
96248    sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
96249    sqlite3VdbeSetNumCols(v, 1);
96250    sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows updated", SQLITE_STATIC);
96251  }
96252
96253update_cleanup:
96254  sqlite3AuthContextPop(&sContext);
96255  sqlite3DbFree(db, aRegIdx);
96256  sqlite3DbFree(db, aXRef);
96257  sqlite3SrcListDelete(db, pTabList);
96258  sqlite3ExprListDelete(db, pChanges);
96259  sqlite3ExprDelete(db, pWhere);
96260  return;
96261}
96262/* Make sure "isView" and other macros defined above are undefined. Otherwise
96263** thely may interfere with compilation of other functions in this file
96264** (or in another file, if this file becomes part of the amalgamation).  */
96265#ifdef isView
96266 #undef isView
96267#endif
96268#ifdef pTrigger
96269 #undef pTrigger
96270#endif
96271
96272#ifndef SQLITE_OMIT_VIRTUALTABLE
96273/*
96274** Generate code for an UPDATE of a virtual table.
96275**
96276** The strategy is that we create an ephemerial table that contains
96277** for each row to be changed:
96278**
96279**   (A)  The original rowid of that row.
96280**   (B)  The revised rowid for the row. (note1)
96281**   (C)  The content of every column in the row.
96282**
96283** Then we loop over this ephemeral table and for each row in
96284** the ephermeral table call VUpdate.
96285**
96286** When finished, drop the ephemeral table.
96287**
96288** (note1) Actually, if we know in advance that (A) is always the same
96289** as (B) we only store (A), then duplicate (A) when pulling
96290** it out of the ephemeral table before calling VUpdate.
96291*/
96292static void updateVirtualTable(
96293  Parse *pParse,       /* The parsing context */
96294  SrcList *pSrc,       /* The virtual table to be modified */
96295  Table *pTab,         /* The virtual table */
96296  ExprList *pChanges,  /* The columns to change in the UPDATE statement */
96297  Expr *pRowid,        /* Expression used to recompute the rowid */
96298  int *aXRef,          /* Mapping from columns of pTab to entries in pChanges */
96299  Expr *pWhere         /* WHERE clause of the UPDATE statement */
96300){
96301  Vdbe *v = pParse->pVdbe;  /* Virtual machine under construction */
96302  ExprList *pEList = 0;     /* The result set of the SELECT statement */
96303  Select *pSelect = 0;      /* The SELECT statement */
96304  Expr *pExpr;              /* Temporary expression */
96305  int ephemTab;             /* Table holding the result of the SELECT */
96306  int i;                    /* Loop counter */
96307  int addr;                 /* Address of top of loop */
96308  int iReg;                 /* First register in set passed to OP_VUpdate */
96309  sqlite3 *db = pParse->db; /* Database connection */
96310  const char *pVTab = (const char*)sqlite3GetVTable(db, pTab);
96311  SelectDest dest;
96312
96313  /* Construct the SELECT statement that will find the new values for
96314  ** all updated rows.
96315  */
96316  pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db, TK_ID, "_rowid_"));
96317  if( pRowid ){
96318    pEList = sqlite3ExprListAppend(pParse, pEList,
96319                                   sqlite3ExprDup(db, pRowid, 0));
96320  }
96321  assert( pTab->iPKey<0 );
96322  for(i=0; i<pTab->nCol; i++){
96323    if( aXRef[i]>=0 ){
96324      pExpr = sqlite3ExprDup(db, pChanges->a[aXRef[i]].pExpr, 0);
96325    }else{
96326      pExpr = sqlite3Expr(db, TK_ID, pTab->aCol[i].zName);
96327    }
96328    pEList = sqlite3ExprListAppend(pParse, pEList, pExpr);
96329  }
96330  pSelect = sqlite3SelectNew(pParse, pEList, pSrc, pWhere, 0, 0, 0, 0, 0, 0);
96331
96332  /* Create the ephemeral table into which the update results will
96333  ** be stored.
96334  */
96335  assert( v );
96336  ephemTab = pParse->nTab++;
96337  sqlite3VdbeAddOp2(v, OP_OpenEphemeral, ephemTab, pTab->nCol+1+(pRowid!=0));
96338  sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
96339
96340  /* fill the ephemeral table
96341  */
96342  sqlite3SelectDestInit(&dest, SRT_Table, ephemTab);
96343  sqlite3Select(pParse, pSelect, &dest);
96344
96345  /* Generate code to scan the ephemeral table and call VUpdate. */
96346  iReg = ++pParse->nMem;
96347  pParse->nMem += pTab->nCol+1;
96348  addr = sqlite3VdbeAddOp2(v, OP_Rewind, ephemTab, 0);
96349  sqlite3VdbeAddOp3(v, OP_Column,  ephemTab, 0, iReg);
96350  sqlite3VdbeAddOp3(v, OP_Column, ephemTab, (pRowid?1:0), iReg+1);
96351  for(i=0; i<pTab->nCol; i++){
96352    sqlite3VdbeAddOp3(v, OP_Column, ephemTab, i+1+(pRowid!=0), iReg+2+i);
96353  }
96354  sqlite3VtabMakeWritable(pParse, pTab);
96355  sqlite3VdbeAddOp4(v, OP_VUpdate, 0, pTab->nCol+2, iReg, pVTab, P4_VTAB);
96356  sqlite3MayAbort(pParse);
96357  sqlite3VdbeAddOp2(v, OP_Next, ephemTab, addr+1);
96358  sqlite3VdbeJumpHere(v, addr);
96359  sqlite3VdbeAddOp2(v, OP_Close, ephemTab, 0);
96360
96361  /* Cleanup */
96362  sqlite3SelectDelete(db, pSelect);
96363}
96364#endif /* SQLITE_OMIT_VIRTUALTABLE */
96365
96366/************** End of update.c **********************************************/
96367/************** Begin file vacuum.c ******************************************/
96368/*
96369** 2003 April 6
96370**
96371** The author disclaims copyright to this source code.  In place of
96372** a legal notice, here is a blessing:
96373**
96374**    May you do good and not evil.
96375**    May you find forgiveness for yourself and forgive others.
96376**    May you share freely, never taking more than you give.
96377**
96378*************************************************************************
96379** This file contains code used to implement the VACUUM command.
96380**
96381** Most of the code in this file may be omitted by defining the
96382** SQLITE_OMIT_VACUUM macro.
96383*/
96384
96385#if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
96386/*
96387** Finalize a prepared statement.  If there was an error, store the
96388** text of the error message in *pzErrMsg.  Return the result code.
96389*/
96390static int vacuumFinalize(sqlite3 *db, sqlite3_stmt *pStmt, char **pzErrMsg){
96391  int rc;
96392  rc = sqlite3VdbeFinalize((Vdbe*)pStmt);
96393  if( rc ){
96394    sqlite3SetString(pzErrMsg, db, sqlite3_errmsg(db));
96395  }
96396  return rc;
96397}
96398
96399/*
96400** Execute zSql on database db. Return an error code.
96401*/
96402static int execSql(sqlite3 *db, char **pzErrMsg, const char *zSql){
96403  sqlite3_stmt *pStmt;
96404  VVA_ONLY( int rc; )
96405  if( !zSql ){
96406    return SQLITE_NOMEM;
96407  }
96408  if( SQLITE_OK!=sqlite3_prepare(db, zSql, -1, &pStmt, 0) ){
96409    sqlite3SetString(pzErrMsg, db, sqlite3_errmsg(db));
96410    return sqlite3_errcode(db);
96411  }
96412  VVA_ONLY( rc = ) sqlite3_step(pStmt);
96413  assert( rc!=SQLITE_ROW );
96414  return vacuumFinalize(db, pStmt, pzErrMsg);
96415}
96416
96417/*
96418** Execute zSql on database db. The statement returns exactly
96419** one column. Execute this as SQL on the same database.
96420*/
96421static int execExecSql(sqlite3 *db, char **pzErrMsg, const char *zSql){
96422  sqlite3_stmt *pStmt;
96423  int rc;
96424
96425  rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
96426  if( rc!=SQLITE_OK ) return rc;
96427
96428  while( SQLITE_ROW==sqlite3_step(pStmt) ){
96429    rc = execSql(db, pzErrMsg, (char*)sqlite3_column_text(pStmt, 0));
96430    if( rc!=SQLITE_OK ){
96431      vacuumFinalize(db, pStmt, pzErrMsg);
96432      return rc;
96433    }
96434  }
96435
96436  return vacuumFinalize(db, pStmt, pzErrMsg);
96437}
96438
96439/*
96440** The non-standard VACUUM command is used to clean up the database,
96441** collapse free space, etc.  It is modelled after the VACUUM command
96442** in PostgreSQL.
96443**
96444** In version 1.0.x of SQLite, the VACUUM command would call
96445** gdbm_reorganize() on all the database tables.  But beginning
96446** with 2.0.0, SQLite no longer uses GDBM so this command has
96447** become a no-op.
96448*/
96449SQLITE_PRIVATE void sqlite3Vacuum(Parse *pParse){
96450  Vdbe *v = sqlite3GetVdbe(pParse);
96451  if( v ){
96452    sqlite3VdbeAddOp2(v, OP_Vacuum, 0, 0);
96453  }
96454  return;
96455}
96456
96457/*
96458** This routine implements the OP_Vacuum opcode of the VDBE.
96459*/
96460SQLITE_PRIVATE int sqlite3RunVacuum(char **pzErrMsg, sqlite3 *db){
96461  int rc = SQLITE_OK;     /* Return code from service routines */
96462  Btree *pMain;           /* The database being vacuumed */
96463  Btree *pTemp;           /* The temporary database we vacuum into */
96464  char *zSql = 0;         /* SQL statements */
96465  int saved_flags;        /* Saved value of the db->flags */
96466  int saved_nChange;      /* Saved value of db->nChange */
96467  int saved_nTotalChange; /* Saved value of db->nTotalChange */
96468  void (*saved_xTrace)(void*,const char*);  /* Saved db->xTrace */
96469  Db *pDb = 0;            /* Database to detach at end of vacuum */
96470  int isMemDb;            /* True if vacuuming a :memory: database */
96471  int nRes;               /* Bytes of reserved space at the end of each page */
96472  int nDb;                /* Number of attached databases */
96473
96474  if( !db->autoCommit ){
96475    sqlite3SetString(pzErrMsg, db, "cannot VACUUM from within a transaction");
96476    return SQLITE_ERROR;
96477  }
96478  if( db->activeVdbeCnt>1 ){
96479    sqlite3SetString(pzErrMsg, db,"cannot VACUUM - SQL statements in progress");
96480    return SQLITE_ERROR;
96481  }
96482
96483  /* Save the current value of the database flags so that it can be
96484  ** restored before returning. Then set the writable-schema flag, and
96485  ** disable CHECK and foreign key constraints.  */
96486  saved_flags = db->flags;
96487  saved_nChange = db->nChange;
96488  saved_nTotalChange = db->nTotalChange;
96489  saved_xTrace = db->xTrace;
96490  db->flags |= SQLITE_WriteSchema | SQLITE_IgnoreChecks | SQLITE_PreferBuiltin;
96491  db->flags &= ~(SQLITE_ForeignKeys | SQLITE_ReverseOrder);
96492  db->xTrace = 0;
96493
96494  pMain = db->aDb[0].pBt;
96495  isMemDb = sqlite3PagerIsMemdb(sqlite3BtreePager(pMain));
96496
96497  /* Attach the temporary database as 'vacuum_db'. The synchronous pragma
96498  ** can be set to 'off' for this file, as it is not recovered if a crash
96499  ** occurs anyway. The integrity of the database is maintained by a
96500  ** (possibly synchronous) transaction opened on the main database before
96501  ** sqlite3BtreeCopyFile() is called.
96502  **
96503  ** An optimisation would be to use a non-journaled pager.
96504  ** (Later:) I tried setting "PRAGMA vacuum_db.journal_mode=OFF" but
96505  ** that actually made the VACUUM run slower.  Very little journalling
96506  ** actually occurs when doing a vacuum since the vacuum_db is initially
96507  ** empty.  Only the journal header is written.  Apparently it takes more
96508  ** time to parse and run the PRAGMA to turn journalling off than it does
96509  ** to write the journal header file.
96510  */
96511  nDb = db->nDb;
96512  if( sqlite3TempInMemory(db) ){
96513    zSql = "ATTACH ':memory:' AS vacuum_db;";
96514  }else{
96515    zSql = "ATTACH '' AS vacuum_db;";
96516  }
96517  rc = execSql(db, pzErrMsg, zSql);
96518  if( db->nDb>nDb ){
96519    pDb = &db->aDb[db->nDb-1];
96520    assert( strcmp(pDb->zName,"vacuum_db")==0 );
96521  }
96522  if( rc!=SQLITE_OK ) goto end_of_vacuum;
96523  pTemp = db->aDb[db->nDb-1].pBt;
96524
96525  /* The call to execSql() to attach the temp database has left the file
96526  ** locked (as there was more than one active statement when the transaction
96527  ** to read the schema was concluded. Unlock it here so that this doesn't
96528  ** cause problems for the call to BtreeSetPageSize() below.  */
96529  sqlite3BtreeCommit(pTemp);
96530
96531  nRes = sqlite3BtreeGetReserve(pMain);
96532
96533  /* A VACUUM cannot change the pagesize of an encrypted database. */
96534#ifdef SQLITE_HAS_CODEC
96535  if( db->nextPagesize ){
96536    extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*);
96537    int nKey;
96538    char *zKey;
96539    sqlite3CodecGetKey(db, 0, (void**)&zKey, &nKey);
96540    if( nKey ) db->nextPagesize = 0;
96541  }
96542#endif
96543
96544  /* Do not attempt to change the page size for a WAL database */
96545  if( sqlite3PagerGetJournalMode(sqlite3BtreePager(pMain))
96546                                               ==PAGER_JOURNALMODE_WAL ){
96547    db->nextPagesize = 0;
96548  }
96549
96550  if( sqlite3BtreeSetPageSize(pTemp, sqlite3BtreeGetPageSize(pMain), nRes, 0)
96551   || (!isMemDb && sqlite3BtreeSetPageSize(pTemp, db->nextPagesize, nRes, 0))
96552   || NEVER(db->mallocFailed)
96553  ){
96554    rc = SQLITE_NOMEM;
96555    goto end_of_vacuum;
96556  }
96557  rc = execSql(db, pzErrMsg, "PRAGMA vacuum_db.synchronous=OFF");
96558  if( rc!=SQLITE_OK ){
96559    goto end_of_vacuum;
96560  }
96561
96562#ifndef SQLITE_OMIT_AUTOVACUUM
96563  sqlite3BtreeSetAutoVacuum(pTemp, db->nextAutovac>=0 ? db->nextAutovac :
96564                                           sqlite3BtreeGetAutoVacuum(pMain));
96565#endif
96566
96567  /* Begin a transaction */
96568  rc = execSql(db, pzErrMsg, "BEGIN EXCLUSIVE;");
96569  if( rc!=SQLITE_OK ) goto end_of_vacuum;
96570
96571  /* Query the schema of the main database. Create a mirror schema
96572  ** in the temporary database.
96573  */
96574  rc = execExecSql(db, pzErrMsg,
96575      "SELECT 'CREATE TABLE vacuum_db.' || substr(sql,14) "
96576      "  FROM sqlite_master WHERE type='table' AND name!='sqlite_sequence'"
96577      "   AND rootpage>0"
96578  );
96579  if( rc!=SQLITE_OK ) goto end_of_vacuum;
96580  rc = execExecSql(db, pzErrMsg,
96581      "SELECT 'CREATE INDEX vacuum_db.' || substr(sql,14)"
96582      "  FROM sqlite_master WHERE sql LIKE 'CREATE INDEX %' ");
96583  if( rc!=SQLITE_OK ) goto end_of_vacuum;
96584  rc = execExecSql(db, pzErrMsg,
96585      "SELECT 'CREATE UNIQUE INDEX vacuum_db.' || substr(sql,21) "
96586      "  FROM sqlite_master WHERE sql LIKE 'CREATE UNIQUE INDEX %'");
96587  if( rc!=SQLITE_OK ) goto end_of_vacuum;
96588
96589  /* Loop through the tables in the main database. For each, do
96590  ** an "INSERT INTO vacuum_db.xxx SELECT * FROM main.xxx;" to copy
96591  ** the contents to the temporary database.
96592  */
96593  rc = execExecSql(db, pzErrMsg,
96594      "SELECT 'INSERT INTO vacuum_db.' || quote(name) "
96595      "|| ' SELECT * FROM main.' || quote(name) || ';'"
96596      "FROM main.sqlite_master "
96597      "WHERE type = 'table' AND name!='sqlite_sequence' "
96598      "  AND rootpage>0"
96599  );
96600  if( rc!=SQLITE_OK ) goto end_of_vacuum;
96601
96602  /* Copy over the sequence table
96603  */
96604  rc = execExecSql(db, pzErrMsg,
96605      "SELECT 'DELETE FROM vacuum_db.' || quote(name) || ';' "
96606      "FROM vacuum_db.sqlite_master WHERE name='sqlite_sequence' "
96607  );
96608  if( rc!=SQLITE_OK ) goto end_of_vacuum;
96609  rc = execExecSql(db, pzErrMsg,
96610      "SELECT 'INSERT INTO vacuum_db.' || quote(name) "
96611      "|| ' SELECT * FROM main.' || quote(name) || ';' "
96612      "FROM vacuum_db.sqlite_master WHERE name=='sqlite_sequence';"
96613  );
96614  if( rc!=SQLITE_OK ) goto end_of_vacuum;
96615
96616
96617  /* Copy the triggers, views, and virtual tables from the main database
96618  ** over to the temporary database.  None of these objects has any
96619  ** associated storage, so all we have to do is copy their entries
96620  ** from the SQLITE_MASTER table.
96621  */
96622  rc = execSql(db, pzErrMsg,
96623      "INSERT INTO vacuum_db.sqlite_master "
96624      "  SELECT type, name, tbl_name, rootpage, sql"
96625      "    FROM main.sqlite_master"
96626      "   WHERE type='view' OR type='trigger'"
96627      "      OR (type='table' AND rootpage=0)"
96628  );
96629  if( rc ) goto end_of_vacuum;
96630
96631  /* At this point, unless the main db was completely empty, there is now a
96632  ** transaction open on the vacuum database, but not on the main database.
96633  ** Open a btree level transaction on the main database. This allows a
96634  ** call to sqlite3BtreeCopyFile(). The main database btree level
96635  ** transaction is then committed, so the SQL level never knows it was
96636  ** opened for writing. This way, the SQL transaction used to create the
96637  ** temporary database never needs to be committed.
96638  */
96639  {
96640    u32 meta;
96641    int i;
96642
96643    /* This array determines which meta meta values are preserved in the
96644    ** vacuum.  Even entries are the meta value number and odd entries
96645    ** are an increment to apply to the meta value after the vacuum.
96646    ** The increment is used to increase the schema cookie so that other
96647    ** connections to the same database will know to reread the schema.
96648    */
96649    static const unsigned char aCopy[] = {
96650       BTREE_SCHEMA_VERSION,     1,  /* Add one to the old schema cookie */
96651       BTREE_DEFAULT_CACHE_SIZE, 0,  /* Preserve the default page cache size */
96652       BTREE_TEXT_ENCODING,      0,  /* Preserve the text encoding */
96653       BTREE_USER_VERSION,       0,  /* Preserve the user version */
96654    };
96655
96656    assert( 1==sqlite3BtreeIsInTrans(pTemp) );
96657    assert( 1==sqlite3BtreeIsInTrans(pMain) );
96658
96659    /* Copy Btree meta values */
96660    for(i=0; i<ArraySize(aCopy); i+=2){
96661      /* GetMeta() and UpdateMeta() cannot fail in this context because
96662      ** we already have page 1 loaded into cache and marked dirty. */
96663      sqlite3BtreeGetMeta(pMain, aCopy[i], &meta);
96664      rc = sqlite3BtreeUpdateMeta(pTemp, aCopy[i], meta+aCopy[i+1]);
96665      if( NEVER(rc!=SQLITE_OK) ) goto end_of_vacuum;
96666    }
96667
96668    rc = sqlite3BtreeCopyFile(pMain, pTemp);
96669    if( rc!=SQLITE_OK ) goto end_of_vacuum;
96670    rc = sqlite3BtreeCommit(pTemp);
96671    if( rc!=SQLITE_OK ) goto end_of_vacuum;
96672#ifndef SQLITE_OMIT_AUTOVACUUM
96673    sqlite3BtreeSetAutoVacuum(pMain, sqlite3BtreeGetAutoVacuum(pTemp));
96674#endif
96675  }
96676
96677  assert( rc==SQLITE_OK );
96678  rc = sqlite3BtreeSetPageSize(pMain, sqlite3BtreeGetPageSize(pTemp), nRes,1);
96679
96680end_of_vacuum:
96681  /* Restore the original value of db->flags */
96682  db->flags = saved_flags;
96683  db->nChange = saved_nChange;
96684  db->nTotalChange = saved_nTotalChange;
96685  db->xTrace = saved_xTrace;
96686  sqlite3BtreeSetPageSize(pMain, -1, -1, 1);
96687
96688  /* Currently there is an SQL level transaction open on the vacuum
96689  ** database. No locks are held on any other files (since the main file
96690  ** was committed at the btree level). So it safe to end the transaction
96691  ** by manually setting the autoCommit flag to true and detaching the
96692  ** vacuum database. The vacuum_db journal file is deleted when the pager
96693  ** is closed by the DETACH.
96694  */
96695  db->autoCommit = 1;
96696
96697  if( pDb ){
96698    sqlite3BtreeClose(pDb->pBt);
96699    pDb->pBt = 0;
96700    pDb->pSchema = 0;
96701  }
96702
96703  /* This both clears the schemas and reduces the size of the db->aDb[]
96704  ** array. */
96705  sqlite3ResetInternalSchema(db, -1);
96706
96707  return rc;
96708}
96709
96710#endif  /* SQLITE_OMIT_VACUUM && SQLITE_OMIT_ATTACH */
96711
96712/************** End of vacuum.c **********************************************/
96713/************** Begin file vtab.c ********************************************/
96714/*
96715** 2006 June 10
96716**
96717** The author disclaims copyright to this source code.  In place of
96718** a legal notice, here is a blessing:
96719**
96720**    May you do good and not evil.
96721**    May you find forgiveness for yourself and forgive others.
96722**    May you share freely, never taking more than you give.
96723**
96724*************************************************************************
96725** This file contains code used to help implement virtual tables.
96726*/
96727#ifndef SQLITE_OMIT_VIRTUALTABLE
96728
96729/*
96730** The actual function that does the work of creating a new module.
96731** This function implements the sqlite3_create_module() and
96732** sqlite3_create_module_v2() interfaces.
96733*/
96734static int createModule(
96735  sqlite3 *db,                    /* Database in which module is registered */
96736  const char *zName,              /* Name assigned to this module */
96737  const sqlite3_module *pModule,  /* The definition of the module */
96738  void *pAux,                     /* Context pointer for xCreate/xConnect */
96739  void (*xDestroy)(void *)        /* Module destructor function */
96740){
96741  int rc, nName;
96742  Module *pMod;
96743
96744  sqlite3_mutex_enter(db->mutex);
96745  nName = sqlite3Strlen30(zName);
96746  pMod = (Module *)sqlite3DbMallocRaw(db, sizeof(Module) + nName + 1);
96747  if( pMod ){
96748    Module *pDel;
96749    char *zCopy = (char *)(&pMod[1]);
96750    memcpy(zCopy, zName, nName+1);
96751    pMod->zName = zCopy;
96752    pMod->pModule = pModule;
96753    pMod->pAux = pAux;
96754    pMod->xDestroy = xDestroy;
96755    pDel = (Module *)sqlite3HashInsert(&db->aModule, zCopy, nName, (void*)pMod);
96756    if( pDel && pDel->xDestroy ){
96757      pDel->xDestroy(pDel->pAux);
96758    }
96759    sqlite3DbFree(db, pDel);
96760    if( pDel==pMod ){
96761      db->mallocFailed = 1;
96762    }
96763    sqlite3ResetInternalSchema(db, -1);
96764  }else if( xDestroy ){
96765    xDestroy(pAux);
96766  }
96767  rc = sqlite3ApiExit(db, SQLITE_OK);
96768  sqlite3_mutex_leave(db->mutex);
96769  return rc;
96770}
96771
96772
96773/*
96774** External API function used to create a new virtual-table module.
96775*/
96776SQLITE_API int sqlite3_create_module(
96777  sqlite3 *db,                    /* Database in which module is registered */
96778  const char *zName,              /* Name assigned to this module */
96779  const sqlite3_module *pModule,  /* The definition of the module */
96780  void *pAux                      /* Context pointer for xCreate/xConnect */
96781){
96782  return createModule(db, zName, pModule, pAux, 0);
96783}
96784
96785/*
96786** External API function used to create a new virtual-table module.
96787*/
96788SQLITE_API int sqlite3_create_module_v2(
96789  sqlite3 *db,                    /* Database in which module is registered */
96790  const char *zName,              /* Name assigned to this module */
96791  const sqlite3_module *pModule,  /* The definition of the module */
96792  void *pAux,                     /* Context pointer for xCreate/xConnect */
96793  void (*xDestroy)(void *)        /* Module destructor function */
96794){
96795  return createModule(db, zName, pModule, pAux, xDestroy);
96796}
96797
96798/*
96799** Lock the virtual table so that it cannot be disconnected.
96800** Locks nest.  Every lock should have a corresponding unlock.
96801** If an unlock is omitted, resources leaks will occur.
96802**
96803** If a disconnect is attempted while a virtual table is locked,
96804** the disconnect is deferred until all locks have been removed.
96805*/
96806SQLITE_PRIVATE void sqlite3VtabLock(VTable *pVTab){
96807  pVTab->nRef++;
96808}
96809
96810
96811/*
96812** pTab is a pointer to a Table structure representing a virtual-table.
96813** Return a pointer to the VTable object used by connection db to access
96814** this virtual-table, if one has been created, or NULL otherwise.
96815*/
96816SQLITE_PRIVATE VTable *sqlite3GetVTable(sqlite3 *db, Table *pTab){
96817  VTable *pVtab;
96818  assert( IsVirtual(pTab) );
96819  for(pVtab=pTab->pVTable; pVtab && pVtab->db!=db; pVtab=pVtab->pNext);
96820  return pVtab;
96821}
96822
96823/*
96824** Decrement the ref-count on a virtual table object. When the ref-count
96825** reaches zero, call the xDisconnect() method to delete the object.
96826*/
96827SQLITE_PRIVATE void sqlite3VtabUnlock(VTable *pVTab){
96828  sqlite3 *db = pVTab->db;
96829
96830  assert( db );
96831  assert( pVTab->nRef>0 );
96832  assert( sqlite3SafetyCheckOk(db) );
96833
96834  pVTab->nRef--;
96835  if( pVTab->nRef==0 ){
96836    sqlite3_vtab *p = pVTab->pVtab;
96837    if( p ){
96838      p->pModule->xDisconnect(p);
96839    }
96840    sqlite3DbFree(db, pVTab);
96841  }
96842}
96843
96844/*
96845** Table p is a virtual table. This function moves all elements in the
96846** p->pVTable list to the sqlite3.pDisconnect lists of their associated
96847** database connections to be disconnected at the next opportunity.
96848** Except, if argument db is not NULL, then the entry associated with
96849** connection db is left in the p->pVTable list.
96850*/
96851static VTable *vtabDisconnectAll(sqlite3 *db, Table *p){
96852  VTable *pRet = 0;
96853  VTable *pVTable = p->pVTable;
96854  p->pVTable = 0;
96855
96856  /* Assert that the mutex (if any) associated with the BtShared database
96857  ** that contains table p is held by the caller. See header comments
96858  ** above function sqlite3VtabUnlockList() for an explanation of why
96859  ** this makes it safe to access the sqlite3.pDisconnect list of any
96860  ** database connection that may have an entry in the p->pVTable list.
96861  */
96862  assert( db==0 || sqlite3SchemaMutexHeld(db, 0, p->pSchema) );
96863
96864  while( pVTable ){
96865    sqlite3 *db2 = pVTable->db;
96866    VTable *pNext = pVTable->pNext;
96867    assert( db2 );
96868    if( db2==db ){
96869      pRet = pVTable;
96870      p->pVTable = pRet;
96871      pRet->pNext = 0;
96872    }else{
96873      pVTable->pNext = db2->pDisconnect;
96874      db2->pDisconnect = pVTable;
96875    }
96876    pVTable = pNext;
96877  }
96878
96879  assert( !db || pRet );
96880  return pRet;
96881}
96882
96883
96884/*
96885** Disconnect all the virtual table objects in the sqlite3.pDisconnect list.
96886**
96887** This function may only be called when the mutexes associated with all
96888** shared b-tree databases opened using connection db are held by the
96889** caller. This is done to protect the sqlite3.pDisconnect list. The
96890** sqlite3.pDisconnect list is accessed only as follows:
96891**
96892**   1) By this function. In this case, all BtShared mutexes and the mutex
96893**      associated with the database handle itself must be held.
96894**
96895**   2) By function vtabDisconnectAll(), when it adds a VTable entry to
96896**      the sqlite3.pDisconnect list. In this case either the BtShared mutex
96897**      associated with the database the virtual table is stored in is held
96898**      or, if the virtual table is stored in a non-sharable database, then
96899**      the database handle mutex is held.
96900**
96901** As a result, a sqlite3.pDisconnect cannot be accessed simultaneously
96902** by multiple threads. It is thread-safe.
96903*/
96904SQLITE_PRIVATE void sqlite3VtabUnlockList(sqlite3 *db){
96905  VTable *p = db->pDisconnect;
96906  db->pDisconnect = 0;
96907
96908  assert( sqlite3BtreeHoldsAllMutexes(db) );
96909  assert( sqlite3_mutex_held(db->mutex) );
96910
96911  if( p ){
96912    sqlite3ExpirePreparedStatements(db);
96913    do {
96914      VTable *pNext = p->pNext;
96915      sqlite3VtabUnlock(p);
96916      p = pNext;
96917    }while( p );
96918  }
96919}
96920
96921/*
96922** Clear any and all virtual-table information from the Table record.
96923** This routine is called, for example, just before deleting the Table
96924** record.
96925**
96926** Since it is a virtual-table, the Table structure contains a pointer
96927** to the head of a linked list of VTable structures. Each VTable
96928** structure is associated with a single sqlite3* user of the schema.
96929** The reference count of the VTable structure associated with database
96930** connection db is decremented immediately (which may lead to the
96931** structure being xDisconnected and free). Any other VTable structures
96932** in the list are moved to the sqlite3.pDisconnect list of the associated
96933** database connection.
96934*/
96935SQLITE_PRIVATE void sqlite3VtabClear(sqlite3 *db, Table *p){
96936  if( !db || db->pnBytesFreed==0 ) vtabDisconnectAll(0, p);
96937  if( p->azModuleArg ){
96938    int i;
96939    for(i=0; i<p->nModuleArg; i++){
96940      sqlite3DbFree(db, p->azModuleArg[i]);
96941    }
96942    sqlite3DbFree(db, p->azModuleArg);
96943  }
96944}
96945
96946/*
96947** Add a new module argument to pTable->azModuleArg[].
96948** The string is not copied - the pointer is stored.  The
96949** string will be freed automatically when the table is
96950** deleted.
96951*/
96952static void addModuleArgument(sqlite3 *db, Table *pTable, char *zArg){
96953  int i = pTable->nModuleArg++;
96954  int nBytes = sizeof(char *)*(1+pTable->nModuleArg);
96955  char **azModuleArg;
96956  azModuleArg = sqlite3DbRealloc(db, pTable->azModuleArg, nBytes);
96957  if( azModuleArg==0 ){
96958    int j;
96959    for(j=0; j<i; j++){
96960      sqlite3DbFree(db, pTable->azModuleArg[j]);
96961    }
96962    sqlite3DbFree(db, zArg);
96963    sqlite3DbFree(db, pTable->azModuleArg);
96964    pTable->nModuleArg = 0;
96965  }else{
96966    azModuleArg[i] = zArg;
96967    azModuleArg[i+1] = 0;
96968  }
96969  pTable->azModuleArg = azModuleArg;
96970}
96971
96972/*
96973** The parser calls this routine when it first sees a CREATE VIRTUAL TABLE
96974** statement.  The module name has been parsed, but the optional list
96975** of parameters that follow the module name are still pending.
96976*/
96977SQLITE_PRIVATE void sqlite3VtabBeginParse(
96978  Parse *pParse,        /* Parsing context */
96979  Token *pName1,        /* Name of new table, or database name */
96980  Token *pName2,        /* Name of new table or NULL */
96981  Token *pModuleName    /* Name of the module for the virtual table */
96982){
96983  int iDb;              /* The database the table is being created in */
96984  Table *pTable;        /* The new virtual table */
96985  sqlite3 *db;          /* Database connection */
96986
96987  sqlite3StartTable(pParse, pName1, pName2, 0, 0, 1, 0);
96988  pTable = pParse->pNewTable;
96989  if( pTable==0 ) return;
96990  assert( 0==pTable->pIndex );
96991
96992  db = pParse->db;
96993  iDb = sqlite3SchemaToIndex(db, pTable->pSchema);
96994  assert( iDb>=0 );
96995
96996  pTable->tabFlags |= TF_Virtual;
96997  pTable->nModuleArg = 0;
96998  addModuleArgument(db, pTable, sqlite3NameFromToken(db, pModuleName));
96999  addModuleArgument(db, pTable, sqlite3DbStrDup(db, db->aDb[iDb].zName));
97000  addModuleArgument(db, pTable, sqlite3DbStrDup(db, pTable->zName));
97001  pParse->sNameToken.n = (int)(&pModuleName->z[pModuleName->n] - pName1->z);
97002
97003#ifndef SQLITE_OMIT_AUTHORIZATION
97004  /* Creating a virtual table invokes the authorization callback twice.
97005  ** The first invocation, to obtain permission to INSERT a row into the
97006  ** sqlite_master table, has already been made by sqlite3StartTable().
97007  ** The second call, to obtain permission to create the table, is made now.
97008  */
97009  if( pTable->azModuleArg ){
97010    sqlite3AuthCheck(pParse, SQLITE_CREATE_VTABLE, pTable->zName,
97011            pTable->azModuleArg[0], pParse->db->aDb[iDb].zName);
97012  }
97013#endif
97014}
97015
97016/*
97017** This routine takes the module argument that has been accumulating
97018** in pParse->zArg[] and appends it to the list of arguments on the
97019** virtual table currently under construction in pParse->pTable.
97020*/
97021static void addArgumentToVtab(Parse *pParse){
97022  if( pParse->sArg.z && ALWAYS(pParse->pNewTable) ){
97023    const char *z = (const char*)pParse->sArg.z;
97024    int n = pParse->sArg.n;
97025    sqlite3 *db = pParse->db;
97026    addModuleArgument(db, pParse->pNewTable, sqlite3DbStrNDup(db, z, n));
97027  }
97028}
97029
97030/*
97031** The parser calls this routine after the CREATE VIRTUAL TABLE statement
97032** has been completely parsed.
97033*/
97034SQLITE_PRIVATE void sqlite3VtabFinishParse(Parse *pParse, Token *pEnd){
97035  Table *pTab = pParse->pNewTable;  /* The table being constructed */
97036  sqlite3 *db = pParse->db;         /* The database connection */
97037
97038  if( pTab==0 ) return;
97039  addArgumentToVtab(pParse);
97040  pParse->sArg.z = 0;
97041  if( pTab->nModuleArg<1 ) return;
97042
97043  /* If the CREATE VIRTUAL TABLE statement is being entered for the
97044  ** first time (in other words if the virtual table is actually being
97045  ** created now instead of just being read out of sqlite_master) then
97046  ** do additional initialization work and store the statement text
97047  ** in the sqlite_master table.
97048  */
97049  if( !db->init.busy ){
97050    char *zStmt;
97051    char *zWhere;
97052    int iDb;
97053    Vdbe *v;
97054
97055    /* Compute the complete text of the CREATE VIRTUAL TABLE statement */
97056    if( pEnd ){
97057      pParse->sNameToken.n = (int)(pEnd->z - pParse->sNameToken.z) + pEnd->n;
97058    }
97059    zStmt = sqlite3MPrintf(db, "CREATE VIRTUAL TABLE %T", &pParse->sNameToken);
97060
97061    /* A slot for the record has already been allocated in the
97062    ** SQLITE_MASTER table.  We just need to update that slot with all
97063    ** the information we've collected.
97064    **
97065    ** The VM register number pParse->regRowid holds the rowid of an
97066    ** entry in the sqlite_master table tht was created for this vtab
97067    ** by sqlite3StartTable().
97068    */
97069    iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
97070    sqlite3NestedParse(pParse,
97071      "UPDATE %Q.%s "
97072         "SET type='table', name=%Q, tbl_name=%Q, rootpage=0, sql=%Q "
97073       "WHERE rowid=#%d",
97074      db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
97075      pTab->zName,
97076      pTab->zName,
97077      zStmt,
97078      pParse->regRowid
97079    );
97080    sqlite3DbFree(db, zStmt);
97081    v = sqlite3GetVdbe(pParse);
97082    sqlite3ChangeCookie(pParse, iDb);
97083
97084    sqlite3VdbeAddOp2(v, OP_Expire, 0, 0);
97085    zWhere = sqlite3MPrintf(db, "name='%q' AND type='table'", pTab->zName);
97086    sqlite3VdbeAddOp4(v, OP_ParseSchema, iDb, 0, 0, zWhere, P4_DYNAMIC);
97087    sqlite3VdbeAddOp4(v, OP_VCreate, iDb, 0, 0,
97088                         pTab->zName, sqlite3Strlen30(pTab->zName) + 1);
97089  }
97090
97091  /* If we are rereading the sqlite_master table create the in-memory
97092  ** record of the table. The xConnect() method is not called until
97093  ** the first time the virtual table is used in an SQL statement. This
97094  ** allows a schema that contains virtual tables to be loaded before
97095  ** the required virtual table implementations are registered.  */
97096  else {
97097    Table *pOld;
97098    Schema *pSchema = pTab->pSchema;
97099    const char *zName = pTab->zName;
97100    int nName = sqlite3Strlen30(zName);
97101    assert( sqlite3SchemaMutexHeld(db, 0, pSchema) );
97102    pOld = sqlite3HashInsert(&pSchema->tblHash, zName, nName, pTab);
97103    if( pOld ){
97104      db->mallocFailed = 1;
97105      assert( pTab==pOld );  /* Malloc must have failed inside HashInsert() */
97106      return;
97107    }
97108    pParse->pNewTable = 0;
97109  }
97110}
97111
97112/*
97113** The parser calls this routine when it sees the first token
97114** of an argument to the module name in a CREATE VIRTUAL TABLE statement.
97115*/
97116SQLITE_PRIVATE void sqlite3VtabArgInit(Parse *pParse){
97117  addArgumentToVtab(pParse);
97118  pParse->sArg.z = 0;
97119  pParse->sArg.n = 0;
97120}
97121
97122/*
97123** The parser calls this routine for each token after the first token
97124** in an argument to the module name in a CREATE VIRTUAL TABLE statement.
97125*/
97126SQLITE_PRIVATE void sqlite3VtabArgExtend(Parse *pParse, Token *p){
97127  Token *pArg = &pParse->sArg;
97128  if( pArg->z==0 ){
97129    pArg->z = p->z;
97130    pArg->n = p->n;
97131  }else{
97132    assert(pArg->z < p->z);
97133    pArg->n = (int)(&p->z[p->n] - pArg->z);
97134  }
97135}
97136
97137/*
97138** Invoke a virtual table constructor (either xCreate or xConnect). The
97139** pointer to the function to invoke is passed as the fourth parameter
97140** to this procedure.
97141*/
97142static int vtabCallConstructor(
97143  sqlite3 *db,
97144  Table *pTab,
97145  Module *pMod,
97146  int (*xConstruct)(sqlite3*,void*,int,const char*const*,sqlite3_vtab**,char**),
97147  char **pzErr
97148){
97149  VTable *pVTable;
97150  int rc;
97151  const char *const*azArg = (const char *const*)pTab->azModuleArg;
97152  int nArg = pTab->nModuleArg;
97153  char *zErr = 0;
97154  char *zModuleName = sqlite3MPrintf(db, "%s", pTab->zName);
97155
97156  if( !zModuleName ){
97157    return SQLITE_NOMEM;
97158  }
97159
97160  pVTable = sqlite3DbMallocZero(db, sizeof(VTable));
97161  if( !pVTable ){
97162    sqlite3DbFree(db, zModuleName);
97163    return SQLITE_NOMEM;
97164  }
97165  pVTable->db = db;
97166  pVTable->pMod = pMod;
97167
97168  assert( !db->pVTab );
97169  assert( xConstruct );
97170  db->pVTab = pTab;
97171
97172  /* Invoke the virtual table constructor */
97173  rc = xConstruct(db, pMod->pAux, nArg, azArg, &pVTable->pVtab, &zErr);
97174  if( rc==SQLITE_NOMEM ) db->mallocFailed = 1;
97175
97176  if( SQLITE_OK!=rc ){
97177    if( zErr==0 ){
97178      *pzErr = sqlite3MPrintf(db, "vtable constructor failed: %s", zModuleName);
97179    }else {
97180      *pzErr = sqlite3MPrintf(db, "%s", zErr);
97181      sqlite3_free(zErr);
97182    }
97183    sqlite3DbFree(db, pVTable);
97184  }else if( ALWAYS(pVTable->pVtab) ){
97185    /* Justification of ALWAYS():  A correct vtab constructor must allocate
97186    ** the sqlite3_vtab object if successful.  */
97187    pVTable->pVtab->pModule = pMod->pModule;
97188    pVTable->nRef = 1;
97189    if( db->pVTab ){
97190      const char *zFormat = "vtable constructor did not declare schema: %s";
97191      *pzErr = sqlite3MPrintf(db, zFormat, pTab->zName);
97192      sqlite3VtabUnlock(pVTable);
97193      rc = SQLITE_ERROR;
97194    }else{
97195      int iCol;
97196      /* If everything went according to plan, link the new VTable structure
97197      ** into the linked list headed by pTab->pVTable. Then loop through the
97198      ** columns of the table to see if any of them contain the token "hidden".
97199      ** If so, set the Column.isHidden flag and remove the token from
97200      ** the type string.  */
97201      pVTable->pNext = pTab->pVTable;
97202      pTab->pVTable = pVTable;
97203
97204      for(iCol=0; iCol<pTab->nCol; iCol++){
97205        char *zType = pTab->aCol[iCol].zType;
97206        int nType;
97207        int i = 0;
97208        if( !zType ) continue;
97209        nType = sqlite3Strlen30(zType);
97210        if( sqlite3StrNICmp("hidden", zType, 6)||(zType[6] && zType[6]!=' ') ){
97211          for(i=0; i<nType; i++){
97212            if( (0==sqlite3StrNICmp(" hidden", &zType[i], 7))
97213             && (zType[i+7]=='\0' || zType[i+7]==' ')
97214            ){
97215              i++;
97216              break;
97217            }
97218          }
97219        }
97220        if( i<nType ){
97221          int j;
97222          int nDel = 6 + (zType[i+6] ? 1 : 0);
97223          for(j=i; (j+nDel)<=nType; j++){
97224            zType[j] = zType[j+nDel];
97225          }
97226          if( zType[i]=='\0' && i>0 ){
97227            assert(zType[i-1]==' ');
97228            zType[i-1] = '\0';
97229          }
97230          pTab->aCol[iCol].isHidden = 1;
97231        }
97232      }
97233    }
97234  }
97235
97236  sqlite3DbFree(db, zModuleName);
97237  db->pVTab = 0;
97238  return rc;
97239}
97240
97241/*
97242** This function is invoked by the parser to call the xConnect() method
97243** of the virtual table pTab. If an error occurs, an error code is returned
97244** and an error left in pParse.
97245**
97246** This call is a no-op if table pTab is not a virtual table.
97247*/
97248SQLITE_PRIVATE int sqlite3VtabCallConnect(Parse *pParse, Table *pTab){
97249  sqlite3 *db = pParse->db;
97250  const char *zMod;
97251  Module *pMod;
97252  int rc;
97253
97254  assert( pTab );
97255  if( (pTab->tabFlags & TF_Virtual)==0 || sqlite3GetVTable(db, pTab) ){
97256    return SQLITE_OK;
97257  }
97258
97259  /* Locate the required virtual table module */
97260  zMod = pTab->azModuleArg[0];
97261  pMod = (Module*)sqlite3HashFind(&db->aModule, zMod, sqlite3Strlen30(zMod));
97262
97263  if( !pMod ){
97264    const char *zModule = pTab->azModuleArg[0];
97265    sqlite3ErrorMsg(pParse, "no such module: %s", zModule);
97266    rc = SQLITE_ERROR;
97267  }else{
97268    char *zErr = 0;
97269    rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xConnect, &zErr);
97270    if( rc!=SQLITE_OK ){
97271      sqlite3ErrorMsg(pParse, "%s", zErr);
97272    }
97273    sqlite3DbFree(db, zErr);
97274  }
97275
97276  return rc;
97277}
97278
97279/*
97280** Add the virtual table pVTab to the array sqlite3.aVTrans[].
97281*/
97282static int addToVTrans(sqlite3 *db, VTable *pVTab){
97283  const int ARRAY_INCR = 5;
97284
97285  /* Grow the sqlite3.aVTrans array if required */
97286  if( (db->nVTrans%ARRAY_INCR)==0 ){
97287    VTable **aVTrans;
97288    int nBytes = sizeof(sqlite3_vtab *) * (db->nVTrans + ARRAY_INCR);
97289    aVTrans = sqlite3DbRealloc(db, (void *)db->aVTrans, nBytes);
97290    if( !aVTrans ){
97291      return SQLITE_NOMEM;
97292    }
97293    memset(&aVTrans[db->nVTrans], 0, sizeof(sqlite3_vtab *)*ARRAY_INCR);
97294    db->aVTrans = aVTrans;
97295  }
97296
97297  /* Add pVtab to the end of sqlite3.aVTrans */
97298  db->aVTrans[db->nVTrans++] = pVTab;
97299  sqlite3VtabLock(pVTab);
97300  return SQLITE_OK;
97301}
97302
97303/*
97304** This function is invoked by the vdbe to call the xCreate method
97305** of the virtual table named zTab in database iDb.
97306**
97307** If an error occurs, *pzErr is set to point an an English language
97308** description of the error and an SQLITE_XXX error code is returned.
97309** In this case the caller must call sqlite3DbFree(db, ) on *pzErr.
97310*/
97311SQLITE_PRIVATE int sqlite3VtabCallCreate(sqlite3 *db, int iDb, const char *zTab, char **pzErr){
97312  int rc = SQLITE_OK;
97313  Table *pTab;
97314  Module *pMod;
97315  const char *zMod;
97316
97317  pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zName);
97318  assert( pTab && (pTab->tabFlags & TF_Virtual)!=0 && !pTab->pVTable );
97319
97320  /* Locate the required virtual table module */
97321  zMod = pTab->azModuleArg[0];
97322  pMod = (Module*)sqlite3HashFind(&db->aModule, zMod, sqlite3Strlen30(zMod));
97323
97324  /* If the module has been registered and includes a Create method,
97325  ** invoke it now. If the module has not been registered, return an
97326  ** error. Otherwise, do nothing.
97327  */
97328  if( !pMod ){
97329    *pzErr = sqlite3MPrintf(db, "no such module: %s", zMod);
97330    rc = SQLITE_ERROR;
97331  }else{
97332    rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xCreate, pzErr);
97333  }
97334
97335  /* Justification of ALWAYS():  The xConstructor method is required to
97336  ** create a valid sqlite3_vtab if it returns SQLITE_OK. */
97337  if( rc==SQLITE_OK && ALWAYS(sqlite3GetVTable(db, pTab)) ){
97338      rc = addToVTrans(db, sqlite3GetVTable(db, pTab));
97339  }
97340
97341  return rc;
97342}
97343
97344/*
97345** This function is used to set the schema of a virtual table.  It is only
97346** valid to call this function from within the xCreate() or xConnect() of a
97347** virtual table module.
97348*/
97349SQLITE_API int sqlite3_declare_vtab(sqlite3 *db, const char *zCreateTable){
97350  Parse *pParse;
97351
97352  int rc = SQLITE_OK;
97353  Table *pTab;
97354  char *zErr = 0;
97355
97356  sqlite3_mutex_enter(db->mutex);
97357  pTab = db->pVTab;
97358  if( !pTab ){
97359    sqlite3Error(db, SQLITE_MISUSE, 0);
97360    sqlite3_mutex_leave(db->mutex);
97361    return SQLITE_MISUSE_BKPT;
97362  }
97363  assert( (pTab->tabFlags & TF_Virtual)!=0 );
97364
97365  pParse = sqlite3StackAllocZero(db, sizeof(*pParse));
97366  if( pParse==0 ){
97367    rc = SQLITE_NOMEM;
97368  }else{
97369    pParse->declareVtab = 1;
97370    pParse->db = db;
97371    pParse->nQueryLoop = 1;
97372
97373    if( SQLITE_OK==sqlite3RunParser(pParse, zCreateTable, &zErr)
97374     && pParse->pNewTable
97375     && !db->mallocFailed
97376     && !pParse->pNewTable->pSelect
97377     && (pParse->pNewTable->tabFlags & TF_Virtual)==0
97378    ){
97379      if( !pTab->aCol ){
97380        pTab->aCol = pParse->pNewTable->aCol;
97381        pTab->nCol = pParse->pNewTable->nCol;
97382        pParse->pNewTable->nCol = 0;
97383        pParse->pNewTable->aCol = 0;
97384      }
97385      db->pVTab = 0;
97386    }else{
97387      sqlite3Error(db, SQLITE_ERROR, (zErr ? "%s" : 0), zErr);
97388      sqlite3DbFree(db, zErr);
97389      rc = SQLITE_ERROR;
97390    }
97391    pParse->declareVtab = 0;
97392
97393    if( pParse->pVdbe ){
97394      sqlite3VdbeFinalize(pParse->pVdbe);
97395    }
97396    sqlite3DeleteTable(db, pParse->pNewTable);
97397    sqlite3StackFree(db, pParse);
97398  }
97399
97400  assert( (rc&0xff)==rc );
97401  rc = sqlite3ApiExit(db, rc);
97402  sqlite3_mutex_leave(db->mutex);
97403  return rc;
97404}
97405
97406/*
97407** This function is invoked by the vdbe to call the xDestroy method
97408** of the virtual table named zTab in database iDb. This occurs
97409** when a DROP TABLE is mentioned.
97410**
97411** This call is a no-op if zTab is not a virtual table.
97412*/
97413SQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3 *db, int iDb, const char *zTab){
97414  int rc = SQLITE_OK;
97415  Table *pTab;
97416
97417  pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zName);
97418  if( ALWAYS(pTab!=0 && pTab->pVTable!=0) ){
97419    VTable *p = vtabDisconnectAll(db, pTab);
97420
97421    assert( rc==SQLITE_OK );
97422    rc = p->pMod->pModule->xDestroy(p->pVtab);
97423
97424    /* Remove the sqlite3_vtab* from the aVTrans[] array, if applicable */
97425    if( rc==SQLITE_OK ){
97426      assert( pTab->pVTable==p && p->pNext==0 );
97427      p->pVtab = 0;
97428      pTab->pVTable = 0;
97429      sqlite3VtabUnlock(p);
97430    }
97431  }
97432
97433  return rc;
97434}
97435
97436/*
97437** This function invokes either the xRollback or xCommit method
97438** of each of the virtual tables in the sqlite3.aVTrans array. The method
97439** called is identified by the second argument, "offset", which is
97440** the offset of the method to call in the sqlite3_module structure.
97441**
97442** The array is cleared after invoking the callbacks.
97443*/
97444static void callFinaliser(sqlite3 *db, int offset){
97445  int i;
97446  if( db->aVTrans ){
97447    for(i=0; i<db->nVTrans; i++){
97448      VTable *pVTab = db->aVTrans[i];
97449      sqlite3_vtab *p = pVTab->pVtab;
97450      if( p ){
97451        int (*x)(sqlite3_vtab *);
97452        x = *(int (**)(sqlite3_vtab *))((char *)p->pModule + offset);
97453        if( x ) x(p);
97454      }
97455      sqlite3VtabUnlock(pVTab);
97456    }
97457    sqlite3DbFree(db, db->aVTrans);
97458    db->nVTrans = 0;
97459    db->aVTrans = 0;
97460  }
97461}
97462
97463/*
97464** Invoke the xSync method of all virtual tables in the sqlite3.aVTrans
97465** array. Return the error code for the first error that occurs, or
97466** SQLITE_OK if all xSync operations are successful.
97467**
97468** Set *pzErrmsg to point to a buffer that should be released using
97469** sqlite3DbFree() containing an error message, if one is available.
97470*/
97471SQLITE_PRIVATE int sqlite3VtabSync(sqlite3 *db, char **pzErrmsg){
97472  int i;
97473  int rc = SQLITE_OK;
97474  VTable **aVTrans = db->aVTrans;
97475
97476  db->aVTrans = 0;
97477  for(i=0; rc==SQLITE_OK && i<db->nVTrans; i++){
97478    int (*x)(sqlite3_vtab *);
97479    sqlite3_vtab *pVtab = aVTrans[i]->pVtab;
97480    if( pVtab && (x = pVtab->pModule->xSync)!=0 ){
97481      rc = x(pVtab);
97482      sqlite3DbFree(db, *pzErrmsg);
97483      *pzErrmsg = sqlite3DbStrDup(db, pVtab->zErrMsg);
97484      sqlite3_free(pVtab->zErrMsg);
97485    }
97486  }
97487  db->aVTrans = aVTrans;
97488  return rc;
97489}
97490
97491/*
97492** Invoke the xRollback method of all virtual tables in the
97493** sqlite3.aVTrans array. Then clear the array itself.
97494*/
97495SQLITE_PRIVATE int sqlite3VtabRollback(sqlite3 *db){
97496  callFinaliser(db, offsetof(sqlite3_module,xRollback));
97497  return SQLITE_OK;
97498}
97499
97500/*
97501** Invoke the xCommit method of all virtual tables in the
97502** sqlite3.aVTrans array. Then clear the array itself.
97503*/
97504SQLITE_PRIVATE int sqlite3VtabCommit(sqlite3 *db){
97505  callFinaliser(db, offsetof(sqlite3_module,xCommit));
97506  return SQLITE_OK;
97507}
97508
97509/*
97510** If the virtual table pVtab supports the transaction interface
97511** (xBegin/xRollback/xCommit and optionally xSync) and a transaction is
97512** not currently open, invoke the xBegin method now.
97513**
97514** If the xBegin call is successful, place the sqlite3_vtab pointer
97515** in the sqlite3.aVTrans array.
97516*/
97517SQLITE_PRIVATE int sqlite3VtabBegin(sqlite3 *db, VTable *pVTab){
97518  int rc = SQLITE_OK;
97519  const sqlite3_module *pModule;
97520
97521  /* Special case: If db->aVTrans is NULL and db->nVTrans is greater
97522  ** than zero, then this function is being called from within a
97523  ** virtual module xSync() callback. It is illegal to write to
97524  ** virtual module tables in this case, so return SQLITE_LOCKED.
97525  */
97526  if( sqlite3VtabInSync(db) ){
97527    return SQLITE_LOCKED;
97528  }
97529  if( !pVTab ){
97530    return SQLITE_OK;
97531  }
97532  pModule = pVTab->pVtab->pModule;
97533
97534  if( pModule->xBegin ){
97535    int i;
97536
97537
97538    /* If pVtab is already in the aVTrans array, return early */
97539    for(i=0; i<db->nVTrans; i++){
97540      if( db->aVTrans[i]==pVTab ){
97541        return SQLITE_OK;
97542      }
97543    }
97544
97545    /* Invoke the xBegin method */
97546    rc = pModule->xBegin(pVTab->pVtab);
97547    if( rc==SQLITE_OK ){
97548      rc = addToVTrans(db, pVTab);
97549    }
97550  }
97551  return rc;
97552}
97553
97554/*
97555** The first parameter (pDef) is a function implementation.  The
97556** second parameter (pExpr) is the first argument to this function.
97557** If pExpr is a column in a virtual table, then let the virtual
97558** table implementation have an opportunity to overload the function.
97559**
97560** This routine is used to allow virtual table implementations to
97561** overload MATCH, LIKE, GLOB, and REGEXP operators.
97562**
97563** Return either the pDef argument (indicating no change) or a
97564** new FuncDef structure that is marked as ephemeral using the
97565** SQLITE_FUNC_EPHEM flag.
97566*/
97567SQLITE_PRIVATE FuncDef *sqlite3VtabOverloadFunction(
97568  sqlite3 *db,    /* Database connection for reporting malloc problems */
97569  FuncDef *pDef,  /* Function to possibly overload */
97570  int nArg,       /* Number of arguments to the function */
97571  Expr *pExpr     /* First argument to the function */
97572){
97573  Table *pTab;
97574  sqlite3_vtab *pVtab;
97575  sqlite3_module *pMod;
97576  void (*xFunc)(sqlite3_context*,int,sqlite3_value**) = 0;
97577  void *pArg = 0;
97578  FuncDef *pNew;
97579  int rc = 0;
97580  char *zLowerName;
97581  unsigned char *z;
97582
97583
97584  /* Check to see the left operand is a column in a virtual table */
97585  if( NEVER(pExpr==0) ) return pDef;
97586  if( pExpr->op!=TK_COLUMN ) return pDef;
97587  pTab = pExpr->pTab;
97588  if( NEVER(pTab==0) ) return pDef;
97589  if( (pTab->tabFlags & TF_Virtual)==0 ) return pDef;
97590  pVtab = sqlite3GetVTable(db, pTab)->pVtab;
97591  assert( pVtab!=0 );
97592  assert( pVtab->pModule!=0 );
97593  pMod = (sqlite3_module *)pVtab->pModule;
97594  if( pMod->xFindFunction==0 ) return pDef;
97595
97596  /* Call the xFindFunction method on the virtual table implementation
97597  ** to see if the implementation wants to overload this function
97598  */
97599  zLowerName = sqlite3DbStrDup(db, pDef->zName);
97600  if( zLowerName ){
97601    for(z=(unsigned char*)zLowerName; *z; z++){
97602      *z = sqlite3UpperToLower[*z];
97603    }
97604    rc = pMod->xFindFunction(pVtab, nArg, zLowerName, &xFunc, &pArg);
97605    sqlite3DbFree(db, zLowerName);
97606  }
97607  if( rc==0 ){
97608    return pDef;
97609  }
97610
97611  /* Create a new ephemeral function definition for the overloaded
97612  ** function */
97613  pNew = sqlite3DbMallocZero(db, sizeof(*pNew)
97614                             + sqlite3Strlen30(pDef->zName) + 1);
97615  if( pNew==0 ){
97616    return pDef;
97617  }
97618  *pNew = *pDef;
97619  pNew->zName = (char *)&pNew[1];
97620  memcpy(pNew->zName, pDef->zName, sqlite3Strlen30(pDef->zName)+1);
97621  pNew->xFunc = xFunc;
97622  pNew->pUserData = pArg;
97623  pNew->flags |= SQLITE_FUNC_EPHEM;
97624  return pNew;
97625}
97626
97627/*
97628** Make sure virtual table pTab is contained in the pParse->apVirtualLock[]
97629** array so that an OP_VBegin will get generated for it.  Add pTab to the
97630** array if it is missing.  If pTab is already in the array, this routine
97631** is a no-op.
97632*/
97633SQLITE_PRIVATE void sqlite3VtabMakeWritable(Parse *pParse, Table *pTab){
97634  Parse *pToplevel = sqlite3ParseToplevel(pParse);
97635  int i, n;
97636  Table **apVtabLock;
97637
97638  assert( IsVirtual(pTab) );
97639  for(i=0; i<pToplevel->nVtabLock; i++){
97640    if( pTab==pToplevel->apVtabLock[i] ) return;
97641  }
97642  n = (pToplevel->nVtabLock+1)*sizeof(pToplevel->apVtabLock[0]);
97643  apVtabLock = sqlite3_realloc(pToplevel->apVtabLock, n);
97644  if( apVtabLock ){
97645    pToplevel->apVtabLock = apVtabLock;
97646    pToplevel->apVtabLock[pToplevel->nVtabLock++] = pTab;
97647  }else{
97648    pToplevel->db->mallocFailed = 1;
97649  }
97650}
97651
97652#endif /* SQLITE_OMIT_VIRTUALTABLE */
97653
97654/************** End of vtab.c ************************************************/
97655/************** Begin file where.c *******************************************/
97656/*
97657** 2001 September 15
97658**
97659** The author disclaims copyright to this source code.  In place of
97660** a legal notice, here is a blessing:
97661**
97662**    May you do good and not evil.
97663**    May you find forgiveness for yourself and forgive others.
97664**    May you share freely, never taking more than you give.
97665**
97666*************************************************************************
97667** This module contains C code that generates VDBE code used to process
97668** the WHERE clause of SQL statements.  This module is responsible for
97669** generating the code that loops through a table looking for applicable
97670** rows.  Indices are selected and used to speed the search when doing
97671** so is applicable.  Because this module is responsible for selecting
97672** indices, you might also think of this module as the "query optimizer".
97673*/
97674
97675
97676/*
97677** Trace output macros
97678*/
97679#if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
97680SQLITE_PRIVATE int sqlite3WhereTrace = 0;
97681#endif
97682#if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
97683# define WHERETRACE(X)  if(sqlite3WhereTrace) sqlite3DebugPrintf X
97684#else
97685# define WHERETRACE(X)
97686#endif
97687
97688/* Forward reference
97689*/
97690typedef struct WhereClause WhereClause;
97691typedef struct WhereMaskSet WhereMaskSet;
97692typedef struct WhereOrInfo WhereOrInfo;
97693typedef struct WhereAndInfo WhereAndInfo;
97694typedef struct WhereCost WhereCost;
97695
97696/*
97697** The query generator uses an array of instances of this structure to
97698** help it analyze the subexpressions of the WHERE clause.  Each WHERE
97699** clause subexpression is separated from the others by AND operators,
97700** usually, or sometimes subexpressions separated by OR.
97701**
97702** All WhereTerms are collected into a single WhereClause structure.
97703** The following identity holds:
97704**
97705**        WhereTerm.pWC->a[WhereTerm.idx] == WhereTerm
97706**
97707** When a term is of the form:
97708**
97709**              X <op> <expr>
97710**
97711** where X is a column name and <op> is one of certain operators,
97712** then WhereTerm.leftCursor and WhereTerm.u.leftColumn record the
97713** cursor number and column number for X.  WhereTerm.eOperator records
97714** the <op> using a bitmask encoding defined by WO_xxx below.  The
97715** use of a bitmask encoding for the operator allows us to search
97716** quickly for terms that match any of several different operators.
97717**
97718** A WhereTerm might also be two or more subterms connected by OR:
97719**
97720**         (t1.X <op> <expr>) OR (t1.Y <op> <expr>) OR ....
97721**
97722** In this second case, wtFlag as the TERM_ORINFO set and eOperator==WO_OR
97723** and the WhereTerm.u.pOrInfo field points to auxiliary information that
97724** is collected about the
97725**
97726** If a term in the WHERE clause does not match either of the two previous
97727** categories, then eOperator==0.  The WhereTerm.pExpr field is still set
97728** to the original subexpression content and wtFlags is set up appropriately
97729** but no other fields in the WhereTerm object are meaningful.
97730**
97731** When eOperator!=0, prereqRight and prereqAll record sets of cursor numbers,
97732** but they do so indirectly.  A single WhereMaskSet structure translates
97733** cursor number into bits and the translated bit is stored in the prereq
97734** fields.  The translation is used in order to maximize the number of
97735** bits that will fit in a Bitmask.  The VDBE cursor numbers might be
97736** spread out over the non-negative integers.  For example, the cursor
97737** numbers might be 3, 8, 9, 10, 20, 23, 41, and 45.  The WhereMaskSet
97738** translates these sparse cursor numbers into consecutive integers
97739** beginning with 0 in order to make the best possible use of the available
97740** bits in the Bitmask.  So, in the example above, the cursor numbers
97741** would be mapped into integers 0 through 7.
97742**
97743** The number of terms in a join is limited by the number of bits
97744** in prereqRight and prereqAll.  The default is 64 bits, hence SQLite
97745** is only able to process joins with 64 or fewer tables.
97746*/
97747typedef struct WhereTerm WhereTerm;
97748struct WhereTerm {
97749  Expr *pExpr;            /* Pointer to the subexpression that is this term */
97750  int iParent;            /* Disable pWC->a[iParent] when this term disabled */
97751  int leftCursor;         /* Cursor number of X in "X <op> <expr>" */
97752  union {
97753    int leftColumn;         /* Column number of X in "X <op> <expr>" */
97754    WhereOrInfo *pOrInfo;   /* Extra information if eOperator==WO_OR */
97755    WhereAndInfo *pAndInfo; /* Extra information if eOperator==WO_AND */
97756  } u;
97757  u16 eOperator;          /* A WO_xx value describing <op> */
97758  u8 wtFlags;             /* TERM_xxx bit flags.  See below */
97759  u8 nChild;              /* Number of children that must disable us */
97760  WhereClause *pWC;       /* The clause this term is part of */
97761  Bitmask prereqRight;    /* Bitmask of tables used by pExpr->pRight */
97762  Bitmask prereqAll;      /* Bitmask of tables referenced by pExpr */
97763};
97764
97765/*
97766** Allowed values of WhereTerm.wtFlags
97767*/
97768#define TERM_DYNAMIC    0x01   /* Need to call sqlite3ExprDelete(db, pExpr) */
97769#define TERM_VIRTUAL    0x02   /* Added by the optimizer.  Do not code */
97770#define TERM_CODED      0x04   /* This term is already coded */
97771#define TERM_COPIED     0x08   /* Has a child */
97772#define TERM_ORINFO     0x10   /* Need to free the WhereTerm.u.pOrInfo object */
97773#define TERM_ANDINFO    0x20   /* Need to free the WhereTerm.u.pAndInfo obj */
97774#define TERM_OR_OK      0x40   /* Used during OR-clause processing */
97775#ifdef SQLITE_ENABLE_STAT2
97776#  define TERM_VNULL    0x80   /* Manufactured x>NULL or x<=NULL term */
97777#else
97778#  define TERM_VNULL    0x00   /* Disabled if not using stat2 */
97779#endif
97780
97781/*
97782** An instance of the following structure holds all information about a
97783** WHERE clause.  Mostly this is a container for one or more WhereTerms.
97784*/
97785struct WhereClause {
97786  Parse *pParse;           /* The parser context */
97787  WhereMaskSet *pMaskSet;  /* Mapping of table cursor numbers to bitmasks */
97788  Bitmask vmask;           /* Bitmask identifying virtual table cursors */
97789  u8 op;                   /* Split operator.  TK_AND or TK_OR */
97790  int nTerm;               /* Number of terms */
97791  int nSlot;               /* Number of entries in a[] */
97792  WhereTerm *a;            /* Each a[] describes a term of the WHERE cluase */
97793#if defined(SQLITE_SMALL_STACK)
97794  WhereTerm aStatic[1];    /* Initial static space for a[] */
97795#else
97796  WhereTerm aStatic[8];    /* Initial static space for a[] */
97797#endif
97798};
97799
97800/*
97801** A WhereTerm with eOperator==WO_OR has its u.pOrInfo pointer set to
97802** a dynamically allocated instance of the following structure.
97803*/
97804struct WhereOrInfo {
97805  WhereClause wc;          /* Decomposition into subterms */
97806  Bitmask indexable;       /* Bitmask of all indexable tables in the clause */
97807};
97808
97809/*
97810** A WhereTerm with eOperator==WO_AND has its u.pAndInfo pointer set to
97811** a dynamically allocated instance of the following structure.
97812*/
97813struct WhereAndInfo {
97814  WhereClause wc;          /* The subexpression broken out */
97815};
97816
97817/*
97818** An instance of the following structure keeps track of a mapping
97819** between VDBE cursor numbers and bits of the bitmasks in WhereTerm.
97820**
97821** The VDBE cursor numbers are small integers contained in
97822** SrcList_item.iCursor and Expr.iTable fields.  For any given WHERE
97823** clause, the cursor numbers might not begin with 0 and they might
97824** contain gaps in the numbering sequence.  But we want to make maximum
97825** use of the bits in our bitmasks.  This structure provides a mapping
97826** from the sparse cursor numbers into consecutive integers beginning
97827** with 0.
97828**
97829** If WhereMaskSet.ix[A]==B it means that The A-th bit of a Bitmask
97830** corresponds VDBE cursor number B.  The A-th bit of a bitmask is 1<<A.
97831**
97832** For example, if the WHERE clause expression used these VDBE
97833** cursors:  4, 5, 8, 29, 57, 73.  Then the  WhereMaskSet structure
97834** would map those cursor numbers into bits 0 through 5.
97835**
97836** Note that the mapping is not necessarily ordered.  In the example
97837** above, the mapping might go like this:  4->3, 5->1, 8->2, 29->0,
97838** 57->5, 73->4.  Or one of 719 other combinations might be used. It
97839** does not really matter.  What is important is that sparse cursor
97840** numbers all get mapped into bit numbers that begin with 0 and contain
97841** no gaps.
97842*/
97843struct WhereMaskSet {
97844  int n;                        /* Number of assigned cursor values */
97845  int ix[BMS];                  /* Cursor assigned to each bit */
97846};
97847
97848/*
97849** A WhereCost object records a lookup strategy and the estimated
97850** cost of pursuing that strategy.
97851*/
97852struct WhereCost {
97853  WherePlan plan;    /* The lookup strategy */
97854  double rCost;      /* Overall cost of pursuing this search strategy */
97855  Bitmask used;      /* Bitmask of cursors used by this plan */
97856};
97857
97858/*
97859** Bitmasks for the operators that indices are able to exploit.  An
97860** OR-ed combination of these values can be used when searching for
97861** terms in the where clause.
97862*/
97863#define WO_IN     0x001
97864#define WO_EQ     0x002
97865#define WO_LT     (WO_EQ<<(TK_LT-TK_EQ))
97866#define WO_LE     (WO_EQ<<(TK_LE-TK_EQ))
97867#define WO_GT     (WO_EQ<<(TK_GT-TK_EQ))
97868#define WO_GE     (WO_EQ<<(TK_GE-TK_EQ))
97869#define WO_MATCH  0x040
97870#define WO_ISNULL 0x080
97871#define WO_OR     0x100       /* Two or more OR-connected terms */
97872#define WO_AND    0x200       /* Two or more AND-connected terms */
97873#define WO_NOOP   0x800       /* This term does not restrict search space */
97874
97875#define WO_ALL    0xfff       /* Mask of all possible WO_* values */
97876#define WO_SINGLE 0x0ff       /* Mask of all non-compound WO_* values */
97877
97878/*
97879** Value for wsFlags returned by bestIndex() and stored in
97880** WhereLevel.wsFlags.  These flags determine which search
97881** strategies are appropriate.
97882**
97883** The least significant 12 bits is reserved as a mask for WO_ values above.
97884** The WhereLevel.wsFlags field is usually set to WO_IN|WO_EQ|WO_ISNULL.
97885** But if the table is the right table of a left join, WhereLevel.wsFlags
97886** is set to WO_IN|WO_EQ.  The WhereLevel.wsFlags field can then be used as
97887** the "op" parameter to findTerm when we are resolving equality constraints.
97888** ISNULL constraints will then not be used on the right table of a left
97889** join.  Tickets #2177 and #2189.
97890*/
97891#define WHERE_ROWID_EQ     0x00001000  /* rowid=EXPR or rowid IN (...) */
97892#define WHERE_ROWID_RANGE  0x00002000  /* rowid<EXPR and/or rowid>EXPR */
97893#define WHERE_COLUMN_EQ    0x00010000  /* x=EXPR or x IN (...) or x IS NULL */
97894#define WHERE_COLUMN_RANGE 0x00020000  /* x<EXPR and/or x>EXPR */
97895#define WHERE_COLUMN_IN    0x00040000  /* x IN (...) */
97896#define WHERE_COLUMN_NULL  0x00080000  /* x IS NULL */
97897#define WHERE_INDEXED      0x000f0000  /* Anything that uses an index */
97898#define WHERE_NOT_FULLSCAN 0x100f3000  /* Does not do a full table scan */
97899#define WHERE_IN_ABLE      0x000f1000  /* Able to support an IN operator */
97900#define WHERE_TOP_LIMIT    0x00100000  /* x<EXPR or x<=EXPR constraint */
97901#define WHERE_BTM_LIMIT    0x00200000  /* x>EXPR or x>=EXPR constraint */
97902#define WHERE_BOTH_LIMIT   0x00300000  /* Both x>EXPR and x<EXPR */
97903#define WHERE_IDX_ONLY     0x00800000  /* Use index only - omit table */
97904#define WHERE_ORDERBY      0x01000000  /* Output will appear in correct order */
97905#define WHERE_REVERSE      0x02000000  /* Scan in reverse order */
97906#define WHERE_UNIQUE       0x04000000  /* Selects no more than one row */
97907#define WHERE_VIRTUALTABLE 0x08000000  /* Use virtual-table processing */
97908#define WHERE_MULTI_OR     0x10000000  /* OR using multiple indices */
97909#define WHERE_TEMP_INDEX   0x20000000  /* Uses an ephemeral index */
97910
97911/*
97912** Initialize a preallocated WhereClause structure.
97913*/
97914static void whereClauseInit(
97915  WhereClause *pWC,        /* The WhereClause to be initialized */
97916  Parse *pParse,           /* The parsing context */
97917  WhereMaskSet *pMaskSet   /* Mapping from table cursor numbers to bitmasks */
97918){
97919  pWC->pParse = pParse;
97920  pWC->pMaskSet = pMaskSet;
97921  pWC->nTerm = 0;
97922  pWC->nSlot = ArraySize(pWC->aStatic);
97923  pWC->a = pWC->aStatic;
97924  pWC->vmask = 0;
97925}
97926
97927/* Forward reference */
97928static void whereClauseClear(WhereClause*);
97929
97930/*
97931** Deallocate all memory associated with a WhereOrInfo object.
97932*/
97933static void whereOrInfoDelete(sqlite3 *db, WhereOrInfo *p){
97934  whereClauseClear(&p->wc);
97935  sqlite3DbFree(db, p);
97936}
97937
97938/*
97939** Deallocate all memory associated with a WhereAndInfo object.
97940*/
97941static void whereAndInfoDelete(sqlite3 *db, WhereAndInfo *p){
97942  whereClauseClear(&p->wc);
97943  sqlite3DbFree(db, p);
97944}
97945
97946/*
97947** Deallocate a WhereClause structure.  The WhereClause structure
97948** itself is not freed.  This routine is the inverse of whereClauseInit().
97949*/
97950static void whereClauseClear(WhereClause *pWC){
97951  int i;
97952  WhereTerm *a;
97953  sqlite3 *db = pWC->pParse->db;
97954  for(i=pWC->nTerm-1, a=pWC->a; i>=0; i--, a++){
97955    if( a->wtFlags & TERM_DYNAMIC ){
97956      sqlite3ExprDelete(db, a->pExpr);
97957    }
97958    if( a->wtFlags & TERM_ORINFO ){
97959      whereOrInfoDelete(db, a->u.pOrInfo);
97960    }else if( a->wtFlags & TERM_ANDINFO ){
97961      whereAndInfoDelete(db, a->u.pAndInfo);
97962    }
97963  }
97964  if( pWC->a!=pWC->aStatic ){
97965    sqlite3DbFree(db, pWC->a);
97966  }
97967}
97968
97969/*
97970** Add a single new WhereTerm entry to the WhereClause object pWC.
97971** The new WhereTerm object is constructed from Expr p and with wtFlags.
97972** The index in pWC->a[] of the new WhereTerm is returned on success.
97973** 0 is returned if the new WhereTerm could not be added due to a memory
97974** allocation error.  The memory allocation failure will be recorded in
97975** the db->mallocFailed flag so that higher-level functions can detect it.
97976**
97977** This routine will increase the size of the pWC->a[] array as necessary.
97978**
97979** If the wtFlags argument includes TERM_DYNAMIC, then responsibility
97980** for freeing the expression p is assumed by the WhereClause object pWC.
97981** This is true even if this routine fails to allocate a new WhereTerm.
97982**
97983** WARNING:  This routine might reallocate the space used to store
97984** WhereTerms.  All pointers to WhereTerms should be invalidated after
97985** calling this routine.  Such pointers may be reinitialized by referencing
97986** the pWC->a[] array.
97987*/
97988static int whereClauseInsert(WhereClause *pWC, Expr *p, u8 wtFlags){
97989  WhereTerm *pTerm;
97990  int idx;
97991  testcase( wtFlags & TERM_VIRTUAL );  /* EV: R-00211-15100 */
97992  if( pWC->nTerm>=pWC->nSlot ){
97993    WhereTerm *pOld = pWC->a;
97994    sqlite3 *db = pWC->pParse->db;
97995    pWC->a = sqlite3DbMallocRaw(db, sizeof(pWC->a[0])*pWC->nSlot*2 );
97996    if( pWC->a==0 ){
97997      if( wtFlags & TERM_DYNAMIC ){
97998        sqlite3ExprDelete(db, p);
97999      }
98000      pWC->a = pOld;
98001      return 0;
98002    }
98003    memcpy(pWC->a, pOld, sizeof(pWC->a[0])*pWC->nTerm);
98004    if( pOld!=pWC->aStatic ){
98005      sqlite3DbFree(db, pOld);
98006    }
98007    pWC->nSlot = sqlite3DbMallocSize(db, pWC->a)/sizeof(pWC->a[0]);
98008  }
98009  pTerm = &pWC->a[idx = pWC->nTerm++];
98010  pTerm->pExpr = p;
98011  pTerm->wtFlags = wtFlags;
98012  pTerm->pWC = pWC;
98013  pTerm->iParent = -1;
98014  return idx;
98015}
98016
98017/*
98018** This routine identifies subexpressions in the WHERE clause where
98019** each subexpression is separated by the AND operator or some other
98020** operator specified in the op parameter.  The WhereClause structure
98021** is filled with pointers to subexpressions.  For example:
98022**
98023**    WHERE  a=='hello' AND coalesce(b,11)<10 AND (c+12!=d OR c==22)
98024**           \________/     \_______________/     \________________/
98025**            slot[0]            slot[1]               slot[2]
98026**
98027** The original WHERE clause in pExpr is unaltered.  All this routine
98028** does is make slot[] entries point to substructure within pExpr.
98029**
98030** In the previous sentence and in the diagram, "slot[]" refers to
98031** the WhereClause.a[] array.  The slot[] array grows as needed to contain
98032** all terms of the WHERE clause.
98033*/
98034static void whereSplit(WhereClause *pWC, Expr *pExpr, int op){
98035  pWC->op = (u8)op;
98036  if( pExpr==0 ) return;
98037  if( pExpr->op!=op ){
98038    whereClauseInsert(pWC, pExpr, 0);
98039  }else{
98040    whereSplit(pWC, pExpr->pLeft, op);
98041    whereSplit(pWC, pExpr->pRight, op);
98042  }
98043}
98044
98045/*
98046** Initialize an expression mask set (a WhereMaskSet object)
98047*/
98048#define initMaskSet(P)  memset(P, 0, sizeof(*P))
98049
98050/*
98051** Return the bitmask for the given cursor number.  Return 0 if
98052** iCursor is not in the set.
98053*/
98054static Bitmask getMask(WhereMaskSet *pMaskSet, int iCursor){
98055  int i;
98056  assert( pMaskSet->n<=(int)sizeof(Bitmask)*8 );
98057  for(i=0; i<pMaskSet->n; i++){
98058    if( pMaskSet->ix[i]==iCursor ){
98059      return ((Bitmask)1)<<i;
98060    }
98061  }
98062  return 0;
98063}
98064
98065/*
98066** Create a new mask for cursor iCursor.
98067**
98068** There is one cursor per table in the FROM clause.  The number of
98069** tables in the FROM clause is limited by a test early in the
98070** sqlite3WhereBegin() routine.  So we know that the pMaskSet->ix[]
98071** array will never overflow.
98072*/
98073static void createMask(WhereMaskSet *pMaskSet, int iCursor){
98074  assert( pMaskSet->n < ArraySize(pMaskSet->ix) );
98075  pMaskSet->ix[pMaskSet->n++] = iCursor;
98076}
98077
98078/*
98079** This routine walks (recursively) an expression tree and generates
98080** a bitmask indicating which tables are used in that expression
98081** tree.
98082**
98083** In order for this routine to work, the calling function must have
98084** previously invoked sqlite3ResolveExprNames() on the expression.  See
98085** the header comment on that routine for additional information.
98086** The sqlite3ResolveExprNames() routines looks for column names and
98087** sets their opcodes to TK_COLUMN and their Expr.iTable fields to
98088** the VDBE cursor number of the table.  This routine just has to
98089** translate the cursor numbers into bitmask values and OR all
98090** the bitmasks together.
98091*/
98092static Bitmask exprListTableUsage(WhereMaskSet*, ExprList*);
98093static Bitmask exprSelectTableUsage(WhereMaskSet*, Select*);
98094static Bitmask exprTableUsage(WhereMaskSet *pMaskSet, Expr *p){
98095  Bitmask mask = 0;
98096  if( p==0 ) return 0;
98097  if( p->op==TK_COLUMN ){
98098    mask = getMask(pMaskSet, p->iTable);
98099    return mask;
98100  }
98101  mask = exprTableUsage(pMaskSet, p->pRight);
98102  mask |= exprTableUsage(pMaskSet, p->pLeft);
98103  if( ExprHasProperty(p, EP_xIsSelect) ){
98104    mask |= exprSelectTableUsage(pMaskSet, p->x.pSelect);
98105  }else{
98106    mask |= exprListTableUsage(pMaskSet, p->x.pList);
98107  }
98108  return mask;
98109}
98110static Bitmask exprListTableUsage(WhereMaskSet *pMaskSet, ExprList *pList){
98111  int i;
98112  Bitmask mask = 0;
98113  if( pList ){
98114    for(i=0; i<pList->nExpr; i++){
98115      mask |= exprTableUsage(pMaskSet, pList->a[i].pExpr);
98116    }
98117  }
98118  return mask;
98119}
98120static Bitmask exprSelectTableUsage(WhereMaskSet *pMaskSet, Select *pS){
98121  Bitmask mask = 0;
98122  while( pS ){
98123    mask |= exprListTableUsage(pMaskSet, pS->pEList);
98124    mask |= exprListTableUsage(pMaskSet, pS->pGroupBy);
98125    mask |= exprListTableUsage(pMaskSet, pS->pOrderBy);
98126    mask |= exprTableUsage(pMaskSet, pS->pWhere);
98127    mask |= exprTableUsage(pMaskSet, pS->pHaving);
98128    pS = pS->pPrior;
98129  }
98130  return mask;
98131}
98132
98133/*
98134** Return TRUE if the given operator is one of the operators that is
98135** allowed for an indexable WHERE clause term.  The allowed operators are
98136** "=", "<", ">", "<=", ">=", and "IN".
98137**
98138** IMPLEMENTATION-OF: R-59926-26393 To be usable by an index a term must be
98139** of one of the following forms: column = expression column > expression
98140** column >= expression column < expression column <= expression
98141** expression = column expression > column expression >= column
98142** expression < column expression <= column column IN
98143** (expression-list) column IN (subquery) column IS NULL
98144*/
98145static int allowedOp(int op){
98146  assert( TK_GT>TK_EQ && TK_GT<TK_GE );
98147  assert( TK_LT>TK_EQ && TK_LT<TK_GE );
98148  assert( TK_LE>TK_EQ && TK_LE<TK_GE );
98149  assert( TK_GE==TK_EQ+4 );
98150  return op==TK_IN || (op>=TK_EQ && op<=TK_GE) || op==TK_ISNULL;
98151}
98152
98153/*
98154** Swap two objects of type TYPE.
98155*/
98156#define SWAP(TYPE,A,B) {TYPE t=A; A=B; B=t;}
98157
98158/*
98159** Commute a comparison operator.  Expressions of the form "X op Y"
98160** are converted into "Y op X".
98161**
98162** If a collation sequence is associated with either the left or right
98163** side of the comparison, it remains associated with the same side after
98164** the commutation. So "Y collate NOCASE op X" becomes
98165** "X collate NOCASE op Y". This is because any collation sequence on
98166** the left hand side of a comparison overrides any collation sequence
98167** attached to the right. For the same reason the EP_ExpCollate flag
98168** is not commuted.
98169*/
98170static void exprCommute(Parse *pParse, Expr *pExpr){
98171  u16 expRight = (pExpr->pRight->flags & EP_ExpCollate);
98172  u16 expLeft = (pExpr->pLeft->flags & EP_ExpCollate);
98173  assert( allowedOp(pExpr->op) && pExpr->op!=TK_IN );
98174  pExpr->pRight->pColl = sqlite3ExprCollSeq(pParse, pExpr->pRight);
98175  pExpr->pLeft->pColl = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
98176  SWAP(CollSeq*,pExpr->pRight->pColl,pExpr->pLeft->pColl);
98177  pExpr->pRight->flags = (pExpr->pRight->flags & ~EP_ExpCollate) | expLeft;
98178  pExpr->pLeft->flags = (pExpr->pLeft->flags & ~EP_ExpCollate) | expRight;
98179  SWAP(Expr*,pExpr->pRight,pExpr->pLeft);
98180  if( pExpr->op>=TK_GT ){
98181    assert( TK_LT==TK_GT+2 );
98182    assert( TK_GE==TK_LE+2 );
98183    assert( TK_GT>TK_EQ );
98184    assert( TK_GT<TK_LE );
98185    assert( pExpr->op>=TK_GT && pExpr->op<=TK_GE );
98186    pExpr->op = ((pExpr->op-TK_GT)^2)+TK_GT;
98187  }
98188}
98189
98190/*
98191** Translate from TK_xx operator to WO_xx bitmask.
98192*/
98193static u16 operatorMask(int op){
98194  u16 c;
98195  assert( allowedOp(op) );
98196  if( op==TK_IN ){
98197    c = WO_IN;
98198  }else if( op==TK_ISNULL ){
98199    c = WO_ISNULL;
98200  }else{
98201    assert( (WO_EQ<<(op-TK_EQ)) < 0x7fff );
98202    c = (u16)(WO_EQ<<(op-TK_EQ));
98203  }
98204  assert( op!=TK_ISNULL || c==WO_ISNULL );
98205  assert( op!=TK_IN || c==WO_IN );
98206  assert( op!=TK_EQ || c==WO_EQ );
98207  assert( op!=TK_LT || c==WO_LT );
98208  assert( op!=TK_LE || c==WO_LE );
98209  assert( op!=TK_GT || c==WO_GT );
98210  assert( op!=TK_GE || c==WO_GE );
98211  return c;
98212}
98213
98214/*
98215** Search for a term in the WHERE clause that is of the form "X <op> <expr>"
98216** where X is a reference to the iColumn of table iCur and <op> is one of
98217** the WO_xx operator codes specified by the op parameter.
98218** Return a pointer to the term.  Return 0 if not found.
98219*/
98220static WhereTerm *findTerm(
98221  WhereClause *pWC,     /* The WHERE clause to be searched */
98222  int iCur,             /* Cursor number of LHS */
98223  int iColumn,          /* Column number of LHS */
98224  Bitmask notReady,     /* RHS must not overlap with this mask */
98225  u32 op,               /* Mask of WO_xx values describing operator */
98226  Index *pIdx           /* Must be compatible with this index, if not NULL */
98227){
98228  WhereTerm *pTerm;
98229  int k;
98230  assert( iCur>=0 );
98231  op &= WO_ALL;
98232  for(pTerm=pWC->a, k=pWC->nTerm; k; k--, pTerm++){
98233    if( pTerm->leftCursor==iCur
98234       && (pTerm->prereqRight & notReady)==0
98235       && pTerm->u.leftColumn==iColumn
98236       && (pTerm->eOperator & op)!=0
98237    ){
98238      if( pIdx && pTerm->eOperator!=WO_ISNULL ){
98239        Expr *pX = pTerm->pExpr;
98240        CollSeq *pColl;
98241        char idxaff;
98242        int j;
98243        Parse *pParse = pWC->pParse;
98244
98245        idxaff = pIdx->pTable->aCol[iColumn].affinity;
98246        if( !sqlite3IndexAffinityOk(pX, idxaff) ) continue;
98247
98248        /* Figure out the collation sequence required from an index for
98249        ** it to be useful for optimising expression pX. Store this
98250        ** value in variable pColl.
98251        */
98252        assert(pX->pLeft);
98253        pColl = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pX->pRight);
98254        assert(pColl || pParse->nErr);
98255
98256        for(j=0; pIdx->aiColumn[j]!=iColumn; j++){
98257          if( NEVER(j>=pIdx->nColumn) ) return 0;
98258        }
98259        if( pColl && sqlite3StrICmp(pColl->zName, pIdx->azColl[j]) ) continue;
98260      }
98261      return pTerm;
98262    }
98263  }
98264  return 0;
98265}
98266
98267/* Forward reference */
98268static void exprAnalyze(SrcList*, WhereClause*, int);
98269
98270/*
98271** Call exprAnalyze on all terms in a WHERE clause.
98272**
98273**
98274*/
98275static void exprAnalyzeAll(
98276  SrcList *pTabList,       /* the FROM clause */
98277  WhereClause *pWC         /* the WHERE clause to be analyzed */
98278){
98279  int i;
98280  for(i=pWC->nTerm-1; i>=0; i--){
98281    exprAnalyze(pTabList, pWC, i);
98282  }
98283}
98284
98285#ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
98286/*
98287** Check to see if the given expression is a LIKE or GLOB operator that
98288** can be optimized using inequality constraints.  Return TRUE if it is
98289** so and false if not.
98290**
98291** In order for the operator to be optimizible, the RHS must be a string
98292** literal that does not begin with a wildcard.
98293*/
98294static int isLikeOrGlob(
98295  Parse *pParse,    /* Parsing and code generating context */
98296  Expr *pExpr,      /* Test this expression */
98297  Expr **ppPrefix,  /* Pointer to TK_STRING expression with pattern prefix */
98298  int *pisComplete, /* True if the only wildcard is % in the last character */
98299  int *pnoCase      /* True if uppercase is equivalent to lowercase */
98300){
98301  const char *z = 0;         /* String on RHS of LIKE operator */
98302  Expr *pRight, *pLeft;      /* Right and left size of LIKE operator */
98303  ExprList *pList;           /* List of operands to the LIKE operator */
98304  int c;                     /* One character in z[] */
98305  int cnt;                   /* Number of non-wildcard prefix characters */
98306  char wc[3];                /* Wildcard characters */
98307  sqlite3 *db = pParse->db;  /* Database connection */
98308  sqlite3_value *pVal = 0;
98309  int op;                    /* Opcode of pRight */
98310
98311  if( !sqlite3IsLikeFunction(db, pExpr, pnoCase, wc) ){
98312    return 0;
98313  }
98314#ifdef SQLITE_EBCDIC
98315  if( *pnoCase ) return 0;
98316#endif
98317  pList = pExpr->x.pList;
98318  pLeft = pList->a[1].pExpr;
98319  if( pLeft->op!=TK_COLUMN || sqlite3ExprAffinity(pLeft)!=SQLITE_AFF_TEXT ){
98320    /* IMP: R-02065-49465 The left-hand side of the LIKE or GLOB operator must
98321    ** be the name of an indexed column with TEXT affinity. */
98322    return 0;
98323  }
98324  assert( pLeft->iColumn!=(-1) ); /* Because IPK never has AFF_TEXT */
98325
98326  pRight = pList->a[0].pExpr;
98327  op = pRight->op;
98328  if( op==TK_REGISTER ){
98329    op = pRight->op2;
98330  }
98331  if( op==TK_VARIABLE ){
98332    Vdbe *pReprepare = pParse->pReprepare;
98333    int iCol = pRight->iColumn;
98334    pVal = sqlite3VdbeGetValue(pReprepare, iCol, SQLITE_AFF_NONE);
98335    if( pVal && sqlite3_value_type(pVal)==SQLITE_TEXT ){
98336      z = (char *)sqlite3_value_text(pVal);
98337    }
98338    sqlite3VdbeSetVarmask(pParse->pVdbe, iCol); /* IMP: R-23257-02778 */
98339    assert( pRight->op==TK_VARIABLE || pRight->op==TK_REGISTER );
98340  }else if( op==TK_STRING ){
98341    z = pRight->u.zToken;
98342  }
98343  if( z ){
98344    cnt = 0;
98345    while( (c=z[cnt])!=0 && c!=wc[0] && c!=wc[1] && c!=wc[2] ){
98346      cnt++;
98347    }
98348    if( cnt!=0 && 255!=(u8)z[cnt-1] ){
98349      Expr *pPrefix;
98350      *pisComplete = c==wc[0] && z[cnt+1]==0;
98351      pPrefix = sqlite3Expr(db, TK_STRING, z);
98352      if( pPrefix ) pPrefix->u.zToken[cnt] = 0;
98353      *ppPrefix = pPrefix;
98354      if( op==TK_VARIABLE ){
98355        Vdbe *v = pParse->pVdbe;
98356        sqlite3VdbeSetVarmask(v, pRight->iColumn); /* IMP: R-23257-02778 */
98357        if( *pisComplete && pRight->u.zToken[1] ){
98358          /* If the rhs of the LIKE expression is a variable, and the current
98359          ** value of the variable means there is no need to invoke the LIKE
98360          ** function, then no OP_Variable will be added to the program.
98361          ** This causes problems for the sqlite3_bind_parameter_name()
98362          ** API. To workaround them, add a dummy OP_Variable here.
98363          */
98364          int r1 = sqlite3GetTempReg(pParse);
98365          sqlite3ExprCodeTarget(pParse, pRight, r1);
98366          sqlite3VdbeChangeP3(v, sqlite3VdbeCurrentAddr(v)-1, 0);
98367          sqlite3ReleaseTempReg(pParse, r1);
98368        }
98369      }
98370    }else{
98371      z = 0;
98372    }
98373  }
98374
98375  sqlite3ValueFree(pVal);
98376  return (z!=0);
98377}
98378#endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
98379
98380
98381#ifndef SQLITE_OMIT_VIRTUALTABLE
98382/*
98383** Check to see if the given expression is of the form
98384**
98385**         column MATCH expr
98386**
98387** If it is then return TRUE.  If not, return FALSE.
98388*/
98389static int isMatchOfColumn(
98390  Expr *pExpr      /* Test this expression */
98391){
98392  ExprList *pList;
98393
98394  if( pExpr->op!=TK_FUNCTION ){
98395    return 0;
98396  }
98397  if( sqlite3StrICmp(pExpr->u.zToken,"match")!=0 ){
98398    return 0;
98399  }
98400  pList = pExpr->x.pList;
98401  if( pList->nExpr!=2 ){
98402    return 0;
98403  }
98404  if( pList->a[1].pExpr->op != TK_COLUMN ){
98405    return 0;
98406  }
98407  return 1;
98408}
98409#endif /* SQLITE_OMIT_VIRTUALTABLE */
98410
98411/*
98412** If the pBase expression originated in the ON or USING clause of
98413** a join, then transfer the appropriate markings over to derived.
98414*/
98415static void transferJoinMarkings(Expr *pDerived, Expr *pBase){
98416  pDerived->flags |= pBase->flags & EP_FromJoin;
98417  pDerived->iRightJoinTable = pBase->iRightJoinTable;
98418}
98419
98420#if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
98421/*
98422** Analyze a term that consists of two or more OR-connected
98423** subterms.  So in:
98424**
98425**     ... WHERE  (a=5) AND (b=7 OR c=9 OR d=13) AND (d=13)
98426**                          ^^^^^^^^^^^^^^^^^^^^
98427**
98428** This routine analyzes terms such as the middle term in the above example.
98429** A WhereOrTerm object is computed and attached to the term under
98430** analysis, regardless of the outcome of the analysis.  Hence:
98431**
98432**     WhereTerm.wtFlags   |=  TERM_ORINFO
98433**     WhereTerm.u.pOrInfo  =  a dynamically allocated WhereOrTerm object
98434**
98435** The term being analyzed must have two or more of OR-connected subterms.
98436** A single subterm might be a set of AND-connected sub-subterms.
98437** Examples of terms under analysis:
98438**
98439**     (A)     t1.x=t2.y OR t1.x=t2.z OR t1.y=15 OR t1.z=t3.a+5
98440**     (B)     x=expr1 OR expr2=x OR x=expr3
98441**     (C)     t1.x=t2.y OR (t1.x=t2.z AND t1.y=15)
98442**     (D)     x=expr1 OR (y>11 AND y<22 AND z LIKE '*hello*')
98443**     (E)     (p.a=1 AND q.b=2 AND r.c=3) OR (p.x=4 AND q.y=5 AND r.z=6)
98444**
98445** CASE 1:
98446**
98447** If all subterms are of the form T.C=expr for some single column of C
98448** a single table T (as shown in example B above) then create a new virtual
98449** term that is an equivalent IN expression.  In other words, if the term
98450** being analyzed is:
98451**
98452**      x = expr1  OR  expr2 = x  OR  x = expr3
98453**
98454** then create a new virtual term like this:
98455**
98456**      x IN (expr1,expr2,expr3)
98457**
98458** CASE 2:
98459**
98460** If all subterms are indexable by a single table T, then set
98461**
98462**     WhereTerm.eOperator              =  WO_OR
98463**     WhereTerm.u.pOrInfo->indexable  |=  the cursor number for table T
98464**
98465** A subterm is "indexable" if it is of the form
98466** "T.C <op> <expr>" where C is any column of table T and
98467** <op> is one of "=", "<", "<=", ">", ">=", "IS NULL", or "IN".
98468** A subterm is also indexable if it is an AND of two or more
98469** subsubterms at least one of which is indexable.  Indexable AND
98470** subterms have their eOperator set to WO_AND and they have
98471** u.pAndInfo set to a dynamically allocated WhereAndTerm object.
98472**
98473** From another point of view, "indexable" means that the subterm could
98474** potentially be used with an index if an appropriate index exists.
98475** This analysis does not consider whether or not the index exists; that
98476** is something the bestIndex() routine will determine.  This analysis
98477** only looks at whether subterms appropriate for indexing exist.
98478**
98479** All examples A through E above all satisfy case 2.  But if a term
98480** also statisfies case 1 (such as B) we know that the optimizer will
98481** always prefer case 1, so in that case we pretend that case 2 is not
98482** satisfied.
98483**
98484** It might be the case that multiple tables are indexable.  For example,
98485** (E) above is indexable on tables P, Q, and R.
98486**
98487** Terms that satisfy case 2 are candidates for lookup by using
98488** separate indices to find rowids for each subterm and composing
98489** the union of all rowids using a RowSet object.  This is similar
98490** to "bitmap indices" in other database engines.
98491**
98492** OTHERWISE:
98493**
98494** If neither case 1 nor case 2 apply, then leave the eOperator set to
98495** zero.  This term is not useful for search.
98496*/
98497static void exprAnalyzeOrTerm(
98498  SrcList *pSrc,            /* the FROM clause */
98499  WhereClause *pWC,         /* the complete WHERE clause */
98500  int idxTerm               /* Index of the OR-term to be analyzed */
98501){
98502  Parse *pParse = pWC->pParse;            /* Parser context */
98503  sqlite3 *db = pParse->db;               /* Database connection */
98504  WhereTerm *pTerm = &pWC->a[idxTerm];    /* The term to be analyzed */
98505  Expr *pExpr = pTerm->pExpr;             /* The expression of the term */
98506  WhereMaskSet *pMaskSet = pWC->pMaskSet; /* Table use masks */
98507  int i;                                  /* Loop counters */
98508  WhereClause *pOrWc;       /* Breakup of pTerm into subterms */
98509  WhereTerm *pOrTerm;       /* A Sub-term within the pOrWc */
98510  WhereOrInfo *pOrInfo;     /* Additional information associated with pTerm */
98511  Bitmask chngToIN;         /* Tables that might satisfy case 1 */
98512  Bitmask indexable;        /* Tables that are indexable, satisfying case 2 */
98513
98514  /*
98515  ** Break the OR clause into its separate subterms.  The subterms are
98516  ** stored in a WhereClause structure containing within the WhereOrInfo
98517  ** object that is attached to the original OR clause term.
98518  */
98519  assert( (pTerm->wtFlags & (TERM_DYNAMIC|TERM_ORINFO|TERM_ANDINFO))==0 );
98520  assert( pExpr->op==TK_OR );
98521  pTerm->u.pOrInfo = pOrInfo = sqlite3DbMallocZero(db, sizeof(*pOrInfo));
98522  if( pOrInfo==0 ) return;
98523  pTerm->wtFlags |= TERM_ORINFO;
98524  pOrWc = &pOrInfo->wc;
98525  whereClauseInit(pOrWc, pWC->pParse, pMaskSet);
98526  whereSplit(pOrWc, pExpr, TK_OR);
98527  exprAnalyzeAll(pSrc, pOrWc);
98528  if( db->mallocFailed ) return;
98529  assert( pOrWc->nTerm>=2 );
98530
98531  /*
98532  ** Compute the set of tables that might satisfy cases 1 or 2.
98533  */
98534  indexable = ~(Bitmask)0;
98535  chngToIN = ~(pWC->vmask);
98536  for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0 && indexable; i--, pOrTerm++){
98537    if( (pOrTerm->eOperator & WO_SINGLE)==0 ){
98538      WhereAndInfo *pAndInfo;
98539      assert( pOrTerm->eOperator==0 );
98540      assert( (pOrTerm->wtFlags & (TERM_ANDINFO|TERM_ORINFO))==0 );
98541      chngToIN = 0;
98542      pAndInfo = sqlite3DbMallocRaw(db, sizeof(*pAndInfo));
98543      if( pAndInfo ){
98544        WhereClause *pAndWC;
98545        WhereTerm *pAndTerm;
98546        int j;
98547        Bitmask b = 0;
98548        pOrTerm->u.pAndInfo = pAndInfo;
98549        pOrTerm->wtFlags |= TERM_ANDINFO;
98550        pOrTerm->eOperator = WO_AND;
98551        pAndWC = &pAndInfo->wc;
98552        whereClauseInit(pAndWC, pWC->pParse, pMaskSet);
98553        whereSplit(pAndWC, pOrTerm->pExpr, TK_AND);
98554        exprAnalyzeAll(pSrc, pAndWC);
98555        testcase( db->mallocFailed );
98556        if( !db->mallocFailed ){
98557          for(j=0, pAndTerm=pAndWC->a; j<pAndWC->nTerm; j++, pAndTerm++){
98558            assert( pAndTerm->pExpr );
98559            if( allowedOp(pAndTerm->pExpr->op) ){
98560              b |= getMask(pMaskSet, pAndTerm->leftCursor);
98561            }
98562          }
98563        }
98564        indexable &= b;
98565      }
98566    }else if( pOrTerm->wtFlags & TERM_COPIED ){
98567      /* Skip this term for now.  We revisit it when we process the
98568      ** corresponding TERM_VIRTUAL term */
98569    }else{
98570      Bitmask b;
98571      b = getMask(pMaskSet, pOrTerm->leftCursor);
98572      if( pOrTerm->wtFlags & TERM_VIRTUAL ){
98573        WhereTerm *pOther = &pOrWc->a[pOrTerm->iParent];
98574        b |= getMask(pMaskSet, pOther->leftCursor);
98575      }
98576      indexable &= b;
98577      if( pOrTerm->eOperator!=WO_EQ ){
98578        chngToIN = 0;
98579      }else{
98580        chngToIN &= b;
98581      }
98582    }
98583  }
98584
98585  /*
98586  ** Record the set of tables that satisfy case 2.  The set might be
98587  ** empty.
98588  */
98589  pOrInfo->indexable = indexable;
98590  pTerm->eOperator = indexable==0 ? 0 : WO_OR;
98591
98592  /*
98593  ** chngToIN holds a set of tables that *might* satisfy case 1.  But
98594  ** we have to do some additional checking to see if case 1 really
98595  ** is satisfied.
98596  **
98597  ** chngToIN will hold either 0, 1, or 2 bits.  The 0-bit case means
98598  ** that there is no possibility of transforming the OR clause into an
98599  ** IN operator because one or more terms in the OR clause contain
98600  ** something other than == on a column in the single table.  The 1-bit
98601  ** case means that every term of the OR clause is of the form
98602  ** "table.column=expr" for some single table.  The one bit that is set
98603  ** will correspond to the common table.  We still need to check to make
98604  ** sure the same column is used on all terms.  The 2-bit case is when
98605  ** the all terms are of the form "table1.column=table2.column".  It
98606  ** might be possible to form an IN operator with either table1.column
98607  ** or table2.column as the LHS if either is common to every term of
98608  ** the OR clause.
98609  **
98610  ** Note that terms of the form "table.column1=table.column2" (the
98611  ** same table on both sizes of the ==) cannot be optimized.
98612  */
98613  if( chngToIN ){
98614    int okToChngToIN = 0;     /* True if the conversion to IN is valid */
98615    int iColumn = -1;         /* Column index on lhs of IN operator */
98616    int iCursor = -1;         /* Table cursor common to all terms */
98617    int j = 0;                /* Loop counter */
98618
98619    /* Search for a table and column that appears on one side or the
98620    ** other of the == operator in every subterm.  That table and column
98621    ** will be recorded in iCursor and iColumn.  There might not be any
98622    ** such table and column.  Set okToChngToIN if an appropriate table
98623    ** and column is found but leave okToChngToIN false if not found.
98624    */
98625    for(j=0; j<2 && !okToChngToIN; j++){
98626      pOrTerm = pOrWc->a;
98627      for(i=pOrWc->nTerm-1; i>=0; i--, pOrTerm++){
98628        assert( pOrTerm->eOperator==WO_EQ );
98629        pOrTerm->wtFlags &= ~TERM_OR_OK;
98630        if( pOrTerm->leftCursor==iCursor ){
98631          /* This is the 2-bit case and we are on the second iteration and
98632          ** current term is from the first iteration.  So skip this term. */
98633          assert( j==1 );
98634          continue;
98635        }
98636        if( (chngToIN & getMask(pMaskSet, pOrTerm->leftCursor))==0 ){
98637          /* This term must be of the form t1.a==t2.b where t2 is in the
98638          ** chngToIN set but t1 is not.  This term will be either preceeded
98639          ** or follwed by an inverted copy (t2.b==t1.a).  Skip this term
98640          ** and use its inversion. */
98641          testcase( pOrTerm->wtFlags & TERM_COPIED );
98642          testcase( pOrTerm->wtFlags & TERM_VIRTUAL );
98643          assert( pOrTerm->wtFlags & (TERM_COPIED|TERM_VIRTUAL) );
98644          continue;
98645        }
98646        iColumn = pOrTerm->u.leftColumn;
98647        iCursor = pOrTerm->leftCursor;
98648        break;
98649      }
98650      if( i<0 ){
98651        /* No candidate table+column was found.  This can only occur
98652        ** on the second iteration */
98653        assert( j==1 );
98654        assert( (chngToIN&(chngToIN-1))==0 );
98655        assert( chngToIN==getMask(pMaskSet, iCursor) );
98656        break;
98657      }
98658      testcase( j==1 );
98659
98660      /* We have found a candidate table and column.  Check to see if that
98661      ** table and column is common to every term in the OR clause */
98662      okToChngToIN = 1;
98663      for(; i>=0 && okToChngToIN; i--, pOrTerm++){
98664        assert( pOrTerm->eOperator==WO_EQ );
98665        if( pOrTerm->leftCursor!=iCursor ){
98666          pOrTerm->wtFlags &= ~TERM_OR_OK;
98667        }else if( pOrTerm->u.leftColumn!=iColumn ){
98668          okToChngToIN = 0;
98669        }else{
98670          int affLeft, affRight;
98671          /* If the right-hand side is also a column, then the affinities
98672          ** of both right and left sides must be such that no type
98673          ** conversions are required on the right.  (Ticket #2249)
98674          */
98675          affRight = sqlite3ExprAffinity(pOrTerm->pExpr->pRight);
98676          affLeft = sqlite3ExprAffinity(pOrTerm->pExpr->pLeft);
98677          if( affRight!=0 && affRight!=affLeft ){
98678            okToChngToIN = 0;
98679          }else{
98680            pOrTerm->wtFlags |= TERM_OR_OK;
98681          }
98682        }
98683      }
98684    }
98685
98686    /* At this point, okToChngToIN is true if original pTerm satisfies
98687    ** case 1.  In that case, construct a new virtual term that is
98688    ** pTerm converted into an IN operator.
98689    **
98690    ** EV: R-00211-15100
98691    */
98692    if( okToChngToIN ){
98693      Expr *pDup;            /* A transient duplicate expression */
98694      ExprList *pList = 0;   /* The RHS of the IN operator */
98695      Expr *pLeft = 0;       /* The LHS of the IN operator */
98696      Expr *pNew;            /* The complete IN operator */
98697
98698      for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0; i--, pOrTerm++){
98699        if( (pOrTerm->wtFlags & TERM_OR_OK)==0 ) continue;
98700        assert( pOrTerm->eOperator==WO_EQ );
98701        assert( pOrTerm->leftCursor==iCursor );
98702        assert( pOrTerm->u.leftColumn==iColumn );
98703        pDup = sqlite3ExprDup(db, pOrTerm->pExpr->pRight, 0);
98704        pList = sqlite3ExprListAppend(pWC->pParse, pList, pDup);
98705        pLeft = pOrTerm->pExpr->pLeft;
98706      }
98707      assert( pLeft!=0 );
98708      pDup = sqlite3ExprDup(db, pLeft, 0);
98709      pNew = sqlite3PExpr(pParse, TK_IN, pDup, 0, 0);
98710      if( pNew ){
98711        int idxNew;
98712        transferJoinMarkings(pNew, pExpr);
98713        assert( !ExprHasProperty(pNew, EP_xIsSelect) );
98714        pNew->x.pList = pList;
98715        idxNew = whereClauseInsert(pWC, pNew, TERM_VIRTUAL|TERM_DYNAMIC);
98716        testcase( idxNew==0 );
98717        exprAnalyze(pSrc, pWC, idxNew);
98718        pTerm = &pWC->a[idxTerm];
98719        pWC->a[idxNew].iParent = idxTerm;
98720        pTerm->nChild = 1;
98721      }else{
98722        sqlite3ExprListDelete(db, pList);
98723      }
98724      pTerm->eOperator = WO_NOOP;  /* case 1 trumps case 2 */
98725    }
98726  }
98727}
98728#endif /* !SQLITE_OMIT_OR_OPTIMIZATION && !SQLITE_OMIT_SUBQUERY */
98729
98730
98731/*
98732** The input to this routine is an WhereTerm structure with only the
98733** "pExpr" field filled in.  The job of this routine is to analyze the
98734** subexpression and populate all the other fields of the WhereTerm
98735** structure.
98736**
98737** If the expression is of the form "<expr> <op> X" it gets commuted
98738** to the standard form of "X <op> <expr>".
98739**
98740** If the expression is of the form "X <op> Y" where both X and Y are
98741** columns, then the original expression is unchanged and a new virtual
98742** term of the form "Y <op> X" is added to the WHERE clause and
98743** analyzed separately.  The original term is marked with TERM_COPIED
98744** and the new term is marked with TERM_DYNAMIC (because it's pExpr
98745** needs to be freed with the WhereClause) and TERM_VIRTUAL (because it
98746** is a commuted copy of a prior term.)  The original term has nChild=1
98747** and the copy has idxParent set to the index of the original term.
98748*/
98749static void exprAnalyze(
98750  SrcList *pSrc,            /* the FROM clause */
98751  WhereClause *pWC,         /* the WHERE clause */
98752  int idxTerm               /* Index of the term to be analyzed */
98753){
98754  WhereTerm *pTerm;                /* The term to be analyzed */
98755  WhereMaskSet *pMaskSet;          /* Set of table index masks */
98756  Expr *pExpr;                     /* The expression to be analyzed */
98757  Bitmask prereqLeft;              /* Prerequesites of the pExpr->pLeft */
98758  Bitmask prereqAll;               /* Prerequesites of pExpr */
98759  Bitmask extraRight = 0;          /* Extra dependencies on LEFT JOIN */
98760  Expr *pStr1 = 0;                 /* RHS of LIKE/GLOB operator */
98761  int isComplete = 0;              /* RHS of LIKE/GLOB ends with wildcard */
98762  int noCase = 0;                  /* LIKE/GLOB distinguishes case */
98763  int op;                          /* Top-level operator.  pExpr->op */
98764  Parse *pParse = pWC->pParse;     /* Parsing context */
98765  sqlite3 *db = pParse->db;        /* Database connection */
98766
98767  if( db->mallocFailed ){
98768    return;
98769  }
98770  pTerm = &pWC->a[idxTerm];
98771  pMaskSet = pWC->pMaskSet;
98772  pExpr = pTerm->pExpr;
98773  prereqLeft = exprTableUsage(pMaskSet, pExpr->pLeft);
98774  op = pExpr->op;
98775  if( op==TK_IN ){
98776    assert( pExpr->pRight==0 );
98777    if( ExprHasProperty(pExpr, EP_xIsSelect) ){
98778      pTerm->prereqRight = exprSelectTableUsage(pMaskSet, pExpr->x.pSelect);
98779    }else{
98780      pTerm->prereqRight = exprListTableUsage(pMaskSet, pExpr->x.pList);
98781    }
98782  }else if( op==TK_ISNULL ){
98783    pTerm->prereqRight = 0;
98784  }else{
98785    pTerm->prereqRight = exprTableUsage(pMaskSet, pExpr->pRight);
98786  }
98787  prereqAll = exprTableUsage(pMaskSet, pExpr);
98788  if( ExprHasProperty(pExpr, EP_FromJoin) ){
98789    Bitmask x = getMask(pMaskSet, pExpr->iRightJoinTable);
98790    prereqAll |= x;
98791    extraRight = x-1;  /* ON clause terms may not be used with an index
98792                       ** on left table of a LEFT JOIN.  Ticket #3015 */
98793  }
98794  pTerm->prereqAll = prereqAll;
98795  pTerm->leftCursor = -1;
98796  pTerm->iParent = -1;
98797  pTerm->eOperator = 0;
98798  if( allowedOp(op) && (pTerm->prereqRight & prereqLeft)==0 ){
98799    Expr *pLeft = pExpr->pLeft;
98800    Expr *pRight = pExpr->pRight;
98801    if( pLeft->op==TK_COLUMN ){
98802      pTerm->leftCursor = pLeft->iTable;
98803      pTerm->u.leftColumn = pLeft->iColumn;
98804      pTerm->eOperator = operatorMask(op);
98805    }
98806    if( pRight && pRight->op==TK_COLUMN ){
98807      WhereTerm *pNew;
98808      Expr *pDup;
98809      if( pTerm->leftCursor>=0 ){
98810        int idxNew;
98811        pDup = sqlite3ExprDup(db, pExpr, 0);
98812        if( db->mallocFailed ){
98813          sqlite3ExprDelete(db, pDup);
98814          return;
98815        }
98816        idxNew = whereClauseInsert(pWC, pDup, TERM_VIRTUAL|TERM_DYNAMIC);
98817        if( idxNew==0 ) return;
98818        pNew = &pWC->a[idxNew];
98819        pNew->iParent = idxTerm;
98820        pTerm = &pWC->a[idxTerm];
98821        pTerm->nChild = 1;
98822        pTerm->wtFlags |= TERM_COPIED;
98823      }else{
98824        pDup = pExpr;
98825        pNew = pTerm;
98826      }
98827      exprCommute(pParse, pDup);
98828      pLeft = pDup->pLeft;
98829      pNew->leftCursor = pLeft->iTable;
98830      pNew->u.leftColumn = pLeft->iColumn;
98831      testcase( (prereqLeft | extraRight) != prereqLeft );
98832      pNew->prereqRight = prereqLeft | extraRight;
98833      pNew->prereqAll = prereqAll;
98834      pNew->eOperator = operatorMask(pDup->op);
98835    }
98836  }
98837
98838#ifndef SQLITE_OMIT_BETWEEN_OPTIMIZATION
98839  /* If a term is the BETWEEN operator, create two new virtual terms
98840  ** that define the range that the BETWEEN implements.  For example:
98841  **
98842  **      a BETWEEN b AND c
98843  **
98844  ** is converted into:
98845  **
98846  **      (a BETWEEN b AND c) AND (a>=b) AND (a<=c)
98847  **
98848  ** The two new terms are added onto the end of the WhereClause object.
98849  ** The new terms are "dynamic" and are children of the original BETWEEN
98850  ** term.  That means that if the BETWEEN term is coded, the children are
98851  ** skipped.  Or, if the children are satisfied by an index, the original
98852  ** BETWEEN term is skipped.
98853  */
98854  else if( pExpr->op==TK_BETWEEN && pWC->op==TK_AND ){
98855    ExprList *pList = pExpr->x.pList;
98856    int i;
98857    static const u8 ops[] = {TK_GE, TK_LE};
98858    assert( pList!=0 );
98859    assert( pList->nExpr==2 );
98860    for(i=0; i<2; i++){
98861      Expr *pNewExpr;
98862      int idxNew;
98863      pNewExpr = sqlite3PExpr(pParse, ops[i],
98864                             sqlite3ExprDup(db, pExpr->pLeft, 0),
98865                             sqlite3ExprDup(db, pList->a[i].pExpr, 0), 0);
98866      idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
98867      testcase( idxNew==0 );
98868      exprAnalyze(pSrc, pWC, idxNew);
98869      pTerm = &pWC->a[idxTerm];
98870      pWC->a[idxNew].iParent = idxTerm;
98871    }
98872    pTerm->nChild = 2;
98873  }
98874#endif /* SQLITE_OMIT_BETWEEN_OPTIMIZATION */
98875
98876#if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
98877  /* Analyze a term that is composed of two or more subterms connected by
98878  ** an OR operator.
98879  */
98880  else if( pExpr->op==TK_OR ){
98881    assert( pWC->op==TK_AND );
98882    exprAnalyzeOrTerm(pSrc, pWC, idxTerm);
98883    pTerm = &pWC->a[idxTerm];
98884  }
98885#endif /* SQLITE_OMIT_OR_OPTIMIZATION */
98886
98887#ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
98888  /* Add constraints to reduce the search space on a LIKE or GLOB
98889  ** operator.
98890  **
98891  ** A like pattern of the form "x LIKE 'abc%'" is changed into constraints
98892  **
98893  **          x>='abc' AND x<'abd' AND x LIKE 'abc%'
98894  **
98895  ** The last character of the prefix "abc" is incremented to form the
98896  ** termination condition "abd".
98897  */
98898  if( pWC->op==TK_AND
98899   && isLikeOrGlob(pParse, pExpr, &pStr1, &isComplete, &noCase)
98900  ){
98901    Expr *pLeft;       /* LHS of LIKE/GLOB operator */
98902    Expr *pStr2;       /* Copy of pStr1 - RHS of LIKE/GLOB operator */
98903    Expr *pNewExpr1;
98904    Expr *pNewExpr2;
98905    int idxNew1;
98906    int idxNew2;
98907    CollSeq *pColl;    /* Collating sequence to use */
98908
98909    pLeft = pExpr->x.pList->a[1].pExpr;
98910    pStr2 = sqlite3ExprDup(db, pStr1, 0);
98911    if( !db->mallocFailed ){
98912      u8 c, *pC;       /* Last character before the first wildcard */
98913      pC = (u8*)&pStr2->u.zToken[sqlite3Strlen30(pStr2->u.zToken)-1];
98914      c = *pC;
98915      if( noCase ){
98916        /* The point is to increment the last character before the first
98917        ** wildcard.  But if we increment '@', that will push it into the
98918        ** alphabetic range where case conversions will mess up the
98919        ** inequality.  To avoid this, make sure to also run the full
98920        ** LIKE on all candidate expressions by clearing the isComplete flag
98921        */
98922        if( c=='A'-1 ) isComplete = 0;   /* EV: R-64339-08207 */
98923
98924
98925        c = sqlite3UpperToLower[c];
98926      }
98927      *pC = c + 1;
98928    }
98929    pColl = sqlite3FindCollSeq(db, SQLITE_UTF8, noCase ? "NOCASE" : "BINARY",0);
98930    pNewExpr1 = sqlite3PExpr(pParse, TK_GE,
98931                     sqlite3ExprSetColl(sqlite3ExprDup(db,pLeft,0), pColl),
98932                     pStr1, 0);
98933    idxNew1 = whereClauseInsert(pWC, pNewExpr1, TERM_VIRTUAL|TERM_DYNAMIC);
98934    testcase( idxNew1==0 );
98935    exprAnalyze(pSrc, pWC, idxNew1);
98936    pNewExpr2 = sqlite3PExpr(pParse, TK_LT,
98937                     sqlite3ExprSetColl(sqlite3ExprDup(db,pLeft,0), pColl),
98938                     pStr2, 0);
98939    idxNew2 = whereClauseInsert(pWC, pNewExpr2, TERM_VIRTUAL|TERM_DYNAMIC);
98940    testcase( idxNew2==0 );
98941    exprAnalyze(pSrc, pWC, idxNew2);
98942    pTerm = &pWC->a[idxTerm];
98943    if( isComplete ){
98944      pWC->a[idxNew1].iParent = idxTerm;
98945      pWC->a[idxNew2].iParent = idxTerm;
98946      pTerm->nChild = 2;
98947    }
98948  }
98949#endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
98950
98951#ifndef SQLITE_OMIT_VIRTUALTABLE
98952  /* Add a WO_MATCH auxiliary term to the constraint set if the
98953  ** current expression is of the form:  column MATCH expr.
98954  ** This information is used by the xBestIndex methods of
98955  ** virtual tables.  The native query optimizer does not attempt
98956  ** to do anything with MATCH functions.
98957  */
98958  if( isMatchOfColumn(pExpr) ){
98959    int idxNew;
98960    Expr *pRight, *pLeft;
98961    WhereTerm *pNewTerm;
98962    Bitmask prereqColumn, prereqExpr;
98963
98964    pRight = pExpr->x.pList->a[0].pExpr;
98965    pLeft = pExpr->x.pList->a[1].pExpr;
98966    prereqExpr = exprTableUsage(pMaskSet, pRight);
98967    prereqColumn = exprTableUsage(pMaskSet, pLeft);
98968    if( (prereqExpr & prereqColumn)==0 ){
98969      Expr *pNewExpr;
98970      pNewExpr = sqlite3PExpr(pParse, TK_MATCH,
98971                              0, sqlite3ExprDup(db, pRight, 0), 0);
98972      idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
98973      testcase( idxNew==0 );
98974      pNewTerm = &pWC->a[idxNew];
98975      pNewTerm->prereqRight = prereqExpr;
98976      pNewTerm->leftCursor = pLeft->iTable;
98977      pNewTerm->u.leftColumn = pLeft->iColumn;
98978      pNewTerm->eOperator = WO_MATCH;
98979      pNewTerm->iParent = idxTerm;
98980      pTerm = &pWC->a[idxTerm];
98981      pTerm->nChild = 1;
98982      pTerm->wtFlags |= TERM_COPIED;
98983      pNewTerm->prereqAll = pTerm->prereqAll;
98984    }
98985  }
98986#endif /* SQLITE_OMIT_VIRTUALTABLE */
98987
98988#ifdef SQLITE_ENABLE_STAT2
98989  /* When sqlite_stat2 histogram data is available an operator of the
98990  ** form "x IS NOT NULL" can sometimes be evaluated more efficiently
98991  ** as "x>NULL" if x is not an INTEGER PRIMARY KEY.  So construct a
98992  ** virtual term of that form.
98993  **
98994  ** Note that the virtual term must be tagged with TERM_VNULL.  This
98995  ** TERM_VNULL tag will suppress the not-null check at the beginning
98996  ** of the loop.  Without the TERM_VNULL flag, the not-null check at
98997  ** the start of the loop will prevent any results from being returned.
98998  */
98999  if( pExpr->op==TK_NOTNULL
99000   && pExpr->pLeft->op==TK_COLUMN
99001   && pExpr->pLeft->iColumn>=0
99002  ){
99003    Expr *pNewExpr;
99004    Expr *pLeft = pExpr->pLeft;
99005    int idxNew;
99006    WhereTerm *pNewTerm;
99007
99008    pNewExpr = sqlite3PExpr(pParse, TK_GT,
99009                            sqlite3ExprDup(db, pLeft, 0),
99010                            sqlite3PExpr(pParse, TK_NULL, 0, 0, 0), 0);
99011
99012    idxNew = whereClauseInsert(pWC, pNewExpr,
99013                              TERM_VIRTUAL|TERM_DYNAMIC|TERM_VNULL);
99014    if( idxNew ){
99015      pNewTerm = &pWC->a[idxNew];
99016      pNewTerm->prereqRight = 0;
99017      pNewTerm->leftCursor = pLeft->iTable;
99018      pNewTerm->u.leftColumn = pLeft->iColumn;
99019      pNewTerm->eOperator = WO_GT;
99020      pNewTerm->iParent = idxTerm;
99021      pTerm = &pWC->a[idxTerm];
99022      pTerm->nChild = 1;
99023      pTerm->wtFlags |= TERM_COPIED;
99024      pNewTerm->prereqAll = pTerm->prereqAll;
99025    }
99026  }
99027#endif /* SQLITE_ENABLE_STAT2 */
99028
99029  /* Prevent ON clause terms of a LEFT JOIN from being used to drive
99030  ** an index for tables to the left of the join.
99031  */
99032  pTerm->prereqRight |= extraRight;
99033}
99034
99035/*
99036** Return TRUE if any of the expressions in pList->a[iFirst...] contain
99037** a reference to any table other than the iBase table.
99038*/
99039static int referencesOtherTables(
99040  ExprList *pList,          /* Search expressions in ths list */
99041  WhereMaskSet *pMaskSet,   /* Mapping from tables to bitmaps */
99042  int iFirst,               /* Be searching with the iFirst-th expression */
99043  int iBase                 /* Ignore references to this table */
99044){
99045  Bitmask allowed = ~getMask(pMaskSet, iBase);
99046  while( iFirst<pList->nExpr ){
99047    if( (exprTableUsage(pMaskSet, pList->a[iFirst++].pExpr)&allowed)!=0 ){
99048      return 1;
99049    }
99050  }
99051  return 0;
99052}
99053
99054
99055/*
99056** This routine decides if pIdx can be used to satisfy the ORDER BY
99057** clause.  If it can, it returns 1.  If pIdx cannot satisfy the
99058** ORDER BY clause, this routine returns 0.
99059**
99060** pOrderBy is an ORDER BY clause from a SELECT statement.  pTab is the
99061** left-most table in the FROM clause of that same SELECT statement and
99062** the table has a cursor number of "base".  pIdx is an index on pTab.
99063**
99064** nEqCol is the number of columns of pIdx that are used as equality
99065** constraints.  Any of these columns may be missing from the ORDER BY
99066** clause and the match can still be a success.
99067**
99068** All terms of the ORDER BY that match against the index must be either
99069** ASC or DESC.  (Terms of the ORDER BY clause past the end of a UNIQUE
99070** index do not need to satisfy this constraint.)  The *pbRev value is
99071** set to 1 if the ORDER BY clause is all DESC and it is set to 0 if
99072** the ORDER BY clause is all ASC.
99073*/
99074static int isSortingIndex(
99075  Parse *pParse,          /* Parsing context */
99076  WhereMaskSet *pMaskSet, /* Mapping from table cursor numbers to bitmaps */
99077  Index *pIdx,            /* The index we are testing */
99078  int base,               /* Cursor number for the table to be sorted */
99079  ExprList *pOrderBy,     /* The ORDER BY clause */
99080  int nEqCol,             /* Number of index columns with == constraints */
99081  int wsFlags,            /* Index usages flags */
99082  int *pbRev              /* Set to 1 if ORDER BY is DESC */
99083){
99084  int i, j;                       /* Loop counters */
99085  int sortOrder = 0;              /* XOR of index and ORDER BY sort direction */
99086  int nTerm;                      /* Number of ORDER BY terms */
99087  struct ExprList_item *pTerm;    /* A term of the ORDER BY clause */
99088  sqlite3 *db = pParse->db;
99089
99090  assert( pOrderBy!=0 );
99091  nTerm = pOrderBy->nExpr;
99092  assert( nTerm>0 );
99093
99094  /* Argument pIdx must either point to a 'real' named index structure,
99095  ** or an index structure allocated on the stack by bestBtreeIndex() to
99096  ** represent the rowid index that is part of every table.  */
99097  assert( pIdx->zName || (pIdx->nColumn==1 && pIdx->aiColumn[0]==-1) );
99098
99099  /* Match terms of the ORDER BY clause against columns of
99100  ** the index.
99101  **
99102  ** Note that indices have pIdx->nColumn regular columns plus
99103  ** one additional column containing the rowid.  The rowid column
99104  ** of the index is also allowed to match against the ORDER BY
99105  ** clause.
99106  */
99107  for(i=j=0, pTerm=pOrderBy->a; j<nTerm && i<=pIdx->nColumn; i++){
99108    Expr *pExpr;       /* The expression of the ORDER BY pTerm */
99109    CollSeq *pColl;    /* The collating sequence of pExpr */
99110    int termSortOrder; /* Sort order for this term */
99111    int iColumn;       /* The i-th column of the index.  -1 for rowid */
99112    int iSortOrder;    /* 1 for DESC, 0 for ASC on the i-th index term */
99113    const char *zColl; /* Name of the collating sequence for i-th index term */
99114
99115    pExpr = pTerm->pExpr;
99116    if( pExpr->op!=TK_COLUMN || pExpr->iTable!=base ){
99117      /* Can not use an index sort on anything that is not a column in the
99118      ** left-most table of the FROM clause */
99119      break;
99120    }
99121    pColl = sqlite3ExprCollSeq(pParse, pExpr);
99122    if( !pColl ){
99123      pColl = db->pDfltColl;
99124    }
99125    if( pIdx->zName && i<pIdx->nColumn ){
99126      iColumn = pIdx->aiColumn[i];
99127      if( iColumn==pIdx->pTable->iPKey ){
99128        iColumn = -1;
99129      }
99130      iSortOrder = pIdx->aSortOrder[i];
99131      zColl = pIdx->azColl[i];
99132    }else{
99133      iColumn = -1;
99134      iSortOrder = 0;
99135      zColl = pColl->zName;
99136    }
99137    if( pExpr->iColumn!=iColumn || sqlite3StrICmp(pColl->zName, zColl) ){
99138      /* Term j of the ORDER BY clause does not match column i of the index */
99139      if( i<nEqCol ){
99140        /* If an index column that is constrained by == fails to match an
99141        ** ORDER BY term, that is OK.  Just ignore that column of the index
99142        */
99143        continue;
99144      }else if( i==pIdx->nColumn ){
99145        /* Index column i is the rowid.  All other terms match. */
99146        break;
99147      }else{
99148        /* If an index column fails to match and is not constrained by ==
99149        ** then the index cannot satisfy the ORDER BY constraint.
99150        */
99151        return 0;
99152      }
99153    }
99154    assert( pIdx->aSortOrder!=0 || iColumn==-1 );
99155    assert( pTerm->sortOrder==0 || pTerm->sortOrder==1 );
99156    assert( iSortOrder==0 || iSortOrder==1 );
99157    termSortOrder = iSortOrder ^ pTerm->sortOrder;
99158    if( i>nEqCol ){
99159      if( termSortOrder!=sortOrder ){
99160        /* Indices can only be used if all ORDER BY terms past the
99161        ** equality constraints are all either DESC or ASC. */
99162        return 0;
99163      }
99164    }else{
99165      sortOrder = termSortOrder;
99166    }
99167    j++;
99168    pTerm++;
99169    if( iColumn<0 && !referencesOtherTables(pOrderBy, pMaskSet, j, base) ){
99170      /* If the indexed column is the primary key and everything matches
99171      ** so far and none of the ORDER BY terms to the right reference other
99172      ** tables in the join, then we are assured that the index can be used
99173      ** to sort because the primary key is unique and so none of the other
99174      ** columns will make any difference
99175      */
99176      j = nTerm;
99177    }
99178  }
99179
99180  *pbRev = sortOrder!=0;
99181  if( j>=nTerm ){
99182    /* All terms of the ORDER BY clause are covered by this index so
99183    ** this index can be used for sorting. */
99184    return 1;
99185  }
99186  if( pIdx->onError!=OE_None && i==pIdx->nColumn
99187      && (wsFlags & WHERE_COLUMN_NULL)==0
99188      && !referencesOtherTables(pOrderBy, pMaskSet, j, base) ){
99189    /* All terms of this index match some prefix of the ORDER BY clause
99190    ** and the index is UNIQUE and no terms on the tail of the ORDER BY
99191    ** clause reference other tables in a join.  If this is all true then
99192    ** the order by clause is superfluous.  Not that if the matching
99193    ** condition is IS NULL then the result is not necessarily unique
99194    ** even on a UNIQUE index, so disallow those cases. */
99195    return 1;
99196  }
99197  return 0;
99198}
99199
99200/*
99201** Prepare a crude estimate of the logarithm of the input value.
99202** The results need not be exact.  This is only used for estimating
99203** the total cost of performing operations with O(logN) or O(NlogN)
99204** complexity.  Because N is just a guess, it is no great tragedy if
99205** logN is a little off.
99206*/
99207static double estLog(double N){
99208  double logN = 1;
99209  double x = 10;
99210  while( N>x ){
99211    logN += 1;
99212    x *= 10;
99213  }
99214  return logN;
99215}
99216
99217/*
99218** Two routines for printing the content of an sqlite3_index_info
99219** structure.  Used for testing and debugging only.  If neither
99220** SQLITE_TEST or SQLITE_DEBUG are defined, then these routines
99221** are no-ops.
99222*/
99223#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_DEBUG)
99224static void TRACE_IDX_INPUTS(sqlite3_index_info *p){
99225  int i;
99226  if( !sqlite3WhereTrace ) return;
99227  for(i=0; i<p->nConstraint; i++){
99228    sqlite3DebugPrintf("  constraint[%d]: col=%d termid=%d op=%d usabled=%d\n",
99229       i,
99230       p->aConstraint[i].iColumn,
99231       p->aConstraint[i].iTermOffset,
99232       p->aConstraint[i].op,
99233       p->aConstraint[i].usable);
99234  }
99235  for(i=0; i<p->nOrderBy; i++){
99236    sqlite3DebugPrintf("  orderby[%d]: col=%d desc=%d\n",
99237       i,
99238       p->aOrderBy[i].iColumn,
99239       p->aOrderBy[i].desc);
99240  }
99241}
99242static void TRACE_IDX_OUTPUTS(sqlite3_index_info *p){
99243  int i;
99244  if( !sqlite3WhereTrace ) return;
99245  for(i=0; i<p->nConstraint; i++){
99246    sqlite3DebugPrintf("  usage[%d]: argvIdx=%d omit=%d\n",
99247       i,
99248       p->aConstraintUsage[i].argvIndex,
99249       p->aConstraintUsage[i].omit);
99250  }
99251  sqlite3DebugPrintf("  idxNum=%d\n", p->idxNum);
99252  sqlite3DebugPrintf("  idxStr=%s\n", p->idxStr);
99253  sqlite3DebugPrintf("  orderByConsumed=%d\n", p->orderByConsumed);
99254  sqlite3DebugPrintf("  estimatedCost=%g\n", p->estimatedCost);
99255}
99256#else
99257#define TRACE_IDX_INPUTS(A)
99258#define TRACE_IDX_OUTPUTS(A)
99259#endif
99260
99261/*
99262** Required because bestIndex() is called by bestOrClauseIndex()
99263*/
99264static void bestIndex(
99265    Parse*, WhereClause*, struct SrcList_item*,
99266    Bitmask, Bitmask, ExprList*, WhereCost*);
99267
99268/*
99269** This routine attempts to find an scanning strategy that can be used
99270** to optimize an 'OR' expression that is part of a WHERE clause.
99271**
99272** The table associated with FROM clause term pSrc may be either a
99273** regular B-Tree table or a virtual table.
99274*/
99275static void bestOrClauseIndex(
99276  Parse *pParse,              /* The parsing context */
99277  WhereClause *pWC,           /* The WHERE clause */
99278  struct SrcList_item *pSrc,  /* The FROM clause term to search */
99279  Bitmask notReady,           /* Mask of cursors not available for indexing */
99280  Bitmask notValid,           /* Cursors not available for any purpose */
99281  ExprList *pOrderBy,         /* The ORDER BY clause */
99282  WhereCost *pCost            /* Lowest cost query plan */
99283){
99284#ifndef SQLITE_OMIT_OR_OPTIMIZATION
99285  const int iCur = pSrc->iCursor;   /* The cursor of the table to be accessed */
99286  const Bitmask maskSrc = getMask(pWC->pMaskSet, iCur);  /* Bitmask for pSrc */
99287  WhereTerm * const pWCEnd = &pWC->a[pWC->nTerm];        /* End of pWC->a[] */
99288  WhereTerm *pTerm;                 /* A single term of the WHERE clause */
99289
99290  /* No OR-clause optimization allowed if the INDEXED BY or NOT INDEXED clauses
99291  ** are used */
99292  if( pSrc->notIndexed || pSrc->pIndex!=0 ){
99293    return;
99294  }
99295
99296  /* Search the WHERE clause terms for a usable WO_OR term. */
99297  for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
99298    if( pTerm->eOperator==WO_OR
99299     && ((pTerm->prereqAll & ~maskSrc) & notReady)==0
99300     && (pTerm->u.pOrInfo->indexable & maskSrc)!=0
99301    ){
99302      WhereClause * const pOrWC = &pTerm->u.pOrInfo->wc;
99303      WhereTerm * const pOrWCEnd = &pOrWC->a[pOrWC->nTerm];
99304      WhereTerm *pOrTerm;
99305      int flags = WHERE_MULTI_OR;
99306      double rTotal = 0;
99307      double nRow = 0;
99308      Bitmask used = 0;
99309
99310      for(pOrTerm=pOrWC->a; pOrTerm<pOrWCEnd; pOrTerm++){
99311        WhereCost sTermCost;
99312        WHERETRACE(("... Multi-index OR testing for term %d of %d....\n",
99313          (pOrTerm - pOrWC->a), (pTerm - pWC->a)
99314        ));
99315        if( pOrTerm->eOperator==WO_AND ){
99316          WhereClause *pAndWC = &pOrTerm->u.pAndInfo->wc;
99317          bestIndex(pParse, pAndWC, pSrc, notReady, notValid, 0, &sTermCost);
99318        }else if( pOrTerm->leftCursor==iCur ){
99319          WhereClause tempWC;
99320          tempWC.pParse = pWC->pParse;
99321          tempWC.pMaskSet = pWC->pMaskSet;
99322          tempWC.op = TK_AND;
99323          tempWC.a = pOrTerm;
99324          tempWC.nTerm = 1;
99325          bestIndex(pParse, &tempWC, pSrc, notReady, notValid, 0, &sTermCost);
99326        }else{
99327          continue;
99328        }
99329        rTotal += sTermCost.rCost;
99330        nRow += sTermCost.plan.nRow;
99331        used |= sTermCost.used;
99332        if( rTotal>=pCost->rCost ) break;
99333      }
99334
99335      /* If there is an ORDER BY clause, increase the scan cost to account
99336      ** for the cost of the sort. */
99337      if( pOrderBy!=0 ){
99338        WHERETRACE(("... sorting increases OR cost %.9g to %.9g\n",
99339                    rTotal, rTotal+nRow*estLog(nRow)));
99340        rTotal += nRow*estLog(nRow);
99341      }
99342
99343      /* If the cost of scanning using this OR term for optimization is
99344      ** less than the current cost stored in pCost, replace the contents
99345      ** of pCost. */
99346      WHERETRACE(("... multi-index OR cost=%.9g nrow=%.9g\n", rTotal, nRow));
99347      if( rTotal<pCost->rCost ){
99348        pCost->rCost = rTotal;
99349        pCost->used = used;
99350        pCost->plan.nRow = nRow;
99351        pCost->plan.wsFlags = flags;
99352        pCost->plan.u.pTerm = pTerm;
99353      }
99354    }
99355  }
99356#endif /* SQLITE_OMIT_OR_OPTIMIZATION */
99357}
99358
99359#ifndef SQLITE_OMIT_AUTOMATIC_INDEX
99360/*
99361** Return TRUE if the WHERE clause term pTerm is of a form where it
99362** could be used with an index to access pSrc, assuming an appropriate
99363** index existed.
99364*/
99365static int termCanDriveIndex(
99366  WhereTerm *pTerm,              /* WHERE clause term to check */
99367  struct SrcList_item *pSrc,     /* Table we are trying to access */
99368  Bitmask notReady               /* Tables in outer loops of the join */
99369){
99370  char aff;
99371  if( pTerm->leftCursor!=pSrc->iCursor ) return 0;
99372  if( pTerm->eOperator!=WO_EQ ) return 0;
99373  if( (pTerm->prereqRight & notReady)!=0 ) return 0;
99374  aff = pSrc->pTab->aCol[pTerm->u.leftColumn].affinity;
99375  if( !sqlite3IndexAffinityOk(pTerm->pExpr, aff) ) return 0;
99376  return 1;
99377}
99378#endif
99379
99380#ifndef SQLITE_OMIT_AUTOMATIC_INDEX
99381/*
99382** If the query plan for pSrc specified in pCost is a full table scan
99383** and indexing is allows (if there is no NOT INDEXED clause) and it
99384** possible to construct a transient index that would perform better
99385** than a full table scan even when the cost of constructing the index
99386** is taken into account, then alter the query plan to use the
99387** transient index.
99388*/
99389static void bestAutomaticIndex(
99390  Parse *pParse,              /* The parsing context */
99391  WhereClause *pWC,           /* The WHERE clause */
99392  struct SrcList_item *pSrc,  /* The FROM clause term to search */
99393  Bitmask notReady,           /* Mask of cursors that are not available */
99394  WhereCost *pCost            /* Lowest cost query plan */
99395){
99396  double nTableRow;           /* Rows in the input table */
99397  double logN;                /* log(nTableRow) */
99398  double costTempIdx;         /* per-query cost of the transient index */
99399  WhereTerm *pTerm;           /* A single term of the WHERE clause */
99400  WhereTerm *pWCEnd;          /* End of pWC->a[] */
99401  Table *pTable;              /* Table tht might be indexed */
99402
99403  if( (pParse->db->flags & SQLITE_AutoIndex)==0 ){
99404    /* Automatic indices are disabled at run-time */
99405    return;
99406  }
99407  if( (pCost->plan.wsFlags & WHERE_NOT_FULLSCAN)!=0 ){
99408    /* We already have some kind of index in use for this query. */
99409    return;
99410  }
99411  if( pSrc->notIndexed ){
99412    /* The NOT INDEXED clause appears in the SQL. */
99413    return;
99414  }
99415
99416  assert( pParse->nQueryLoop >= (double)1 );
99417  pTable = pSrc->pTab;
99418  nTableRow = pTable->nRowEst;
99419  logN = estLog(nTableRow);
99420  costTempIdx = 2*logN*(nTableRow/pParse->nQueryLoop + 1);
99421  if( costTempIdx>=pCost->rCost ){
99422    /* The cost of creating the transient table would be greater than
99423    ** doing the full table scan */
99424    return;
99425  }
99426
99427  /* Search for any equality comparison term */
99428  pWCEnd = &pWC->a[pWC->nTerm];
99429  for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
99430    if( termCanDriveIndex(pTerm, pSrc, notReady) ){
99431      WHERETRACE(("auto-index reduces cost from %.1f to %.1f\n",
99432                    pCost->rCost, costTempIdx));
99433      pCost->rCost = costTempIdx;
99434      pCost->plan.nRow = logN + 1;
99435      pCost->plan.wsFlags = WHERE_TEMP_INDEX;
99436      pCost->used = pTerm->prereqRight;
99437      break;
99438    }
99439  }
99440}
99441#else
99442# define bestAutomaticIndex(A,B,C,D,E)  /* no-op */
99443#endif /* SQLITE_OMIT_AUTOMATIC_INDEX */
99444
99445
99446#ifndef SQLITE_OMIT_AUTOMATIC_INDEX
99447/*
99448** Generate code to construct the Index object for an automatic index
99449** and to set up the WhereLevel object pLevel so that the code generator
99450** makes use of the automatic index.
99451*/
99452static void constructAutomaticIndex(
99453  Parse *pParse,              /* The parsing context */
99454  WhereClause *pWC,           /* The WHERE clause */
99455  struct SrcList_item *pSrc,  /* The FROM clause term to get the next index */
99456  Bitmask notReady,           /* Mask of cursors that are not available */
99457  WhereLevel *pLevel          /* Write new index here */
99458){
99459  int nColumn;                /* Number of columns in the constructed index */
99460  WhereTerm *pTerm;           /* A single term of the WHERE clause */
99461  WhereTerm *pWCEnd;          /* End of pWC->a[] */
99462  int nByte;                  /* Byte of memory needed for pIdx */
99463  Index *pIdx;                /* Object describing the transient index */
99464  Vdbe *v;                    /* Prepared statement under construction */
99465  int regIsInit;              /* Register set by initialization */
99466  int addrInit;               /* Address of the initialization bypass jump */
99467  Table *pTable;              /* The table being indexed */
99468  KeyInfo *pKeyinfo;          /* Key information for the index */
99469  int addrTop;                /* Top of the index fill loop */
99470  int regRecord;              /* Register holding an index record */
99471  int n;                      /* Column counter */
99472  int i;                      /* Loop counter */
99473  int mxBitCol;               /* Maximum column in pSrc->colUsed */
99474  CollSeq *pColl;             /* Collating sequence to on a column */
99475  Bitmask idxCols;            /* Bitmap of columns used for indexing */
99476  Bitmask extraCols;          /* Bitmap of additional columns */
99477
99478  /* Generate code to skip over the creation and initialization of the
99479  ** transient index on 2nd and subsequent iterations of the loop. */
99480  v = pParse->pVdbe;
99481  assert( v!=0 );
99482  regIsInit = ++pParse->nMem;
99483  addrInit = sqlite3VdbeAddOp1(v, OP_If, regIsInit);
99484  sqlite3VdbeAddOp2(v, OP_Integer, 1, regIsInit);
99485
99486  /* Count the number of columns that will be added to the index
99487  ** and used to match WHERE clause constraints */
99488  nColumn = 0;
99489  pTable = pSrc->pTab;
99490  pWCEnd = &pWC->a[pWC->nTerm];
99491  idxCols = 0;
99492  for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
99493    if( termCanDriveIndex(pTerm, pSrc, notReady) ){
99494      int iCol = pTerm->u.leftColumn;
99495      Bitmask cMask = iCol>=BMS ? ((Bitmask)1)<<(BMS-1) : ((Bitmask)1)<<iCol;
99496      testcase( iCol==BMS );
99497      testcase( iCol==BMS-1 );
99498      if( (idxCols & cMask)==0 ){
99499        nColumn++;
99500        idxCols |= cMask;
99501      }
99502    }
99503  }
99504  assert( nColumn>0 );
99505  pLevel->plan.nEq = nColumn;
99506
99507  /* Count the number of additional columns needed to create a
99508  ** covering index.  A "covering index" is an index that contains all
99509  ** columns that are needed by the query.  With a covering index, the
99510  ** original table never needs to be accessed.  Automatic indices must
99511  ** be a covering index because the index will not be updated if the
99512  ** original table changes and the index and table cannot both be used
99513  ** if they go out of sync.
99514  */
99515  extraCols = pSrc->colUsed & (~idxCols | (((Bitmask)1)<<(BMS-1)));
99516  mxBitCol = (pTable->nCol >= BMS-1) ? BMS-1 : pTable->nCol;
99517  testcase( pTable->nCol==BMS-1 );
99518  testcase( pTable->nCol==BMS-2 );
99519  for(i=0; i<mxBitCol; i++){
99520    if( extraCols & (((Bitmask)1)<<i) ) nColumn++;
99521  }
99522  if( pSrc->colUsed & (((Bitmask)1)<<(BMS-1)) ){
99523    nColumn += pTable->nCol - BMS + 1;
99524  }
99525  pLevel->plan.wsFlags |= WHERE_COLUMN_EQ | WHERE_IDX_ONLY | WO_EQ;
99526
99527  /* Construct the Index object to describe this index */
99528  nByte = sizeof(Index);
99529  nByte += nColumn*sizeof(int);     /* Index.aiColumn */
99530  nByte += nColumn*sizeof(char*);   /* Index.azColl */
99531  nByte += nColumn;                 /* Index.aSortOrder */
99532  pIdx = sqlite3DbMallocZero(pParse->db, nByte);
99533  if( pIdx==0 ) return;
99534  pLevel->plan.u.pIdx = pIdx;
99535  pIdx->azColl = (char**)&pIdx[1];
99536  pIdx->aiColumn = (int*)&pIdx->azColl[nColumn];
99537  pIdx->aSortOrder = (u8*)&pIdx->aiColumn[nColumn];
99538  pIdx->zName = "auto-index";
99539  pIdx->nColumn = nColumn;
99540  pIdx->pTable = pTable;
99541  n = 0;
99542  idxCols = 0;
99543  for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
99544    if( termCanDriveIndex(pTerm, pSrc, notReady) ){
99545      int iCol = pTerm->u.leftColumn;
99546      Bitmask cMask = iCol>=BMS ? ((Bitmask)1)<<(BMS-1) : ((Bitmask)1)<<iCol;
99547      if( (idxCols & cMask)==0 ){
99548        Expr *pX = pTerm->pExpr;
99549        idxCols |= cMask;
99550        pIdx->aiColumn[n] = pTerm->u.leftColumn;
99551        pColl = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pX->pRight);
99552        pIdx->azColl[n] = ALWAYS(pColl) ? pColl->zName : "BINARY";
99553        n++;
99554      }
99555    }
99556  }
99557  assert( (u32)n==pLevel->plan.nEq );
99558
99559  /* Add additional columns needed to make the automatic index into
99560  ** a covering index */
99561  for(i=0; i<mxBitCol; i++){
99562    if( extraCols & (((Bitmask)1)<<i) ){
99563      pIdx->aiColumn[n] = i;
99564      pIdx->azColl[n] = "BINARY";
99565      n++;
99566    }
99567  }
99568  if( pSrc->colUsed & (((Bitmask)1)<<(BMS-1)) ){
99569    for(i=BMS-1; i<pTable->nCol; i++){
99570      pIdx->aiColumn[n] = i;
99571      pIdx->azColl[n] = "BINARY";
99572      n++;
99573    }
99574  }
99575  assert( n==nColumn );
99576
99577  /* Create the automatic index */
99578  pKeyinfo = sqlite3IndexKeyinfo(pParse, pIdx);
99579  assert( pLevel->iIdxCur>=0 );
99580  sqlite3VdbeAddOp4(v, OP_OpenAutoindex, pLevel->iIdxCur, nColumn+1, 0,
99581                    (char*)pKeyinfo, P4_KEYINFO_HANDOFF);
99582  VdbeComment((v, "for %s", pTable->zName));
99583
99584  /* Fill the automatic index with content */
99585  addrTop = sqlite3VdbeAddOp1(v, OP_Rewind, pLevel->iTabCur);
99586  regRecord = sqlite3GetTempReg(pParse);
99587  sqlite3GenerateIndexKey(pParse, pIdx, pLevel->iTabCur, regRecord, 1);
99588  sqlite3VdbeAddOp2(v, OP_IdxInsert, pLevel->iIdxCur, regRecord);
99589  sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
99590  sqlite3VdbeAddOp2(v, OP_Next, pLevel->iTabCur, addrTop+1);
99591  sqlite3VdbeChangeP5(v, SQLITE_STMTSTATUS_AUTOINDEX);
99592  sqlite3VdbeJumpHere(v, addrTop);
99593  sqlite3ReleaseTempReg(pParse, regRecord);
99594
99595  /* Jump here when skipping the initialization */
99596  sqlite3VdbeJumpHere(v, addrInit);
99597}
99598#endif /* SQLITE_OMIT_AUTOMATIC_INDEX */
99599
99600#ifndef SQLITE_OMIT_VIRTUALTABLE
99601/*
99602** Allocate and populate an sqlite3_index_info structure. It is the
99603** responsibility of the caller to eventually release the structure
99604** by passing the pointer returned by this function to sqlite3_free().
99605*/
99606static sqlite3_index_info *allocateIndexInfo(
99607  Parse *pParse,
99608  WhereClause *pWC,
99609  struct SrcList_item *pSrc,
99610  ExprList *pOrderBy
99611){
99612  int i, j;
99613  int nTerm;
99614  struct sqlite3_index_constraint *pIdxCons;
99615  struct sqlite3_index_orderby *pIdxOrderBy;
99616  struct sqlite3_index_constraint_usage *pUsage;
99617  WhereTerm *pTerm;
99618  int nOrderBy;
99619  sqlite3_index_info *pIdxInfo;
99620
99621  WHERETRACE(("Recomputing index info for %s...\n", pSrc->pTab->zName));
99622
99623  /* Count the number of possible WHERE clause constraints referring
99624  ** to this virtual table */
99625  for(i=nTerm=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
99626    if( pTerm->leftCursor != pSrc->iCursor ) continue;
99627    assert( (pTerm->eOperator&(pTerm->eOperator-1))==0 );
99628    testcase( pTerm->eOperator==WO_IN );
99629    testcase( pTerm->eOperator==WO_ISNULL );
99630    if( pTerm->eOperator & (WO_IN|WO_ISNULL) ) continue;
99631    nTerm++;
99632  }
99633
99634  /* If the ORDER BY clause contains only columns in the current
99635  ** virtual table then allocate space for the aOrderBy part of
99636  ** the sqlite3_index_info structure.
99637  */
99638  nOrderBy = 0;
99639  if( pOrderBy ){
99640    for(i=0; i<pOrderBy->nExpr; i++){
99641      Expr *pExpr = pOrderBy->a[i].pExpr;
99642      if( pExpr->op!=TK_COLUMN || pExpr->iTable!=pSrc->iCursor ) break;
99643    }
99644    if( i==pOrderBy->nExpr ){
99645      nOrderBy = pOrderBy->nExpr;
99646    }
99647  }
99648
99649  /* Allocate the sqlite3_index_info structure
99650  */
99651  pIdxInfo = sqlite3DbMallocZero(pParse->db, sizeof(*pIdxInfo)
99652                           + (sizeof(*pIdxCons) + sizeof(*pUsage))*nTerm
99653                           + sizeof(*pIdxOrderBy)*nOrderBy );
99654  if( pIdxInfo==0 ){
99655    sqlite3ErrorMsg(pParse, "out of memory");
99656    /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
99657    return 0;
99658  }
99659
99660  /* Initialize the structure.  The sqlite3_index_info structure contains
99661  ** many fields that are declared "const" to prevent xBestIndex from
99662  ** changing them.  We have to do some funky casting in order to
99663  ** initialize those fields.
99664  */
99665  pIdxCons = (struct sqlite3_index_constraint*)&pIdxInfo[1];
99666  pIdxOrderBy = (struct sqlite3_index_orderby*)&pIdxCons[nTerm];
99667  pUsage = (struct sqlite3_index_constraint_usage*)&pIdxOrderBy[nOrderBy];
99668  *(int*)&pIdxInfo->nConstraint = nTerm;
99669  *(int*)&pIdxInfo->nOrderBy = nOrderBy;
99670  *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint = pIdxCons;
99671  *(struct sqlite3_index_orderby**)&pIdxInfo->aOrderBy = pIdxOrderBy;
99672  *(struct sqlite3_index_constraint_usage**)&pIdxInfo->aConstraintUsage =
99673                                                                   pUsage;
99674
99675  for(i=j=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
99676    if( pTerm->leftCursor != pSrc->iCursor ) continue;
99677    assert( (pTerm->eOperator&(pTerm->eOperator-1))==0 );
99678    testcase( pTerm->eOperator==WO_IN );
99679    testcase( pTerm->eOperator==WO_ISNULL );
99680    if( pTerm->eOperator & (WO_IN|WO_ISNULL) ) continue;
99681    pIdxCons[j].iColumn = pTerm->u.leftColumn;
99682    pIdxCons[j].iTermOffset = i;
99683    pIdxCons[j].op = (u8)pTerm->eOperator;
99684    /* The direct assignment in the previous line is possible only because
99685    ** the WO_ and SQLITE_INDEX_CONSTRAINT_ codes are identical.  The
99686    ** following asserts verify this fact. */
99687    assert( WO_EQ==SQLITE_INDEX_CONSTRAINT_EQ );
99688    assert( WO_LT==SQLITE_INDEX_CONSTRAINT_LT );
99689    assert( WO_LE==SQLITE_INDEX_CONSTRAINT_LE );
99690    assert( WO_GT==SQLITE_INDEX_CONSTRAINT_GT );
99691    assert( WO_GE==SQLITE_INDEX_CONSTRAINT_GE );
99692    assert( WO_MATCH==SQLITE_INDEX_CONSTRAINT_MATCH );
99693    assert( pTerm->eOperator & (WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE|WO_MATCH) );
99694    j++;
99695  }
99696  for(i=0; i<nOrderBy; i++){
99697    Expr *pExpr = pOrderBy->a[i].pExpr;
99698    pIdxOrderBy[i].iColumn = pExpr->iColumn;
99699    pIdxOrderBy[i].desc = pOrderBy->a[i].sortOrder;
99700  }
99701
99702  return pIdxInfo;
99703}
99704
99705/*
99706** The table object reference passed as the second argument to this function
99707** must represent a virtual table. This function invokes the xBestIndex()
99708** method of the virtual table with the sqlite3_index_info pointer passed
99709** as the argument.
99710**
99711** If an error occurs, pParse is populated with an error message and a
99712** non-zero value is returned. Otherwise, 0 is returned and the output
99713** part of the sqlite3_index_info structure is left populated.
99714**
99715** Whether or not an error is returned, it is the responsibility of the
99716** caller to eventually free p->idxStr if p->needToFreeIdxStr indicates
99717** that this is required.
99718*/
99719static int vtabBestIndex(Parse *pParse, Table *pTab, sqlite3_index_info *p){
99720  sqlite3_vtab *pVtab = sqlite3GetVTable(pParse->db, pTab)->pVtab;
99721  int i;
99722  int rc;
99723
99724  WHERETRACE(("xBestIndex for %s\n", pTab->zName));
99725  TRACE_IDX_INPUTS(p);
99726  rc = pVtab->pModule->xBestIndex(pVtab, p);
99727  TRACE_IDX_OUTPUTS(p);
99728
99729  if( rc!=SQLITE_OK ){
99730    if( rc==SQLITE_NOMEM ){
99731      pParse->db->mallocFailed = 1;
99732    }else if( !pVtab->zErrMsg ){
99733      sqlite3ErrorMsg(pParse, "%s", sqlite3ErrStr(rc));
99734    }else{
99735      sqlite3ErrorMsg(pParse, "%s", pVtab->zErrMsg);
99736    }
99737  }
99738  sqlite3_free(pVtab->zErrMsg);
99739  pVtab->zErrMsg = 0;
99740
99741  for(i=0; i<p->nConstraint; i++){
99742    if( !p->aConstraint[i].usable && p->aConstraintUsage[i].argvIndex>0 ){
99743      sqlite3ErrorMsg(pParse,
99744          "table %s: xBestIndex returned an invalid plan", pTab->zName);
99745    }
99746  }
99747
99748  return pParse->nErr;
99749}
99750
99751
99752/*
99753** Compute the best index for a virtual table.
99754**
99755** The best index is computed by the xBestIndex method of the virtual
99756** table module.  This routine is really just a wrapper that sets up
99757** the sqlite3_index_info structure that is used to communicate with
99758** xBestIndex.
99759**
99760** In a join, this routine might be called multiple times for the
99761** same virtual table.  The sqlite3_index_info structure is created
99762** and initialized on the first invocation and reused on all subsequent
99763** invocations.  The sqlite3_index_info structure is also used when
99764** code is generated to access the virtual table.  The whereInfoDelete()
99765** routine takes care of freeing the sqlite3_index_info structure after
99766** everybody has finished with it.
99767*/
99768static void bestVirtualIndex(
99769  Parse *pParse,                  /* The parsing context */
99770  WhereClause *pWC,               /* The WHERE clause */
99771  struct SrcList_item *pSrc,      /* The FROM clause term to search */
99772  Bitmask notReady,               /* Mask of cursors not available for index */
99773  Bitmask notValid,               /* Cursors not valid for any purpose */
99774  ExprList *pOrderBy,             /* The order by clause */
99775  WhereCost *pCost,               /* Lowest cost query plan */
99776  sqlite3_index_info **ppIdxInfo  /* Index information passed to xBestIndex */
99777){
99778  Table *pTab = pSrc->pTab;
99779  sqlite3_index_info *pIdxInfo;
99780  struct sqlite3_index_constraint *pIdxCons;
99781  struct sqlite3_index_constraint_usage *pUsage;
99782  WhereTerm *pTerm;
99783  int i, j;
99784  int nOrderBy;
99785  double rCost;
99786
99787  /* Make sure wsFlags is initialized to some sane value. Otherwise, if the
99788  ** malloc in allocateIndexInfo() fails and this function returns leaving
99789  ** wsFlags in an uninitialized state, the caller may behave unpredictably.
99790  */
99791  memset(pCost, 0, sizeof(*pCost));
99792  pCost->plan.wsFlags = WHERE_VIRTUALTABLE;
99793
99794  /* If the sqlite3_index_info structure has not been previously
99795  ** allocated and initialized, then allocate and initialize it now.
99796  */
99797  pIdxInfo = *ppIdxInfo;
99798  if( pIdxInfo==0 ){
99799    *ppIdxInfo = pIdxInfo = allocateIndexInfo(pParse, pWC, pSrc, pOrderBy);
99800  }
99801  if( pIdxInfo==0 ){
99802    return;
99803  }
99804
99805  /* At this point, the sqlite3_index_info structure that pIdxInfo points
99806  ** to will have been initialized, either during the current invocation or
99807  ** during some prior invocation.  Now we just have to customize the
99808  ** details of pIdxInfo for the current invocation and pass it to
99809  ** xBestIndex.
99810  */
99811
99812  /* The module name must be defined. Also, by this point there must
99813  ** be a pointer to an sqlite3_vtab structure. Otherwise
99814  ** sqlite3ViewGetColumnNames() would have picked up the error.
99815  */
99816  assert( pTab->azModuleArg && pTab->azModuleArg[0] );
99817  assert( sqlite3GetVTable(pParse->db, pTab) );
99818
99819  /* Set the aConstraint[].usable fields and initialize all
99820  ** output variables to zero.
99821  **
99822  ** aConstraint[].usable is true for constraints where the right-hand
99823  ** side contains only references to tables to the left of the current
99824  ** table.  In other words, if the constraint is of the form:
99825  **
99826  **           column = expr
99827  **
99828  ** and we are evaluating a join, then the constraint on column is
99829  ** only valid if all tables referenced in expr occur to the left
99830  ** of the table containing column.
99831  **
99832  ** The aConstraints[] array contains entries for all constraints
99833  ** on the current table.  That way we only have to compute it once
99834  ** even though we might try to pick the best index multiple times.
99835  ** For each attempt at picking an index, the order of tables in the
99836  ** join might be different so we have to recompute the usable flag
99837  ** each time.
99838  */
99839  pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
99840  pUsage = pIdxInfo->aConstraintUsage;
99841  for(i=0; i<pIdxInfo->nConstraint; i++, pIdxCons++){
99842    j = pIdxCons->iTermOffset;
99843    pTerm = &pWC->a[j];
99844    pIdxCons->usable = (pTerm->prereqRight&notReady) ? 0 : 1;
99845  }
99846  memset(pUsage, 0, sizeof(pUsage[0])*pIdxInfo->nConstraint);
99847  if( pIdxInfo->needToFreeIdxStr ){
99848    sqlite3_free(pIdxInfo->idxStr);
99849  }
99850  pIdxInfo->idxStr = 0;
99851  pIdxInfo->idxNum = 0;
99852  pIdxInfo->needToFreeIdxStr = 0;
99853  pIdxInfo->orderByConsumed = 0;
99854  /* ((double)2) In case of SQLITE_OMIT_FLOATING_POINT... */
99855  pIdxInfo->estimatedCost = SQLITE_BIG_DBL / ((double)2);
99856  nOrderBy = pIdxInfo->nOrderBy;
99857  if( !pOrderBy ){
99858    pIdxInfo->nOrderBy = 0;
99859  }
99860
99861  if( vtabBestIndex(pParse, pTab, pIdxInfo) ){
99862    return;
99863  }
99864
99865  pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
99866  for(i=0; i<pIdxInfo->nConstraint; i++){
99867    if( pUsage[i].argvIndex>0 ){
99868      pCost->used |= pWC->a[pIdxCons[i].iTermOffset].prereqRight;
99869    }
99870  }
99871
99872  /* If there is an ORDER BY clause, and the selected virtual table index
99873  ** does not satisfy it, increase the cost of the scan accordingly. This
99874  ** matches the processing for non-virtual tables in bestBtreeIndex().
99875  */
99876  rCost = pIdxInfo->estimatedCost;
99877  if( pOrderBy && pIdxInfo->orderByConsumed==0 ){
99878    rCost += estLog(rCost)*rCost;
99879  }
99880
99881  /* The cost is not allowed to be larger than SQLITE_BIG_DBL (the
99882  ** inital value of lowestCost in this loop. If it is, then the
99883  ** (cost<lowestCost) test below will never be true.
99884  **
99885  ** Use "(double)2" instead of "2.0" in case OMIT_FLOATING_POINT
99886  ** is defined.
99887  */
99888  if( (SQLITE_BIG_DBL/((double)2))<rCost ){
99889    pCost->rCost = (SQLITE_BIG_DBL/((double)2));
99890  }else{
99891    pCost->rCost = rCost;
99892  }
99893  pCost->plan.u.pVtabIdx = pIdxInfo;
99894  if( pIdxInfo->orderByConsumed ){
99895    pCost->plan.wsFlags |= WHERE_ORDERBY;
99896  }
99897  pCost->plan.nEq = 0;
99898  pIdxInfo->nOrderBy = nOrderBy;
99899
99900  /* Try to find a more efficient access pattern by using multiple indexes
99901  ** to optimize an OR expression within the WHERE clause.
99902  */
99903  bestOrClauseIndex(pParse, pWC, pSrc, notReady, notValid, pOrderBy, pCost);
99904}
99905#endif /* SQLITE_OMIT_VIRTUALTABLE */
99906
99907/*
99908** Argument pIdx is a pointer to an index structure that has an array of
99909** SQLITE_INDEX_SAMPLES evenly spaced samples of the first indexed column
99910** stored in Index.aSample. These samples divide the domain of values stored
99911** the index into (SQLITE_INDEX_SAMPLES+1) regions.
99912** Region 0 contains all values less than the first sample value. Region
99913** 1 contains values between the first and second samples.  Region 2 contains
99914** values between samples 2 and 3.  And so on.  Region SQLITE_INDEX_SAMPLES
99915** contains values larger than the last sample.
99916**
99917** If the index contains many duplicates of a single value, then it is
99918** possible that two or more adjacent samples can hold the same value.
99919** When that is the case, the smallest possible region code is returned
99920** when roundUp is false and the largest possible region code is returned
99921** when roundUp is true.
99922**
99923** If successful, this function determines which of the regions value
99924** pVal lies in, sets *piRegion to the region index (a value between 0
99925** and SQLITE_INDEX_SAMPLES+1, inclusive) and returns SQLITE_OK.
99926** Or, if an OOM occurs while converting text values between encodings,
99927** SQLITE_NOMEM is returned and *piRegion is undefined.
99928*/
99929#ifdef SQLITE_ENABLE_STAT2
99930static int whereRangeRegion(
99931  Parse *pParse,              /* Database connection */
99932  Index *pIdx,                /* Index to consider domain of */
99933  sqlite3_value *pVal,        /* Value to consider */
99934  int roundUp,                /* Return largest valid region if true */
99935  int *piRegion               /* OUT: Region of domain in which value lies */
99936){
99937  assert( roundUp==0 || roundUp==1 );
99938  if( ALWAYS(pVal) ){
99939    IndexSample *aSample = pIdx->aSample;
99940    int i = 0;
99941    int eType = sqlite3_value_type(pVal);
99942
99943    if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
99944      double r = sqlite3_value_double(pVal);
99945      for(i=0; i<SQLITE_INDEX_SAMPLES; i++){
99946        if( aSample[i].eType==SQLITE_NULL ) continue;
99947        if( aSample[i].eType>=SQLITE_TEXT ) break;
99948        if( roundUp ){
99949          if( aSample[i].u.r>r ) break;
99950        }else{
99951          if( aSample[i].u.r>=r ) break;
99952        }
99953      }
99954    }else if( eType==SQLITE_NULL ){
99955      i = 0;
99956      if( roundUp ){
99957        while( i<SQLITE_INDEX_SAMPLES && aSample[i].eType==SQLITE_NULL ) i++;
99958      }
99959    }else{
99960      sqlite3 *db = pParse->db;
99961      CollSeq *pColl;
99962      const u8 *z;
99963      int n;
99964
99965      /* pVal comes from sqlite3ValueFromExpr() so the type cannot be NULL */
99966      assert( eType==SQLITE_TEXT || eType==SQLITE_BLOB );
99967
99968      if( eType==SQLITE_BLOB ){
99969        z = (const u8 *)sqlite3_value_blob(pVal);
99970        pColl = db->pDfltColl;
99971        assert( pColl->enc==SQLITE_UTF8 );
99972      }else{
99973        pColl = sqlite3GetCollSeq(db, SQLITE_UTF8, 0, *pIdx->azColl);
99974        if( pColl==0 ){
99975          sqlite3ErrorMsg(pParse, "no such collation sequence: %s",
99976                          *pIdx->azColl);
99977          return SQLITE_ERROR;
99978        }
99979        z = (const u8 *)sqlite3ValueText(pVal, pColl->enc);
99980        if( !z ){
99981          return SQLITE_NOMEM;
99982        }
99983        assert( z && pColl && pColl->xCmp );
99984      }
99985      n = sqlite3ValueBytes(pVal, pColl->enc);
99986
99987      for(i=0; i<SQLITE_INDEX_SAMPLES; i++){
99988        int c;
99989        int eSampletype = aSample[i].eType;
99990        if( eSampletype==SQLITE_NULL || eSampletype<eType ) continue;
99991        if( (eSampletype!=eType) ) break;
99992#ifndef SQLITE_OMIT_UTF16
99993        if( pColl->enc!=SQLITE_UTF8 ){
99994          int nSample;
99995          char *zSample = sqlite3Utf8to16(
99996              db, pColl->enc, aSample[i].u.z, aSample[i].nByte, &nSample
99997          );
99998          if( !zSample ){
99999            assert( db->mallocFailed );
100000            return SQLITE_NOMEM;
100001          }
100002          c = pColl->xCmp(pColl->pUser, nSample, zSample, n, z);
100003          sqlite3DbFree(db, zSample);
100004        }else
100005#endif
100006        {
100007          c = pColl->xCmp(pColl->pUser, aSample[i].nByte, aSample[i].u.z, n, z);
100008        }
100009        if( c-roundUp>=0 ) break;
100010      }
100011    }
100012
100013    assert( i>=0 && i<=SQLITE_INDEX_SAMPLES );
100014    *piRegion = i;
100015  }
100016  return SQLITE_OK;
100017}
100018#endif   /* #ifdef SQLITE_ENABLE_STAT2 */
100019
100020/*
100021** If expression pExpr represents a literal value, set *pp to point to
100022** an sqlite3_value structure containing the same value, with affinity
100023** aff applied to it, before returning. It is the responsibility of the
100024** caller to eventually release this structure by passing it to
100025** sqlite3ValueFree().
100026**
100027** If the current parse is a recompile (sqlite3Reprepare()) and pExpr
100028** is an SQL variable that currently has a non-NULL value bound to it,
100029** create an sqlite3_value structure containing this value, again with
100030** affinity aff applied to it, instead.
100031**
100032** If neither of the above apply, set *pp to NULL.
100033**
100034** If an error occurs, return an error code. Otherwise, SQLITE_OK.
100035*/
100036#ifdef SQLITE_ENABLE_STAT2
100037static int valueFromExpr(
100038  Parse *pParse,
100039  Expr *pExpr,
100040  u8 aff,
100041  sqlite3_value **pp
100042){
100043  if( pExpr->op==TK_VARIABLE
100044   || (pExpr->op==TK_REGISTER && pExpr->op2==TK_VARIABLE)
100045  ){
100046    int iVar = pExpr->iColumn;
100047    sqlite3VdbeSetVarmask(pParse->pVdbe, iVar); /* IMP: R-23257-02778 */
100048    *pp = sqlite3VdbeGetValue(pParse->pReprepare, iVar, aff);
100049    return SQLITE_OK;
100050  }
100051  return sqlite3ValueFromExpr(pParse->db, pExpr, SQLITE_UTF8, aff, pp);
100052}
100053#endif
100054
100055/*
100056** This function is used to estimate the number of rows that will be visited
100057** by scanning an index for a range of values. The range may have an upper
100058** bound, a lower bound, or both. The WHERE clause terms that set the upper
100059** and lower bounds are represented by pLower and pUpper respectively. For
100060** example, assuming that index p is on t1(a):
100061**
100062**   ... FROM t1 WHERE a > ? AND a < ? ...
100063**                    |_____|   |_____|
100064**                       |         |
100065**                     pLower    pUpper
100066**
100067** If either of the upper or lower bound is not present, then NULL is passed in
100068** place of the corresponding WhereTerm.
100069**
100070** The nEq parameter is passed the index of the index column subject to the
100071** range constraint. Or, equivalently, the number of equality constraints
100072** optimized by the proposed index scan. For example, assuming index p is
100073** on t1(a, b), and the SQL query is:
100074**
100075**   ... FROM t1 WHERE a = ? AND b > ? AND b < ? ...
100076**
100077** then nEq should be passed the value 1 (as the range restricted column,
100078** b, is the second left-most column of the index). Or, if the query is:
100079**
100080**   ... FROM t1 WHERE a > ? AND a < ? ...
100081**
100082** then nEq should be passed 0.
100083**
100084** The returned value is an integer between 1 and 100, inclusive. A return
100085** value of 1 indicates that the proposed range scan is expected to visit
100086** approximately 1/100th (1%) of the rows selected by the nEq equality
100087** constraints (if any). A return value of 100 indicates that it is expected
100088** that the range scan will visit every row (100%) selected by the equality
100089** constraints.
100090**
100091** In the absence of sqlite_stat2 ANALYZE data, each range inequality
100092** reduces the search space by 3/4ths.  Hence a single constraint (x>?)
100093** results in a return of 25 and a range constraint (x>? AND x<?) results
100094** in a return of 6.
100095*/
100096static int whereRangeScanEst(
100097  Parse *pParse,       /* Parsing & code generating context */
100098  Index *p,            /* The index containing the range-compared column; "x" */
100099  int nEq,             /* index into p->aCol[] of the range-compared column */
100100  WhereTerm *pLower,   /* Lower bound on the range. ex: "x>123" Might be NULL */
100101  WhereTerm *pUpper,   /* Upper bound on the range. ex: "x<455" Might be NULL */
100102  int *piEst           /* OUT: Return value */
100103){
100104  int rc = SQLITE_OK;
100105
100106#ifdef SQLITE_ENABLE_STAT2
100107
100108  if( nEq==0 && p->aSample ){
100109    sqlite3_value *pLowerVal = 0;
100110    sqlite3_value *pUpperVal = 0;
100111    int iEst;
100112    int iLower = 0;
100113    int iUpper = SQLITE_INDEX_SAMPLES;
100114    int roundUpUpper = 0;
100115    int roundUpLower = 0;
100116    u8 aff = p->pTable->aCol[p->aiColumn[0]].affinity;
100117
100118    if( pLower ){
100119      Expr *pExpr = pLower->pExpr->pRight;
100120      rc = valueFromExpr(pParse, pExpr, aff, &pLowerVal);
100121      assert( pLower->eOperator==WO_GT || pLower->eOperator==WO_GE );
100122      roundUpLower = (pLower->eOperator==WO_GT) ?1:0;
100123    }
100124    if( rc==SQLITE_OK && pUpper ){
100125      Expr *pExpr = pUpper->pExpr->pRight;
100126      rc = valueFromExpr(pParse, pExpr, aff, &pUpperVal);
100127      assert( pUpper->eOperator==WO_LT || pUpper->eOperator==WO_LE );
100128      roundUpUpper = (pUpper->eOperator==WO_LE) ?1:0;
100129    }
100130
100131    if( rc!=SQLITE_OK || (pLowerVal==0 && pUpperVal==0) ){
100132      sqlite3ValueFree(pLowerVal);
100133      sqlite3ValueFree(pUpperVal);
100134      goto range_est_fallback;
100135    }else if( pLowerVal==0 ){
100136      rc = whereRangeRegion(pParse, p, pUpperVal, roundUpUpper, &iUpper);
100137      if( pLower ) iLower = iUpper/2;
100138    }else if( pUpperVal==0 ){
100139      rc = whereRangeRegion(pParse, p, pLowerVal, roundUpLower, &iLower);
100140      if( pUpper ) iUpper = (iLower + SQLITE_INDEX_SAMPLES + 1)/2;
100141    }else{
100142      rc = whereRangeRegion(pParse, p, pUpperVal, roundUpUpper, &iUpper);
100143      if( rc==SQLITE_OK ){
100144        rc = whereRangeRegion(pParse, p, pLowerVal, roundUpLower, &iLower);
100145      }
100146    }
100147    WHERETRACE(("range scan regions: %d..%d\n", iLower, iUpper));
100148
100149    iEst = iUpper - iLower;
100150    testcase( iEst==SQLITE_INDEX_SAMPLES );
100151    assert( iEst<=SQLITE_INDEX_SAMPLES );
100152    if( iEst<1 ){
100153      *piEst = 50/SQLITE_INDEX_SAMPLES;
100154    }else{
100155      *piEst = (iEst*100)/SQLITE_INDEX_SAMPLES;
100156    }
100157    sqlite3ValueFree(pLowerVal);
100158    sqlite3ValueFree(pUpperVal);
100159    return rc;
100160  }
100161range_est_fallback:
100162#else
100163  UNUSED_PARAMETER(pParse);
100164  UNUSED_PARAMETER(p);
100165  UNUSED_PARAMETER(nEq);
100166#endif
100167  assert( pLower || pUpper );
100168  *piEst = 100;
100169  if( pLower && (pLower->wtFlags & TERM_VNULL)==0 ) *piEst /= 4;
100170  if( pUpper ) *piEst /= 4;
100171  return rc;
100172}
100173
100174#ifdef SQLITE_ENABLE_STAT2
100175/*
100176** Estimate the number of rows that will be returned based on
100177** an equality constraint x=VALUE and where that VALUE occurs in
100178** the histogram data.  This only works when x is the left-most
100179** column of an index and sqlite_stat2 histogram data is available
100180** for that index.  When pExpr==NULL that means the constraint is
100181** "x IS NULL" instead of "x=VALUE".
100182**
100183** Write the estimated row count into *pnRow and return SQLITE_OK.
100184** If unable to make an estimate, leave *pnRow unchanged and return
100185** non-zero.
100186**
100187** This routine can fail if it is unable to load a collating sequence
100188** required for string comparison, or if unable to allocate memory
100189** for a UTF conversion required for comparison.  The error is stored
100190** in the pParse structure.
100191*/
100192static int whereEqualScanEst(
100193  Parse *pParse,       /* Parsing & code generating context */
100194  Index *p,            /* The index whose left-most column is pTerm */
100195  Expr *pExpr,         /* Expression for VALUE in the x=VALUE constraint */
100196  double *pnRow        /* Write the revised row estimate here */
100197){
100198  sqlite3_value *pRhs = 0;  /* VALUE on right-hand side of pTerm */
100199  int iLower, iUpper;       /* Range of histogram regions containing pRhs */
100200  u8 aff;                   /* Column affinity */
100201  int rc;                   /* Subfunction return code */
100202  double nRowEst;           /* New estimate of the number of rows */
100203
100204  assert( p->aSample!=0 );
100205  aff = p->pTable->aCol[p->aiColumn[0]].affinity;
100206  if( pExpr ){
100207    rc = valueFromExpr(pParse, pExpr, aff, &pRhs);
100208    if( rc ) goto whereEqualScanEst_cancel;
100209  }else{
100210    pRhs = sqlite3ValueNew(pParse->db);
100211  }
100212  if( pRhs==0 ) return SQLITE_NOTFOUND;
100213  rc = whereRangeRegion(pParse, p, pRhs, 0, &iLower);
100214  if( rc ) goto whereEqualScanEst_cancel;
100215  rc = whereRangeRegion(pParse, p, pRhs, 1, &iUpper);
100216  if( rc ) goto whereEqualScanEst_cancel;
100217  WHERETRACE(("equality scan regions: %d..%d\n", iLower, iUpper));
100218  if( iLower>=iUpper ){
100219    nRowEst = p->aiRowEst[0]/(SQLITE_INDEX_SAMPLES*2);
100220    if( nRowEst<*pnRow ) *pnRow = nRowEst;
100221  }else{
100222    nRowEst = (iUpper-iLower)*p->aiRowEst[0]/SQLITE_INDEX_SAMPLES;
100223    *pnRow = nRowEst;
100224  }
100225
100226whereEqualScanEst_cancel:
100227  sqlite3ValueFree(pRhs);
100228  return rc;
100229}
100230#endif /* defined(SQLITE_ENABLE_STAT2) */
100231
100232#ifdef SQLITE_ENABLE_STAT2
100233/*
100234** Estimate the number of rows that will be returned based on
100235** an IN constraint where the right-hand side of the IN operator
100236** is a list of values.  Example:
100237**
100238**        WHERE x IN (1,2,3,4)
100239**
100240** Write the estimated row count into *pnRow and return SQLITE_OK.
100241** If unable to make an estimate, leave *pnRow unchanged and return
100242** non-zero.
100243**
100244** This routine can fail if it is unable to load a collating sequence
100245** required for string comparison, or if unable to allocate memory
100246** for a UTF conversion required for comparison.  The error is stored
100247** in the pParse structure.
100248*/
100249static int whereInScanEst(
100250  Parse *pParse,       /* Parsing & code generating context */
100251  Index *p,            /* The index whose left-most column is pTerm */
100252  ExprList *pList,     /* The value list on the RHS of "x IN (v1,v2,v3,...)" */
100253  double *pnRow        /* Write the revised row estimate here */
100254){
100255  sqlite3_value *pVal = 0;  /* One value from list */
100256  int iLower, iUpper;       /* Range of histogram regions containing pRhs */
100257  u8 aff;                   /* Column affinity */
100258  int rc = SQLITE_OK;       /* Subfunction return code */
100259  double nRowEst;           /* New estimate of the number of rows */
100260  int nSpan = 0;            /* Number of histogram regions spanned */
100261  int nSingle = 0;          /* Histogram regions hit by a single value */
100262  int nNotFound = 0;        /* Count of values that are not constants */
100263  int i;                               /* Loop counter */
100264  u8 aSpan[SQLITE_INDEX_SAMPLES+1];    /* Histogram regions that are spanned */
100265  u8 aSingle[SQLITE_INDEX_SAMPLES+1];  /* Histogram regions hit once */
100266
100267  assert( p->aSample!=0 );
100268  aff = p->pTable->aCol[p->aiColumn[0]].affinity;
100269  memset(aSpan, 0, sizeof(aSpan));
100270  memset(aSingle, 0, sizeof(aSingle));
100271  for(i=0; i<pList->nExpr; i++){
100272    sqlite3ValueFree(pVal);
100273    rc = valueFromExpr(pParse, pList->a[i].pExpr, aff, &pVal);
100274    if( rc ) break;
100275    if( pVal==0 || sqlite3_value_type(pVal)==SQLITE_NULL ){
100276      nNotFound++;
100277      continue;
100278    }
100279    rc = whereRangeRegion(pParse, p, pVal, 0, &iLower);
100280    if( rc ) break;
100281    rc = whereRangeRegion(pParse, p, pVal, 1, &iUpper);
100282    if( rc ) break;
100283    if( iLower>=iUpper ){
100284      aSingle[iLower] = 1;
100285    }else{
100286      assert( iLower>=0 && iUpper<=SQLITE_INDEX_SAMPLES );
100287      while( iLower<iUpper ) aSpan[iLower++] = 1;
100288    }
100289  }
100290  if( rc==SQLITE_OK ){
100291    for(i=nSpan=0; i<=SQLITE_INDEX_SAMPLES; i++){
100292      if( aSpan[i] ){
100293        nSpan++;
100294      }else if( aSingle[i] ){
100295        nSingle++;
100296      }
100297    }
100298    nRowEst = (nSpan*2+nSingle)*p->aiRowEst[0]/(2*SQLITE_INDEX_SAMPLES)
100299               + nNotFound*p->aiRowEst[1];
100300    if( nRowEst > p->aiRowEst[0] ) nRowEst = p->aiRowEst[0];
100301    *pnRow = nRowEst;
100302    WHERETRACE(("IN row estimate: nSpan=%d, nSingle=%d, nNotFound=%d, est=%g\n",
100303                 nSpan, nSingle, nNotFound, nRowEst));
100304  }
100305  sqlite3ValueFree(pVal);
100306  return rc;
100307}
100308#endif /* defined(SQLITE_ENABLE_STAT2) */
100309
100310
100311/*
100312** Find the best query plan for accessing a particular table.  Write the
100313** best query plan and its cost into the WhereCost object supplied as the
100314** last parameter.
100315**
100316** The lowest cost plan wins.  The cost is an estimate of the amount of
100317** CPU and disk I/O needed to process the requested result.
100318** Factors that influence cost include:
100319**
100320**    *  The estimated number of rows that will be retrieved.  (The
100321**       fewer the better.)
100322**
100323**    *  Whether or not sorting must occur.
100324**
100325**    *  Whether or not there must be separate lookups in the
100326**       index and in the main table.
100327**
100328** If there was an INDEXED BY clause (pSrc->pIndex) attached to the table in
100329** the SQL statement, then this function only considers plans using the
100330** named index. If no such plan is found, then the returned cost is
100331** SQLITE_BIG_DBL. If a plan is found that uses the named index,
100332** then the cost is calculated in the usual way.
100333**
100334** If a NOT INDEXED clause (pSrc->notIndexed!=0) was attached to the table
100335** in the SELECT statement, then no indexes are considered. However, the
100336** selected plan may still take advantage of the built-in rowid primary key
100337** index.
100338*/
100339static void bestBtreeIndex(
100340  Parse *pParse,              /* The parsing context */
100341  WhereClause *pWC,           /* The WHERE clause */
100342  struct SrcList_item *pSrc,  /* The FROM clause term to search */
100343  Bitmask notReady,           /* Mask of cursors not available for indexing */
100344  Bitmask notValid,           /* Cursors not available for any purpose */
100345  ExprList *pOrderBy,         /* The ORDER BY clause */
100346  WhereCost *pCost            /* Lowest cost query plan */
100347){
100348  int iCur = pSrc->iCursor;   /* The cursor of the table to be accessed */
100349  Index *pProbe;              /* An index we are evaluating */
100350  Index *pIdx;                /* Copy of pProbe, or zero for IPK index */
100351  int eqTermMask;             /* Current mask of valid equality operators */
100352  int idxEqTermMask;          /* Index mask of valid equality operators */
100353  Index sPk;                  /* A fake index object for the primary key */
100354  unsigned int aiRowEstPk[2]; /* The aiRowEst[] value for the sPk index */
100355  int aiColumnPk = -1;        /* The aColumn[] value for the sPk index */
100356  int wsFlagMask;             /* Allowed flags in pCost->plan.wsFlag */
100357
100358  /* Initialize the cost to a worst-case value */
100359  memset(pCost, 0, sizeof(*pCost));
100360  pCost->rCost = SQLITE_BIG_DBL;
100361
100362  /* If the pSrc table is the right table of a LEFT JOIN then we may not
100363  ** use an index to satisfy IS NULL constraints on that table.  This is
100364  ** because columns might end up being NULL if the table does not match -
100365  ** a circumstance which the index cannot help us discover.  Ticket #2177.
100366  */
100367  if( pSrc->jointype & JT_LEFT ){
100368    idxEqTermMask = WO_EQ|WO_IN;
100369  }else{
100370    idxEqTermMask = WO_EQ|WO_IN|WO_ISNULL;
100371  }
100372
100373  if( pSrc->pIndex ){
100374    /* An INDEXED BY clause specifies a particular index to use */
100375    pIdx = pProbe = pSrc->pIndex;
100376    wsFlagMask = ~(WHERE_ROWID_EQ|WHERE_ROWID_RANGE);
100377    eqTermMask = idxEqTermMask;
100378  }else{
100379    /* There is no INDEXED BY clause.  Create a fake Index object in local
100380    ** variable sPk to represent the rowid primary key index.  Make this
100381    ** fake index the first in a chain of Index objects with all of the real
100382    ** indices to follow */
100383    Index *pFirst;                  /* First of real indices on the table */
100384    memset(&sPk, 0, sizeof(Index));
100385    sPk.nColumn = 1;
100386    sPk.aiColumn = &aiColumnPk;
100387    sPk.aiRowEst = aiRowEstPk;
100388    sPk.onError = OE_Replace;
100389    sPk.pTable = pSrc->pTab;
100390    aiRowEstPk[0] = pSrc->pTab->nRowEst;
100391    aiRowEstPk[1] = 1;
100392    pFirst = pSrc->pTab->pIndex;
100393    if( pSrc->notIndexed==0 ){
100394      /* The real indices of the table are only considered if the
100395      ** NOT INDEXED qualifier is omitted from the FROM clause */
100396      sPk.pNext = pFirst;
100397    }
100398    pProbe = &sPk;
100399    wsFlagMask = ~(
100400        WHERE_COLUMN_IN|WHERE_COLUMN_EQ|WHERE_COLUMN_NULL|WHERE_COLUMN_RANGE
100401    );
100402    eqTermMask = WO_EQ|WO_IN;
100403    pIdx = 0;
100404  }
100405
100406  /* Loop over all indices looking for the best one to use
100407  */
100408  for(; pProbe; pIdx=pProbe=pProbe->pNext){
100409    const unsigned int * const aiRowEst = pProbe->aiRowEst;
100410    double cost;                /* Cost of using pProbe */
100411    double nRow;                /* Estimated number of rows in result set */
100412    double log10N;              /* base-10 logarithm of nRow (inexact) */
100413    int rev;                    /* True to scan in reverse order */
100414    int wsFlags = 0;
100415    Bitmask used = 0;
100416
100417    /* The following variables are populated based on the properties of
100418    ** index being evaluated. They are then used to determine the expected
100419    ** cost and number of rows returned.
100420    **
100421    **  nEq:
100422    **    Number of equality terms that can be implemented using the index.
100423    **    In other words, the number of initial fields in the index that
100424    **    are used in == or IN or NOT NULL constraints of the WHERE clause.
100425    **
100426    **  nInMul:
100427    **    The "in-multiplier". This is an estimate of how many seek operations
100428    **    SQLite must perform on the index in question. For example, if the
100429    **    WHERE clause is:
100430    **
100431    **      WHERE a IN (1, 2, 3) AND b IN (4, 5, 6)
100432    **
100433    **    SQLite must perform 9 lookups on an index on (a, b), so nInMul is
100434    **    set to 9. Given the same schema and either of the following WHERE
100435    **    clauses:
100436    **
100437    **      WHERE a =  1
100438    **      WHERE a >= 2
100439    **
100440    **    nInMul is set to 1.
100441    **
100442    **    If there exists a WHERE term of the form "x IN (SELECT ...)", then
100443    **    the sub-select is assumed to return 25 rows for the purposes of
100444    **    determining nInMul.
100445    **
100446    **  bInEst:
100447    **    Set to true if there was at least one "x IN (SELECT ...)" term used
100448    **    in determining the value of nInMul.  Note that the RHS of the
100449    **    IN operator must be a SELECT, not a value list, for this variable
100450    **    to be true.
100451    **
100452    **  estBound:
100453    **    An estimate on the amount of the table that must be searched.  A
100454    **    value of 100 means the entire table is searched.  Range constraints
100455    **    might reduce this to a value less than 100 to indicate that only
100456    **    a fraction of the table needs searching.  In the absence of
100457    **    sqlite_stat2 ANALYZE data, a single inequality reduces the search
100458    **    space to 1/4rd its original size.  So an x>? constraint reduces
100459    **    estBound to 25.  Two constraints (x>? AND x<?) reduce estBound to 6.
100460    **
100461    **  bSort:
100462    **    Boolean. True if there is an ORDER BY clause that will require an
100463    **    external sort (i.e. scanning the index being evaluated will not
100464    **    correctly order records).
100465    **
100466    **  bLookup:
100467    **    Boolean. True if a table lookup is required for each index entry
100468    **    visited.  In other words, true if this is not a covering index.
100469    **    This is always false for the rowid primary key index of a table.
100470    **    For other indexes, it is true unless all the columns of the table
100471    **    used by the SELECT statement are present in the index (such an
100472    **    index is sometimes described as a covering index).
100473    **    For example, given the index on (a, b), the second of the following
100474    **    two queries requires table b-tree lookups in order to find the value
100475    **    of column c, but the first does not because columns a and b are
100476    **    both available in the index.
100477    **
100478    **             SELECT a, b    FROM tbl WHERE a = 1;
100479    **             SELECT a, b, c FROM tbl WHERE a = 1;
100480    */
100481    int nEq;                      /* Number of == or IN terms matching index */
100482    int bInEst = 0;               /* True if "x IN (SELECT...)" seen */
100483    int nInMul = 1;               /* Number of distinct equalities to lookup */
100484    int estBound = 100;           /* Estimated reduction in search space */
100485    int nBound = 0;               /* Number of range constraints seen */
100486    int bSort = 0;                /* True if external sort required */
100487    int bLookup = 0;              /* True if not a covering index */
100488    WhereTerm *pTerm;             /* A single term of the WHERE clause */
100489#ifdef SQLITE_ENABLE_STAT2
100490    WhereTerm *pFirstTerm = 0;    /* First term matching the index */
100491#endif
100492
100493    /* Determine the values of nEq and nInMul */
100494    for(nEq=0; nEq<pProbe->nColumn; nEq++){
100495      int j = pProbe->aiColumn[nEq];
100496      pTerm = findTerm(pWC, iCur, j, notReady, eqTermMask, pIdx);
100497      if( pTerm==0 ) break;
100498      wsFlags |= (WHERE_COLUMN_EQ|WHERE_ROWID_EQ);
100499      if( pTerm->eOperator & WO_IN ){
100500        Expr *pExpr = pTerm->pExpr;
100501        wsFlags |= WHERE_COLUMN_IN;
100502        if( ExprHasProperty(pExpr, EP_xIsSelect) ){
100503          /* "x IN (SELECT ...)":  Assume the SELECT returns 25 rows */
100504          nInMul *= 25;
100505          bInEst = 1;
100506        }else if( ALWAYS(pExpr->x.pList && pExpr->x.pList->nExpr) ){
100507          /* "x IN (value, value, ...)" */
100508          nInMul *= pExpr->x.pList->nExpr;
100509        }
100510      }else if( pTerm->eOperator & WO_ISNULL ){
100511        wsFlags |= WHERE_COLUMN_NULL;
100512      }
100513#ifdef SQLITE_ENABLE_STAT2
100514      if( nEq==0 && pProbe->aSample ) pFirstTerm = pTerm;
100515#endif
100516      used |= pTerm->prereqRight;
100517    }
100518
100519    /* Determine the value of estBound. */
100520    if( nEq<pProbe->nColumn && pProbe->bUnordered==0 ){
100521      int j = pProbe->aiColumn[nEq];
100522      if( findTerm(pWC, iCur, j, notReady, WO_LT|WO_LE|WO_GT|WO_GE, pIdx) ){
100523        WhereTerm *pTop = findTerm(pWC, iCur, j, notReady, WO_LT|WO_LE, pIdx);
100524        WhereTerm *pBtm = findTerm(pWC, iCur, j, notReady, WO_GT|WO_GE, pIdx);
100525        whereRangeScanEst(pParse, pProbe, nEq, pBtm, pTop, &estBound);
100526        if( pTop ){
100527          nBound = 1;
100528          wsFlags |= WHERE_TOP_LIMIT;
100529          used |= pTop->prereqRight;
100530        }
100531        if( pBtm ){
100532          nBound++;
100533          wsFlags |= WHERE_BTM_LIMIT;
100534          used |= pBtm->prereqRight;
100535        }
100536        wsFlags |= (WHERE_COLUMN_RANGE|WHERE_ROWID_RANGE);
100537      }
100538    }else if( pProbe->onError!=OE_None ){
100539      testcase( wsFlags & WHERE_COLUMN_IN );
100540      testcase( wsFlags & WHERE_COLUMN_NULL );
100541      if( (wsFlags & (WHERE_COLUMN_IN|WHERE_COLUMN_NULL))==0 ){
100542        wsFlags |= WHERE_UNIQUE;
100543      }
100544    }
100545
100546    /* If there is an ORDER BY clause and the index being considered will
100547    ** naturally scan rows in the required order, set the appropriate flags
100548    ** in wsFlags. Otherwise, if there is an ORDER BY clause but the index
100549    ** will scan rows in a different order, set the bSort variable.  */
100550    if( pOrderBy ){
100551      if( (wsFlags & WHERE_COLUMN_IN)==0
100552        && pProbe->bUnordered==0
100553        && isSortingIndex(pParse, pWC->pMaskSet, pProbe, iCur, pOrderBy,
100554                          nEq, wsFlags, &rev)
100555      ){
100556        wsFlags |= WHERE_ROWID_RANGE|WHERE_COLUMN_RANGE|WHERE_ORDERBY;
100557        wsFlags |= (rev ? WHERE_REVERSE : 0);
100558      }else{
100559        bSort = 1;
100560      }
100561    }
100562
100563    /* If currently calculating the cost of using an index (not the IPK
100564    ** index), determine if all required column data may be obtained without
100565    ** using the main table (i.e. if the index is a covering
100566    ** index for this query). If it is, set the WHERE_IDX_ONLY flag in
100567    ** wsFlags. Otherwise, set the bLookup variable to true.  */
100568    if( pIdx && wsFlags ){
100569      Bitmask m = pSrc->colUsed;
100570      int j;
100571      for(j=0; j<pIdx->nColumn; j++){
100572        int x = pIdx->aiColumn[j];
100573        if( x<BMS-1 ){
100574          m &= ~(((Bitmask)1)<<x);
100575        }
100576      }
100577      if( m==0 ){
100578        wsFlags |= WHERE_IDX_ONLY;
100579      }else{
100580        bLookup = 1;
100581      }
100582    }
100583
100584    /*
100585    ** Estimate the number of rows of output.  For an "x IN (SELECT...)"
100586    ** constraint, do not let the estimate exceed half the rows in the table.
100587    */
100588    nRow = (double)(aiRowEst[nEq] * nInMul);
100589    if( bInEst && nRow*2>aiRowEst[0] ){
100590      nRow = aiRowEst[0]/2;
100591      nInMul = (int)(nRow / aiRowEst[nEq]);
100592    }
100593
100594#ifdef SQLITE_ENABLE_STAT2
100595    /* If the constraint is of the form x=VALUE and histogram
100596    ** data is available for column x, then it might be possible
100597    ** to get a better estimate on the number of rows based on
100598    ** VALUE and how common that value is according to the histogram.
100599    */
100600    if( nRow>(double)1 && nEq==1 && pFirstTerm!=0 ){
100601      if( pFirstTerm->eOperator & (WO_EQ|WO_ISNULL) ){
100602        testcase( pFirstTerm->eOperator==WO_EQ );
100603        testcase( pFirstTerm->eOperator==WO_ISNULL );
100604        whereEqualScanEst(pParse, pProbe, pFirstTerm->pExpr->pRight, &nRow);
100605      }else if( pFirstTerm->eOperator==WO_IN && bInEst==0 ){
100606        whereInScanEst(pParse, pProbe, pFirstTerm->pExpr->x.pList, &nRow);
100607      }
100608    }
100609#endif /* SQLITE_ENABLE_STAT2 */
100610
100611    /* Adjust the number of output rows and downward to reflect rows
100612    ** that are excluded by range constraints.
100613    */
100614    nRow = (nRow * (double)estBound) / (double)100;
100615    if( nRow<1 ) nRow = 1;
100616
100617    /* Experiments run on real SQLite databases show that the time needed
100618    ** to do a binary search to locate a row in a table or index is roughly
100619    ** log10(N) times the time to move from one row to the next row within
100620    ** a table or index.  The actual times can vary, with the size of
100621    ** records being an important factor.  Both moves and searches are
100622    ** slower with larger records, presumably because fewer records fit
100623    ** on one page and hence more pages have to be fetched.
100624    **
100625    ** The ANALYZE command and the sqlite_stat1 and sqlite_stat2 tables do
100626    ** not give us data on the relative sizes of table and index records.
100627    ** So this computation assumes table records are about twice as big
100628    ** as index records
100629    */
100630    if( (wsFlags & WHERE_NOT_FULLSCAN)==0 ){
100631      /* The cost of a full table scan is a number of move operations equal
100632      ** to the number of rows in the table.
100633      **
100634      ** We add an additional 4x penalty to full table scans.  This causes
100635      ** the cost function to err on the side of choosing an index over
100636      ** choosing a full scan.  This 4x full-scan penalty is an arguable
100637      ** decision and one which we expect to revisit in the future.  But
100638      ** it seems to be working well enough at the moment.
100639      */
100640      cost = aiRowEst[0]*4;
100641    }else{
100642      log10N = estLog(aiRowEst[0]);
100643      cost = nRow;
100644      if( pIdx ){
100645        if( bLookup ){
100646          /* For an index lookup followed by a table lookup:
100647          **    nInMul index searches to find the start of each index range
100648          **  + nRow steps through the index
100649          **  + nRow table searches to lookup the table entry using the rowid
100650          */
100651          cost += (nInMul + nRow)*log10N;
100652        }else{
100653          /* For a covering index:
100654          **     nInMul index searches to find the initial entry
100655          **   + nRow steps through the index
100656          */
100657          cost += nInMul*log10N;
100658        }
100659      }else{
100660        /* For a rowid primary key lookup:
100661        **    nInMult table searches to find the initial entry for each range
100662        **  + nRow steps through the table
100663        */
100664        cost += nInMul*log10N;
100665      }
100666    }
100667
100668    /* Add in the estimated cost of sorting the result.  Actual experimental
100669    ** measurements of sorting performance in SQLite show that sorting time
100670    ** adds C*N*log10(N) to the cost, where N is the number of rows to be
100671    ** sorted and C is a factor between 1.95 and 4.3.  We will split the
100672    ** difference and select C of 3.0.
100673    */
100674    if( bSort ){
100675      cost += nRow*estLog(nRow)*3;
100676    }
100677
100678    /**** Cost of using this index has now been computed ****/
100679
100680    /* If there are additional constraints on this table that cannot
100681    ** be used with the current index, but which might lower the number
100682    ** of output rows, adjust the nRow value accordingly.  This only
100683    ** matters if the current index is the least costly, so do not bother
100684    ** with this step if we already know this index will not be chosen.
100685    ** Also, never reduce the output row count below 2 using this step.
100686    **
100687    ** It is critical that the notValid mask be used here instead of
100688    ** the notReady mask.  When computing an "optimal" index, the notReady
100689    ** mask will only have one bit set - the bit for the current table.
100690    ** The notValid mask, on the other hand, always has all bits set for
100691    ** tables that are not in outer loops.  If notReady is used here instead
100692    ** of notValid, then a optimal index that depends on inner joins loops
100693    ** might be selected even when there exists an optimal index that has
100694    ** no such dependency.
100695    */
100696    if( nRow>2 && cost<=pCost->rCost ){
100697      int k;                       /* Loop counter */
100698      int nSkipEq = nEq;           /* Number of == constraints to skip */
100699      int nSkipRange = nBound;     /* Number of < constraints to skip */
100700      Bitmask thisTab;             /* Bitmap for pSrc */
100701
100702      thisTab = getMask(pWC->pMaskSet, iCur);
100703      for(pTerm=pWC->a, k=pWC->nTerm; nRow>2 && k; k--, pTerm++){
100704        if( pTerm->wtFlags & TERM_VIRTUAL ) continue;
100705        if( (pTerm->prereqAll & notValid)!=thisTab ) continue;
100706        if( pTerm->eOperator & (WO_EQ|WO_IN|WO_ISNULL) ){
100707          if( nSkipEq ){
100708            /* Ignore the first nEq equality matches since the index
100709            ** has already accounted for these */
100710            nSkipEq--;
100711          }else{
100712            /* Assume each additional equality match reduces the result
100713            ** set size by a factor of 10 */
100714            nRow /= 10;
100715          }
100716        }else if( pTerm->eOperator & (WO_LT|WO_LE|WO_GT|WO_GE) ){
100717          if( nSkipRange ){
100718            /* Ignore the first nSkipRange range constraints since the index
100719            ** has already accounted for these */
100720            nSkipRange--;
100721          }else{
100722            /* Assume each additional range constraint reduces the result
100723            ** set size by a factor of 3.  Indexed range constraints reduce
100724            ** the search space by a larger factor: 4.  We make indexed range
100725            ** more selective intentionally because of the subjective
100726            ** observation that indexed range constraints really are more
100727            ** selective in practice, on average. */
100728            nRow /= 3;
100729          }
100730        }else if( pTerm->eOperator!=WO_NOOP ){
100731          /* Any other expression lowers the output row count by half */
100732          nRow /= 2;
100733        }
100734      }
100735      if( nRow<2 ) nRow = 2;
100736    }
100737
100738
100739    WHERETRACE((
100740      "%s(%s): nEq=%d nInMul=%d estBound=%d bSort=%d bLookup=%d wsFlags=0x%x\n"
100741      "         notReady=0x%llx log10N=%.1f nRow=%.1f cost=%.1f used=0x%llx\n",
100742      pSrc->pTab->zName, (pIdx ? pIdx->zName : "ipk"),
100743      nEq, nInMul, estBound, bSort, bLookup, wsFlags,
100744      notReady, log10N, nRow, cost, used
100745    ));
100746
100747    /* If this index is the best we have seen so far, then record this
100748    ** index and its cost in the pCost structure.
100749    */
100750    if( (!pIdx || wsFlags)
100751     && (cost<pCost->rCost || (cost<=pCost->rCost && nRow<pCost->plan.nRow))
100752    ){
100753      pCost->rCost = cost;
100754      pCost->used = used;
100755      pCost->plan.nRow = nRow;
100756      pCost->plan.wsFlags = (wsFlags&wsFlagMask);
100757      pCost->plan.nEq = nEq;
100758      pCost->plan.u.pIdx = pIdx;
100759    }
100760
100761    /* If there was an INDEXED BY clause, then only that one index is
100762    ** considered. */
100763    if( pSrc->pIndex ) break;
100764
100765    /* Reset masks for the next index in the loop */
100766    wsFlagMask = ~(WHERE_ROWID_EQ|WHERE_ROWID_RANGE);
100767    eqTermMask = idxEqTermMask;
100768  }
100769
100770  /* If there is no ORDER BY clause and the SQLITE_ReverseOrder flag
100771  ** is set, then reverse the order that the index will be scanned
100772  ** in. This is used for application testing, to help find cases
100773  ** where application behaviour depends on the (undefined) order that
100774  ** SQLite outputs rows in in the absence of an ORDER BY clause.  */
100775  if( !pOrderBy && pParse->db->flags & SQLITE_ReverseOrder ){
100776    pCost->plan.wsFlags |= WHERE_REVERSE;
100777  }
100778
100779  assert( pOrderBy || (pCost->plan.wsFlags&WHERE_ORDERBY)==0 );
100780  assert( pCost->plan.u.pIdx==0 || (pCost->plan.wsFlags&WHERE_ROWID_EQ)==0 );
100781  assert( pSrc->pIndex==0
100782       || pCost->plan.u.pIdx==0
100783       || pCost->plan.u.pIdx==pSrc->pIndex
100784  );
100785
100786  WHERETRACE(("best index is: %s\n",
100787    ((pCost->plan.wsFlags & WHERE_NOT_FULLSCAN)==0 ? "none" :
100788         pCost->plan.u.pIdx ? pCost->plan.u.pIdx->zName : "ipk")
100789  ));
100790
100791  bestOrClauseIndex(pParse, pWC, pSrc, notReady, notValid, pOrderBy, pCost);
100792  bestAutomaticIndex(pParse, pWC, pSrc, notReady, pCost);
100793  pCost->plan.wsFlags |= eqTermMask;
100794}
100795
100796/*
100797** Find the query plan for accessing table pSrc->pTab. Write the
100798** best query plan and its cost into the WhereCost object supplied
100799** as the last parameter. This function may calculate the cost of
100800** both real and virtual table scans.
100801*/
100802static void bestIndex(
100803  Parse *pParse,              /* The parsing context */
100804  WhereClause *pWC,           /* The WHERE clause */
100805  struct SrcList_item *pSrc,  /* The FROM clause term to search */
100806  Bitmask notReady,           /* Mask of cursors not available for indexing */
100807  Bitmask notValid,           /* Cursors not available for any purpose */
100808  ExprList *pOrderBy,         /* The ORDER BY clause */
100809  WhereCost *pCost            /* Lowest cost query plan */
100810){
100811#ifndef SQLITE_OMIT_VIRTUALTABLE
100812  if( IsVirtual(pSrc->pTab) ){
100813    sqlite3_index_info *p = 0;
100814    bestVirtualIndex(pParse, pWC, pSrc, notReady, notValid, pOrderBy, pCost,&p);
100815    if( p->needToFreeIdxStr ){
100816      sqlite3_free(p->idxStr);
100817    }
100818    sqlite3DbFree(pParse->db, p);
100819  }else
100820#endif
100821  {
100822    bestBtreeIndex(pParse, pWC, pSrc, notReady, notValid, pOrderBy, pCost);
100823  }
100824}
100825
100826/*
100827** Disable a term in the WHERE clause.  Except, do not disable the term
100828** if it controls a LEFT OUTER JOIN and it did not originate in the ON
100829** or USING clause of that join.
100830**
100831** Consider the term t2.z='ok' in the following queries:
100832**
100833**   (1)  SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x WHERE t2.z='ok'
100834**   (2)  SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x AND t2.z='ok'
100835**   (3)  SELECT * FROM t1, t2 WHERE t1.a=t2.x AND t2.z='ok'
100836**
100837** The t2.z='ok' is disabled in the in (2) because it originates
100838** in the ON clause.  The term is disabled in (3) because it is not part
100839** of a LEFT OUTER JOIN.  In (1), the term is not disabled.
100840**
100841** IMPLEMENTATION-OF: R-24597-58655 No tests are done for terms that are
100842** completely satisfied by indices.
100843**
100844** Disabling a term causes that term to not be tested in the inner loop
100845** of the join.  Disabling is an optimization.  When terms are satisfied
100846** by indices, we disable them to prevent redundant tests in the inner
100847** loop.  We would get the correct results if nothing were ever disabled,
100848** but joins might run a little slower.  The trick is to disable as much
100849** as we can without disabling too much.  If we disabled in (1), we'd get
100850** the wrong answer.  See ticket #813.
100851*/
100852static void disableTerm(WhereLevel *pLevel, WhereTerm *pTerm){
100853  if( pTerm
100854      && (pTerm->wtFlags & TERM_CODED)==0
100855      && (pLevel->iLeftJoin==0 || ExprHasProperty(pTerm->pExpr, EP_FromJoin))
100856  ){
100857    pTerm->wtFlags |= TERM_CODED;
100858    if( pTerm->iParent>=0 ){
100859      WhereTerm *pOther = &pTerm->pWC->a[pTerm->iParent];
100860      if( (--pOther->nChild)==0 ){
100861        disableTerm(pLevel, pOther);
100862      }
100863    }
100864  }
100865}
100866
100867/*
100868** Code an OP_Affinity opcode to apply the column affinity string zAff
100869** to the n registers starting at base.
100870**
100871** As an optimization, SQLITE_AFF_NONE entries (which are no-ops) at the
100872** beginning and end of zAff are ignored.  If all entries in zAff are
100873** SQLITE_AFF_NONE, then no code gets generated.
100874**
100875** This routine makes its own copy of zAff so that the caller is free
100876** to modify zAff after this routine returns.
100877*/
100878static void codeApplyAffinity(Parse *pParse, int base, int n, char *zAff){
100879  Vdbe *v = pParse->pVdbe;
100880  if( zAff==0 ){
100881    assert( pParse->db->mallocFailed );
100882    return;
100883  }
100884  assert( v!=0 );
100885
100886  /* Adjust base and n to skip over SQLITE_AFF_NONE entries at the beginning
100887  ** and end of the affinity string.
100888  */
100889  while( n>0 && zAff[0]==SQLITE_AFF_NONE ){
100890    n--;
100891    base++;
100892    zAff++;
100893  }
100894  while( n>1 && zAff[n-1]==SQLITE_AFF_NONE ){
100895    n--;
100896  }
100897
100898  /* Code the OP_Affinity opcode if there is anything left to do. */
100899  if( n>0 ){
100900    sqlite3VdbeAddOp2(v, OP_Affinity, base, n);
100901    sqlite3VdbeChangeP4(v, -1, zAff, n);
100902    sqlite3ExprCacheAffinityChange(pParse, base, n);
100903  }
100904}
100905
100906
100907/*
100908** Generate code for a single equality term of the WHERE clause.  An equality
100909** term can be either X=expr or X IN (...).   pTerm is the term to be
100910** coded.
100911**
100912** The current value for the constraint is left in register iReg.
100913**
100914** For a constraint of the form X=expr, the expression is evaluated and its
100915** result is left on the stack.  For constraints of the form X IN (...)
100916** this routine sets up a loop that will iterate over all values of X.
100917*/
100918static int codeEqualityTerm(
100919  Parse *pParse,      /* The parsing context */
100920  WhereTerm *pTerm,   /* The term of the WHERE clause to be coded */
100921  WhereLevel *pLevel, /* When level of the FROM clause we are working on */
100922  int iTarget         /* Attempt to leave results in this register */
100923){
100924  Expr *pX = pTerm->pExpr;
100925  Vdbe *v = pParse->pVdbe;
100926  int iReg;                  /* Register holding results */
100927
100928  assert( iTarget>0 );
100929  if( pX->op==TK_EQ ){
100930    iReg = sqlite3ExprCodeTarget(pParse, pX->pRight, iTarget);
100931  }else if( pX->op==TK_ISNULL ){
100932    iReg = iTarget;
100933    sqlite3VdbeAddOp2(v, OP_Null, 0, iReg);
100934#ifndef SQLITE_OMIT_SUBQUERY
100935  }else{
100936    int eType;
100937    int iTab;
100938    struct InLoop *pIn;
100939
100940    assert( pX->op==TK_IN );
100941    iReg = iTarget;
100942    eType = sqlite3FindInIndex(pParse, pX, 0);
100943    iTab = pX->iTable;
100944    sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0);
100945    assert( pLevel->plan.wsFlags & WHERE_IN_ABLE );
100946    if( pLevel->u.in.nIn==0 ){
100947      pLevel->addrNxt = sqlite3VdbeMakeLabel(v);
100948    }
100949    pLevel->u.in.nIn++;
100950    pLevel->u.in.aInLoop =
100951       sqlite3DbReallocOrFree(pParse->db, pLevel->u.in.aInLoop,
100952                              sizeof(pLevel->u.in.aInLoop[0])*pLevel->u.in.nIn);
100953    pIn = pLevel->u.in.aInLoop;
100954    if( pIn ){
100955      pIn += pLevel->u.in.nIn - 1;
100956      pIn->iCur = iTab;
100957      if( eType==IN_INDEX_ROWID ){
100958        pIn->addrInTop = sqlite3VdbeAddOp2(v, OP_Rowid, iTab, iReg);
100959      }else{
100960        pIn->addrInTop = sqlite3VdbeAddOp3(v, OP_Column, iTab, 0, iReg);
100961      }
100962      sqlite3VdbeAddOp1(v, OP_IsNull, iReg);
100963    }else{
100964      pLevel->u.in.nIn = 0;
100965    }
100966#endif
100967  }
100968  disableTerm(pLevel, pTerm);
100969  return iReg;
100970}
100971
100972/*
100973** Generate code that will evaluate all == and IN constraints for an
100974** index.
100975**
100976** For example, consider table t1(a,b,c,d,e,f) with index i1(a,b,c).
100977** Suppose the WHERE clause is this:  a==5 AND b IN (1,2,3) AND c>5 AND c<10
100978** The index has as many as three equality constraints, but in this
100979** example, the third "c" value is an inequality.  So only two
100980** constraints are coded.  This routine will generate code to evaluate
100981** a==5 and b IN (1,2,3).  The current values for a and b will be stored
100982** in consecutive registers and the index of the first register is returned.
100983**
100984** In the example above nEq==2.  But this subroutine works for any value
100985** of nEq including 0.  If nEq==0, this routine is nearly a no-op.
100986** The only thing it does is allocate the pLevel->iMem memory cell and
100987** compute the affinity string.
100988**
100989** This routine always allocates at least one memory cell and returns
100990** the index of that memory cell. The code that
100991** calls this routine will use that memory cell to store the termination
100992** key value of the loop.  If one or more IN operators appear, then
100993** this routine allocates an additional nEq memory cells for internal
100994** use.
100995**
100996** Before returning, *pzAff is set to point to a buffer containing a
100997** copy of the column affinity string of the index allocated using
100998** sqlite3DbMalloc(). Except, entries in the copy of the string associated
100999** with equality constraints that use NONE affinity are set to
101000** SQLITE_AFF_NONE. This is to deal with SQL such as the following:
101001**
101002**   CREATE TABLE t1(a TEXT PRIMARY KEY, b);
101003**   SELECT ... FROM t1 AS t2, t1 WHERE t1.a = t2.b;
101004**
101005** In the example above, the index on t1(a) has TEXT affinity. But since
101006** the right hand side of the equality constraint (t2.b) has NONE affinity,
101007** no conversion should be attempted before using a t2.b value as part of
101008** a key to search the index. Hence the first byte in the returned affinity
101009** string in this example would be set to SQLITE_AFF_NONE.
101010*/
101011static int codeAllEqualityTerms(
101012  Parse *pParse,        /* Parsing context */
101013  WhereLevel *pLevel,   /* Which nested loop of the FROM we are coding */
101014  WhereClause *pWC,     /* The WHERE clause */
101015  Bitmask notReady,     /* Which parts of FROM have not yet been coded */
101016  int nExtraReg,        /* Number of extra registers to allocate */
101017  char **pzAff          /* OUT: Set to point to affinity string */
101018){
101019  int nEq = pLevel->plan.nEq;   /* The number of == or IN constraints to code */
101020  Vdbe *v = pParse->pVdbe;      /* The vm under construction */
101021  Index *pIdx;                  /* The index being used for this loop */
101022  int iCur = pLevel->iTabCur;   /* The cursor of the table */
101023  WhereTerm *pTerm;             /* A single constraint term */
101024  int j;                        /* Loop counter */
101025  int regBase;                  /* Base register */
101026  int nReg;                     /* Number of registers to allocate */
101027  char *zAff;                   /* Affinity string to return */
101028
101029  /* This module is only called on query plans that use an index. */
101030  assert( pLevel->plan.wsFlags & WHERE_INDEXED );
101031  pIdx = pLevel->plan.u.pIdx;
101032
101033  /* Figure out how many memory cells we will need then allocate them.
101034  */
101035  regBase = pParse->nMem + 1;
101036  nReg = pLevel->plan.nEq + nExtraReg;
101037  pParse->nMem += nReg;
101038
101039  zAff = sqlite3DbStrDup(pParse->db, sqlite3IndexAffinityStr(v, pIdx));
101040  if( !zAff ){
101041    pParse->db->mallocFailed = 1;
101042  }
101043
101044  /* Evaluate the equality constraints
101045  */
101046  assert( pIdx->nColumn>=nEq );
101047  for(j=0; j<nEq; j++){
101048    int r1;
101049    int k = pIdx->aiColumn[j];
101050    pTerm = findTerm(pWC, iCur, k, notReady, pLevel->plan.wsFlags, pIdx);
101051    if( NEVER(pTerm==0) ) break;
101052    /* The following true for indices with redundant columns.
101053    ** Ex: CREATE INDEX i1 ON t1(a,b,a); SELECT * FROM t1 WHERE a=0 AND b=0; */
101054    testcase( (pTerm->wtFlags & TERM_CODED)!=0 );
101055    testcase( pTerm->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
101056    r1 = codeEqualityTerm(pParse, pTerm, pLevel, regBase+j);
101057    if( r1!=regBase+j ){
101058      if( nReg==1 ){
101059        sqlite3ReleaseTempReg(pParse, regBase);
101060        regBase = r1;
101061      }else{
101062        sqlite3VdbeAddOp2(v, OP_SCopy, r1, regBase+j);
101063      }
101064    }
101065    testcase( pTerm->eOperator & WO_ISNULL );
101066    testcase( pTerm->eOperator & WO_IN );
101067    if( (pTerm->eOperator & (WO_ISNULL|WO_IN))==0 ){
101068      Expr *pRight = pTerm->pExpr->pRight;
101069      sqlite3ExprCodeIsNullJump(v, pRight, regBase+j, pLevel->addrBrk);
101070      if( zAff ){
101071        if( sqlite3CompareAffinity(pRight, zAff[j])==SQLITE_AFF_NONE ){
101072          zAff[j] = SQLITE_AFF_NONE;
101073        }
101074        if( sqlite3ExprNeedsNoAffinityChange(pRight, zAff[j]) ){
101075          zAff[j] = SQLITE_AFF_NONE;
101076        }
101077      }
101078    }
101079  }
101080  *pzAff = zAff;
101081  return regBase;
101082}
101083
101084#ifndef SQLITE_OMIT_EXPLAIN
101085/*
101086** This routine is a helper for explainIndexRange() below
101087**
101088** pStr holds the text of an expression that we are building up one term
101089** at a time.  This routine adds a new term to the end of the expression.
101090** Terms are separated by AND so add the "AND" text for second and subsequent
101091** terms only.
101092*/
101093static void explainAppendTerm(
101094  StrAccum *pStr,             /* The text expression being built */
101095  int iTerm,                  /* Index of this term.  First is zero */
101096  const char *zColumn,        /* Name of the column */
101097  const char *zOp             /* Name of the operator */
101098){
101099  if( iTerm ) sqlite3StrAccumAppend(pStr, " AND ", 5);
101100  sqlite3StrAccumAppend(pStr, zColumn, -1);
101101  sqlite3StrAccumAppend(pStr, zOp, 1);
101102  sqlite3StrAccumAppend(pStr, "?", 1);
101103}
101104
101105/*
101106** Argument pLevel describes a strategy for scanning table pTab. This
101107** function returns a pointer to a string buffer containing a description
101108** of the subset of table rows scanned by the strategy in the form of an
101109** SQL expression. Or, if all rows are scanned, NULL is returned.
101110**
101111** For example, if the query:
101112**
101113**   SELECT * FROM t1 WHERE a=1 AND b>2;
101114**
101115** is run and there is an index on (a, b), then this function returns a
101116** string similar to:
101117**
101118**   "a=? AND b>?"
101119**
101120** The returned pointer points to memory obtained from sqlite3DbMalloc().
101121** It is the responsibility of the caller to free the buffer when it is
101122** no longer required.
101123*/
101124static char *explainIndexRange(sqlite3 *db, WhereLevel *pLevel, Table *pTab){
101125  WherePlan *pPlan = &pLevel->plan;
101126  Index *pIndex = pPlan->u.pIdx;
101127  int nEq = pPlan->nEq;
101128  int i, j;
101129  Column *aCol = pTab->aCol;
101130  int *aiColumn = pIndex->aiColumn;
101131  StrAccum txt;
101132
101133  if( nEq==0 && (pPlan->wsFlags & (WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))==0 ){
101134    return 0;
101135  }
101136  sqlite3StrAccumInit(&txt, 0, 0, SQLITE_MAX_LENGTH);
101137  txt.db = db;
101138  sqlite3StrAccumAppend(&txt, " (", 2);
101139  for(i=0; i<nEq; i++){
101140    explainAppendTerm(&txt, i, aCol[aiColumn[i]].zName, "=");
101141  }
101142
101143  j = i;
101144  if( pPlan->wsFlags&WHERE_BTM_LIMIT ){
101145    explainAppendTerm(&txt, i++, aCol[aiColumn[j]].zName, ">");
101146  }
101147  if( pPlan->wsFlags&WHERE_TOP_LIMIT ){
101148    explainAppendTerm(&txt, i, aCol[aiColumn[j]].zName, "<");
101149  }
101150  sqlite3StrAccumAppend(&txt, ")", 1);
101151  return sqlite3StrAccumFinish(&txt);
101152}
101153
101154/*
101155** This function is a no-op unless currently processing an EXPLAIN QUERY PLAN
101156** command. If the query being compiled is an EXPLAIN QUERY PLAN, a single
101157** record is added to the output to describe the table scan strategy in
101158** pLevel.
101159*/
101160static void explainOneScan(
101161  Parse *pParse,                  /* Parse context */
101162  SrcList *pTabList,              /* Table list this loop refers to */
101163  WhereLevel *pLevel,             /* Scan to write OP_Explain opcode for */
101164  int iLevel,                     /* Value for "level" column of output */
101165  int iFrom,                      /* Value for "from" column of output */
101166  u16 wctrlFlags                  /* Flags passed to sqlite3WhereBegin() */
101167){
101168  if( pParse->explain==2 ){
101169    u32 flags = pLevel->plan.wsFlags;
101170    struct SrcList_item *pItem = &pTabList->a[pLevel->iFrom];
101171    Vdbe *v = pParse->pVdbe;      /* VM being constructed */
101172    sqlite3 *db = pParse->db;     /* Database handle */
101173    char *zMsg;                   /* Text to add to EQP output */
101174    sqlite3_int64 nRow;           /* Expected number of rows visited by scan */
101175    int iId = pParse->iSelectId;  /* Select id (left-most output column) */
101176    int isSearch;                 /* True for a SEARCH. False for SCAN. */
101177
101178    if( (flags&WHERE_MULTI_OR) || (wctrlFlags&WHERE_ONETABLE_ONLY) ) return;
101179
101180    isSearch = (pLevel->plan.nEq>0)
101181             || (flags&(WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))!=0
101182             || (wctrlFlags&(WHERE_ORDERBY_MIN|WHERE_ORDERBY_MAX));
101183
101184    zMsg = sqlite3MPrintf(db, "%s", isSearch?"SEARCH":"SCAN");
101185    if( pItem->pSelect ){
101186      zMsg = sqlite3MAppendf(db, zMsg, "%s SUBQUERY %d", zMsg,pItem->iSelectId);
101187    }else{
101188      zMsg = sqlite3MAppendf(db, zMsg, "%s TABLE %s", zMsg, pItem->zName);
101189    }
101190
101191    if( pItem->zAlias ){
101192      zMsg = sqlite3MAppendf(db, zMsg, "%s AS %s", zMsg, pItem->zAlias);
101193    }
101194    if( (flags & WHERE_INDEXED)!=0 ){
101195      char *zWhere = explainIndexRange(db, pLevel, pItem->pTab);
101196      zMsg = sqlite3MAppendf(db, zMsg, "%s USING %s%sINDEX%s%s%s", zMsg,
101197          ((flags & WHERE_TEMP_INDEX)?"AUTOMATIC ":""),
101198          ((flags & WHERE_IDX_ONLY)?"COVERING ":""),
101199          ((flags & WHERE_TEMP_INDEX)?"":" "),
101200          ((flags & WHERE_TEMP_INDEX)?"": pLevel->plan.u.pIdx->zName),
101201          zWhere
101202      );
101203      sqlite3DbFree(db, zWhere);
101204    }else if( flags & (WHERE_ROWID_EQ|WHERE_ROWID_RANGE) ){
101205      zMsg = sqlite3MAppendf(db, zMsg, "%s USING INTEGER PRIMARY KEY", zMsg);
101206
101207      if( flags&WHERE_ROWID_EQ ){
101208        zMsg = sqlite3MAppendf(db, zMsg, "%s (rowid=?)", zMsg);
101209      }else if( (flags&WHERE_BOTH_LIMIT)==WHERE_BOTH_LIMIT ){
101210        zMsg = sqlite3MAppendf(db, zMsg, "%s (rowid>? AND rowid<?)", zMsg);
101211      }else if( flags&WHERE_BTM_LIMIT ){
101212        zMsg = sqlite3MAppendf(db, zMsg, "%s (rowid>?)", zMsg);
101213      }else if( flags&WHERE_TOP_LIMIT ){
101214        zMsg = sqlite3MAppendf(db, zMsg, "%s (rowid<?)", zMsg);
101215      }
101216    }
101217#ifndef SQLITE_OMIT_VIRTUALTABLE
101218    else if( (flags & WHERE_VIRTUALTABLE)!=0 ){
101219      sqlite3_index_info *pVtabIdx = pLevel->plan.u.pVtabIdx;
101220      zMsg = sqlite3MAppendf(db, zMsg, "%s VIRTUAL TABLE INDEX %d:%s", zMsg,
101221                  pVtabIdx->idxNum, pVtabIdx->idxStr);
101222    }
101223#endif
101224    if( wctrlFlags&(WHERE_ORDERBY_MIN|WHERE_ORDERBY_MAX) ){
101225      testcase( wctrlFlags & WHERE_ORDERBY_MIN );
101226      nRow = 1;
101227    }else{
101228      nRow = (sqlite3_int64)pLevel->plan.nRow;
101229    }
101230    zMsg = sqlite3MAppendf(db, zMsg, "%s (~%lld rows)", zMsg, nRow);
101231    sqlite3VdbeAddOp4(v, OP_Explain, iId, iLevel, iFrom, zMsg, P4_DYNAMIC);
101232  }
101233}
101234#else
101235# define explainOneScan(u,v,w,x,y,z)
101236#endif /* SQLITE_OMIT_EXPLAIN */
101237
101238
101239/*
101240** Generate code for the start of the iLevel-th loop in the WHERE clause
101241** implementation described by pWInfo.
101242*/
101243static Bitmask codeOneLoopStart(
101244  WhereInfo *pWInfo,   /* Complete information about the WHERE clause */
101245  int iLevel,          /* Which level of pWInfo->a[] should be coded */
101246  u16 wctrlFlags,      /* One of the WHERE_* flags defined in sqliteInt.h */
101247  Bitmask notReady     /* Which tables are currently available */
101248){
101249  int j, k;            /* Loop counters */
101250  int iCur;            /* The VDBE cursor for the table */
101251  int addrNxt;         /* Where to jump to continue with the next IN case */
101252  int omitTable;       /* True if we use the index only */
101253  int bRev;            /* True if we need to scan in reverse order */
101254  WhereLevel *pLevel;  /* The where level to be coded */
101255  WhereClause *pWC;    /* Decomposition of the entire WHERE clause */
101256  WhereTerm *pTerm;               /* A WHERE clause term */
101257  Parse *pParse;                  /* Parsing context */
101258  Vdbe *v;                        /* The prepared stmt under constructions */
101259  struct SrcList_item *pTabItem;  /* FROM clause term being coded */
101260  int addrBrk;                    /* Jump here to break out of the loop */
101261  int addrCont;                   /* Jump here to continue with next cycle */
101262  int iRowidReg = 0;        /* Rowid is stored in this register, if not zero */
101263  int iReleaseReg = 0;      /* Temp register to free before returning */
101264
101265  pParse = pWInfo->pParse;
101266  v = pParse->pVdbe;
101267  pWC = pWInfo->pWC;
101268  pLevel = &pWInfo->a[iLevel];
101269  pTabItem = &pWInfo->pTabList->a[pLevel->iFrom];
101270  iCur = pTabItem->iCursor;
101271  bRev = (pLevel->plan.wsFlags & WHERE_REVERSE)!=0;
101272  omitTable = (pLevel->plan.wsFlags & WHERE_IDX_ONLY)!=0
101273           && (wctrlFlags & WHERE_FORCE_TABLE)==0;
101274
101275  /* Create labels for the "break" and "continue" instructions
101276  ** for the current loop.  Jump to addrBrk to break out of a loop.
101277  ** Jump to cont to go immediately to the next iteration of the
101278  ** loop.
101279  **
101280  ** When there is an IN operator, we also have a "addrNxt" label that
101281  ** means to continue with the next IN value combination.  When
101282  ** there are no IN operators in the constraints, the "addrNxt" label
101283  ** is the same as "addrBrk".
101284  */
101285  addrBrk = pLevel->addrBrk = pLevel->addrNxt = sqlite3VdbeMakeLabel(v);
101286  addrCont = pLevel->addrCont = sqlite3VdbeMakeLabel(v);
101287
101288  /* If this is the right table of a LEFT OUTER JOIN, allocate and
101289  ** initialize a memory cell that records if this table matches any
101290  ** row of the left table of the join.
101291  */
101292  if( pLevel->iFrom>0 && (pTabItem[0].jointype & JT_LEFT)!=0 ){
101293    pLevel->iLeftJoin = ++pParse->nMem;
101294    sqlite3VdbeAddOp2(v, OP_Integer, 0, pLevel->iLeftJoin);
101295    VdbeComment((v, "init LEFT JOIN no-match flag"));
101296  }
101297
101298#ifndef SQLITE_OMIT_VIRTUALTABLE
101299  if(  (pLevel->plan.wsFlags & WHERE_VIRTUALTABLE)!=0 ){
101300    /* Case 0:  The table is a virtual-table.  Use the VFilter and VNext
101301    **          to access the data.
101302    */
101303    int iReg;   /* P3 Value for OP_VFilter */
101304    sqlite3_index_info *pVtabIdx = pLevel->plan.u.pVtabIdx;
101305    int nConstraint = pVtabIdx->nConstraint;
101306    struct sqlite3_index_constraint_usage *aUsage =
101307                                                pVtabIdx->aConstraintUsage;
101308    const struct sqlite3_index_constraint *aConstraint =
101309                                                pVtabIdx->aConstraint;
101310
101311    sqlite3ExprCachePush(pParse);
101312    iReg = sqlite3GetTempRange(pParse, nConstraint+2);
101313    for(j=1; j<=nConstraint; j++){
101314      for(k=0; k<nConstraint; k++){
101315        if( aUsage[k].argvIndex==j ){
101316          int iTerm = aConstraint[k].iTermOffset;
101317          sqlite3ExprCode(pParse, pWC->a[iTerm].pExpr->pRight, iReg+j+1);
101318          break;
101319        }
101320      }
101321      if( k==nConstraint ) break;
101322    }
101323    sqlite3VdbeAddOp2(v, OP_Integer, pVtabIdx->idxNum, iReg);
101324    sqlite3VdbeAddOp2(v, OP_Integer, j-1, iReg+1);
101325    sqlite3VdbeAddOp4(v, OP_VFilter, iCur, addrBrk, iReg, pVtabIdx->idxStr,
101326                      pVtabIdx->needToFreeIdxStr ? P4_MPRINTF : P4_STATIC);
101327    pVtabIdx->needToFreeIdxStr = 0;
101328    for(j=0; j<nConstraint; j++){
101329      if( aUsage[j].omit ){
101330        int iTerm = aConstraint[j].iTermOffset;
101331        disableTerm(pLevel, &pWC->a[iTerm]);
101332      }
101333    }
101334    pLevel->op = OP_VNext;
101335    pLevel->p1 = iCur;
101336    pLevel->p2 = sqlite3VdbeCurrentAddr(v);
101337    sqlite3ReleaseTempRange(pParse, iReg, nConstraint+2);
101338    sqlite3ExprCachePop(pParse, 1);
101339  }else
101340#endif /* SQLITE_OMIT_VIRTUALTABLE */
101341
101342  if( pLevel->plan.wsFlags & WHERE_ROWID_EQ ){
101343    /* Case 1:  We can directly reference a single row using an
101344    **          equality comparison against the ROWID field.  Or
101345    **          we reference multiple rows using a "rowid IN (...)"
101346    **          construct.
101347    */
101348    iReleaseReg = sqlite3GetTempReg(pParse);
101349    pTerm = findTerm(pWC, iCur, -1, notReady, WO_EQ|WO_IN, 0);
101350    assert( pTerm!=0 );
101351    assert( pTerm->pExpr!=0 );
101352    assert( pTerm->leftCursor==iCur );
101353    assert( omitTable==0 );
101354    testcase( pTerm->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
101355    iRowidReg = codeEqualityTerm(pParse, pTerm, pLevel, iReleaseReg);
101356    addrNxt = pLevel->addrNxt;
101357    sqlite3VdbeAddOp2(v, OP_MustBeInt, iRowidReg, addrNxt);
101358    sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addrNxt, iRowidReg);
101359    sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
101360    VdbeComment((v, "pk"));
101361    pLevel->op = OP_Noop;
101362  }else if( pLevel->plan.wsFlags & WHERE_ROWID_RANGE ){
101363    /* Case 2:  We have an inequality comparison against the ROWID field.
101364    */
101365    int testOp = OP_Noop;
101366    int start;
101367    int memEndValue = 0;
101368    WhereTerm *pStart, *pEnd;
101369
101370    assert( omitTable==0 );
101371    pStart = findTerm(pWC, iCur, -1, notReady, WO_GT|WO_GE, 0);
101372    pEnd = findTerm(pWC, iCur, -1, notReady, WO_LT|WO_LE, 0);
101373    if( bRev ){
101374      pTerm = pStart;
101375      pStart = pEnd;
101376      pEnd = pTerm;
101377    }
101378    if( pStart ){
101379      Expr *pX;             /* The expression that defines the start bound */
101380      int r1, rTemp;        /* Registers for holding the start boundary */
101381
101382      /* The following constant maps TK_xx codes into corresponding
101383      ** seek opcodes.  It depends on a particular ordering of TK_xx
101384      */
101385      const u8 aMoveOp[] = {
101386           /* TK_GT */  OP_SeekGt,
101387           /* TK_LE */  OP_SeekLe,
101388           /* TK_LT */  OP_SeekLt,
101389           /* TK_GE */  OP_SeekGe
101390      };
101391      assert( TK_LE==TK_GT+1 );      /* Make sure the ordering.. */
101392      assert( TK_LT==TK_GT+2 );      /*  ... of the TK_xx values... */
101393      assert( TK_GE==TK_GT+3 );      /*  ... is correcct. */
101394
101395      testcase( pStart->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
101396      pX = pStart->pExpr;
101397      assert( pX!=0 );
101398      assert( pStart->leftCursor==iCur );
101399      r1 = sqlite3ExprCodeTemp(pParse, pX->pRight, &rTemp);
101400      sqlite3VdbeAddOp3(v, aMoveOp[pX->op-TK_GT], iCur, addrBrk, r1);
101401      VdbeComment((v, "pk"));
101402      sqlite3ExprCacheAffinityChange(pParse, r1, 1);
101403      sqlite3ReleaseTempReg(pParse, rTemp);
101404      disableTerm(pLevel, pStart);
101405    }else{
101406      sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iCur, addrBrk);
101407    }
101408    if( pEnd ){
101409      Expr *pX;
101410      pX = pEnd->pExpr;
101411      assert( pX!=0 );
101412      assert( pEnd->leftCursor==iCur );
101413      testcase( pEnd->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
101414      memEndValue = ++pParse->nMem;
101415      sqlite3ExprCode(pParse, pX->pRight, memEndValue);
101416      if( pX->op==TK_LT || pX->op==TK_GT ){
101417        testOp = bRev ? OP_Le : OP_Ge;
101418      }else{
101419        testOp = bRev ? OP_Lt : OP_Gt;
101420      }
101421      disableTerm(pLevel, pEnd);
101422    }
101423    start = sqlite3VdbeCurrentAddr(v);
101424    pLevel->op = bRev ? OP_Prev : OP_Next;
101425    pLevel->p1 = iCur;
101426    pLevel->p2 = start;
101427    if( pStart==0 && pEnd==0 ){
101428      pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
101429    }else{
101430      assert( pLevel->p5==0 );
101431    }
101432    if( testOp!=OP_Noop ){
101433      iRowidReg = iReleaseReg = sqlite3GetTempReg(pParse);
101434      sqlite3VdbeAddOp2(v, OP_Rowid, iCur, iRowidReg);
101435      sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
101436      sqlite3VdbeAddOp3(v, testOp, memEndValue, addrBrk, iRowidReg);
101437      sqlite3VdbeChangeP5(v, SQLITE_AFF_NUMERIC | SQLITE_JUMPIFNULL);
101438    }
101439  }else if( pLevel->plan.wsFlags & (WHERE_COLUMN_RANGE|WHERE_COLUMN_EQ) ){
101440    /* Case 3: A scan using an index.
101441    **
101442    **         The WHERE clause may contain zero or more equality
101443    **         terms ("==" or "IN" operators) that refer to the N
101444    **         left-most columns of the index. It may also contain
101445    **         inequality constraints (>, <, >= or <=) on the indexed
101446    **         column that immediately follows the N equalities. Only
101447    **         the right-most column can be an inequality - the rest must
101448    **         use the "==" and "IN" operators. For example, if the
101449    **         index is on (x,y,z), then the following clauses are all
101450    **         optimized:
101451    **
101452    **            x=5
101453    **            x=5 AND y=10
101454    **            x=5 AND y<10
101455    **            x=5 AND y>5 AND y<10
101456    **            x=5 AND y=5 AND z<=10
101457    **
101458    **         The z<10 term of the following cannot be used, only
101459    **         the x=5 term:
101460    **
101461    **            x=5 AND z<10
101462    **
101463    **         N may be zero if there are inequality constraints.
101464    **         If there are no inequality constraints, then N is at
101465    **         least one.
101466    **
101467    **         This case is also used when there are no WHERE clause
101468    **         constraints but an index is selected anyway, in order
101469    **         to force the output order to conform to an ORDER BY.
101470    */
101471    static const u8 aStartOp[] = {
101472      0,
101473      0,
101474      OP_Rewind,           /* 2: (!start_constraints && startEq &&  !bRev) */
101475      OP_Last,             /* 3: (!start_constraints && startEq &&   bRev) */
101476      OP_SeekGt,           /* 4: (start_constraints  && !startEq && !bRev) */
101477      OP_SeekLt,           /* 5: (start_constraints  && !startEq &&  bRev) */
101478      OP_SeekGe,           /* 6: (start_constraints  &&  startEq && !bRev) */
101479      OP_SeekLe            /* 7: (start_constraints  &&  startEq &&  bRev) */
101480    };
101481    static const u8 aEndOp[] = {
101482      OP_Noop,             /* 0: (!end_constraints) */
101483      OP_IdxGE,            /* 1: (end_constraints && !bRev) */
101484      OP_IdxLT             /* 2: (end_constraints && bRev) */
101485    };
101486    int nEq = pLevel->plan.nEq;  /* Number of == or IN terms */
101487    int isMinQuery = 0;          /* If this is an optimized SELECT min(x).. */
101488    int regBase;                 /* Base register holding constraint values */
101489    int r1;                      /* Temp register */
101490    WhereTerm *pRangeStart = 0;  /* Inequality constraint at range start */
101491    WhereTerm *pRangeEnd = 0;    /* Inequality constraint at range end */
101492    int startEq;                 /* True if range start uses ==, >= or <= */
101493    int endEq;                   /* True if range end uses ==, >= or <= */
101494    int start_constraints;       /* Start of range is constrained */
101495    int nConstraint;             /* Number of constraint terms */
101496    Index *pIdx;                 /* The index we will be using */
101497    int iIdxCur;                 /* The VDBE cursor for the index */
101498    int nExtraReg = 0;           /* Number of extra registers needed */
101499    int op;                      /* Instruction opcode */
101500    char *zStartAff;             /* Affinity for start of range constraint */
101501    char *zEndAff;               /* Affinity for end of range constraint */
101502
101503    pIdx = pLevel->plan.u.pIdx;
101504    iIdxCur = pLevel->iIdxCur;
101505    k = pIdx->aiColumn[nEq];     /* Column for inequality constraints */
101506
101507    /* If this loop satisfies a sort order (pOrderBy) request that
101508    ** was passed to this function to implement a "SELECT min(x) ..."
101509    ** query, then the caller will only allow the loop to run for
101510    ** a single iteration. This means that the first row returned
101511    ** should not have a NULL value stored in 'x'. If column 'x' is
101512    ** the first one after the nEq equality constraints in the index,
101513    ** this requires some special handling.
101514    */
101515    if( (wctrlFlags&WHERE_ORDERBY_MIN)!=0
101516     && (pLevel->plan.wsFlags&WHERE_ORDERBY)
101517     && (pIdx->nColumn>nEq)
101518    ){
101519      /* assert( pOrderBy->nExpr==1 ); */
101520      /* assert( pOrderBy->a[0].pExpr->iColumn==pIdx->aiColumn[nEq] ); */
101521      isMinQuery = 1;
101522      nExtraReg = 1;
101523    }
101524
101525    /* Find any inequality constraint terms for the start and end
101526    ** of the range.
101527    */
101528    if( pLevel->plan.wsFlags & WHERE_TOP_LIMIT ){
101529      pRangeEnd = findTerm(pWC, iCur, k, notReady, (WO_LT|WO_LE), pIdx);
101530      nExtraReg = 1;
101531    }
101532    if( pLevel->plan.wsFlags & WHERE_BTM_LIMIT ){
101533      pRangeStart = findTerm(pWC, iCur, k, notReady, (WO_GT|WO_GE), pIdx);
101534      nExtraReg = 1;
101535    }
101536
101537    /* Generate code to evaluate all constraint terms using == or IN
101538    ** and store the values of those terms in an array of registers
101539    ** starting at regBase.
101540    */
101541    regBase = codeAllEqualityTerms(
101542        pParse, pLevel, pWC, notReady, nExtraReg, &zStartAff
101543    );
101544    zEndAff = sqlite3DbStrDup(pParse->db, zStartAff);
101545    addrNxt = pLevel->addrNxt;
101546
101547    /* If we are doing a reverse order scan on an ascending index, or
101548    ** a forward order scan on a descending index, interchange the
101549    ** start and end terms (pRangeStart and pRangeEnd).
101550    */
101551    if( nEq<pIdx->nColumn && bRev==(pIdx->aSortOrder[nEq]==SQLITE_SO_ASC) ){
101552      SWAP(WhereTerm *, pRangeEnd, pRangeStart);
101553    }
101554
101555    testcase( pRangeStart && pRangeStart->eOperator & WO_LE );
101556    testcase( pRangeStart && pRangeStart->eOperator & WO_GE );
101557    testcase( pRangeEnd && pRangeEnd->eOperator & WO_LE );
101558    testcase( pRangeEnd && pRangeEnd->eOperator & WO_GE );
101559    startEq = !pRangeStart || pRangeStart->eOperator & (WO_LE|WO_GE);
101560    endEq =   !pRangeEnd || pRangeEnd->eOperator & (WO_LE|WO_GE);
101561    start_constraints = pRangeStart || nEq>0;
101562
101563    /* Seek the index cursor to the start of the range. */
101564    nConstraint = nEq;
101565    if( pRangeStart ){
101566      Expr *pRight = pRangeStart->pExpr->pRight;
101567      sqlite3ExprCode(pParse, pRight, regBase+nEq);
101568      if( (pRangeStart->wtFlags & TERM_VNULL)==0 ){
101569        sqlite3ExprCodeIsNullJump(v, pRight, regBase+nEq, addrNxt);
101570      }
101571      if( zStartAff ){
101572        if( sqlite3CompareAffinity(pRight, zStartAff[nEq])==SQLITE_AFF_NONE){
101573          /* Since the comparison is to be performed with no conversions
101574          ** applied to the operands, set the affinity to apply to pRight to
101575          ** SQLITE_AFF_NONE.  */
101576          zStartAff[nEq] = SQLITE_AFF_NONE;
101577        }
101578        if( sqlite3ExprNeedsNoAffinityChange(pRight, zStartAff[nEq]) ){
101579          zStartAff[nEq] = SQLITE_AFF_NONE;
101580        }
101581      }
101582      nConstraint++;
101583      testcase( pRangeStart->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
101584    }else if( isMinQuery ){
101585      sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq);
101586      nConstraint++;
101587      startEq = 0;
101588      start_constraints = 1;
101589    }
101590    codeApplyAffinity(pParse, regBase, nConstraint, zStartAff);
101591    op = aStartOp[(start_constraints<<2) + (startEq<<1) + bRev];
101592    assert( op!=0 );
101593    testcase( op==OP_Rewind );
101594    testcase( op==OP_Last );
101595    testcase( op==OP_SeekGt );
101596    testcase( op==OP_SeekGe );
101597    testcase( op==OP_SeekLe );
101598    testcase( op==OP_SeekLt );
101599    sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
101600
101601    /* Load the value for the inequality constraint at the end of the
101602    ** range (if any).
101603    */
101604    nConstraint = nEq;
101605    if( pRangeEnd ){
101606      Expr *pRight = pRangeEnd->pExpr->pRight;
101607      sqlite3ExprCacheRemove(pParse, regBase+nEq, 1);
101608      sqlite3ExprCode(pParse, pRight, regBase+nEq);
101609      if( (pRangeEnd->wtFlags & TERM_VNULL)==0 ){
101610        sqlite3ExprCodeIsNullJump(v, pRight, regBase+nEq, addrNxt);
101611      }
101612      if( zEndAff ){
101613        if( sqlite3CompareAffinity(pRight, zEndAff[nEq])==SQLITE_AFF_NONE){
101614          /* Since the comparison is to be performed with no conversions
101615          ** applied to the operands, set the affinity to apply to pRight to
101616          ** SQLITE_AFF_NONE.  */
101617          zEndAff[nEq] = SQLITE_AFF_NONE;
101618        }
101619        if( sqlite3ExprNeedsNoAffinityChange(pRight, zEndAff[nEq]) ){
101620          zEndAff[nEq] = SQLITE_AFF_NONE;
101621        }
101622      }
101623      codeApplyAffinity(pParse, regBase, nEq+1, zEndAff);
101624      nConstraint++;
101625      testcase( pRangeEnd->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
101626    }
101627    sqlite3DbFree(pParse->db, zStartAff);
101628    sqlite3DbFree(pParse->db, zEndAff);
101629
101630    /* Top of the loop body */
101631    pLevel->p2 = sqlite3VdbeCurrentAddr(v);
101632
101633    /* Check if the index cursor is past the end of the range. */
101634    op = aEndOp[(pRangeEnd || nEq) * (1 + bRev)];
101635    testcase( op==OP_Noop );
101636    testcase( op==OP_IdxGE );
101637    testcase( op==OP_IdxLT );
101638    if( op!=OP_Noop ){
101639      sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
101640      sqlite3VdbeChangeP5(v, endEq!=bRev ?1:0);
101641    }
101642
101643    /* If there are inequality constraints, check that the value
101644    ** of the table column that the inequality contrains is not NULL.
101645    ** If it is, jump to the next iteration of the loop.
101646    */
101647    r1 = sqlite3GetTempReg(pParse);
101648    testcase( pLevel->plan.wsFlags & WHERE_BTM_LIMIT );
101649    testcase( pLevel->plan.wsFlags & WHERE_TOP_LIMIT );
101650    if( (pLevel->plan.wsFlags & (WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))!=0 ){
101651      sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, nEq, r1);
101652      sqlite3VdbeAddOp2(v, OP_IsNull, r1, addrCont);
101653    }
101654    sqlite3ReleaseTempReg(pParse, r1);
101655
101656    /* Seek the table cursor, if required */
101657    disableTerm(pLevel, pRangeStart);
101658    disableTerm(pLevel, pRangeEnd);
101659    if( !omitTable ){
101660      iRowidReg = iReleaseReg = sqlite3GetTempReg(pParse);
101661      sqlite3VdbeAddOp2(v, OP_IdxRowid, iIdxCur, iRowidReg);
101662      sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
101663      sqlite3VdbeAddOp2(v, OP_Seek, iCur, iRowidReg);  /* Deferred seek */
101664    }
101665
101666    /* Record the instruction used to terminate the loop. Disable
101667    ** WHERE clause terms made redundant by the index range scan.
101668    */
101669    if( pLevel->plan.wsFlags & WHERE_UNIQUE ){
101670      pLevel->op = OP_Noop;
101671    }else if( bRev ){
101672      pLevel->op = OP_Prev;
101673    }else{
101674      pLevel->op = OP_Next;
101675    }
101676    pLevel->p1 = iIdxCur;
101677  }else
101678
101679#ifndef SQLITE_OMIT_OR_OPTIMIZATION
101680  if( pLevel->plan.wsFlags & WHERE_MULTI_OR ){
101681    /* Case 4:  Two or more separately indexed terms connected by OR
101682    **
101683    ** Example:
101684    **
101685    **   CREATE TABLE t1(a,b,c,d);
101686    **   CREATE INDEX i1 ON t1(a);
101687    **   CREATE INDEX i2 ON t1(b);
101688    **   CREATE INDEX i3 ON t1(c);
101689    **
101690    **   SELECT * FROM t1 WHERE a=5 OR b=7 OR (c=11 AND d=13)
101691    **
101692    ** In the example, there are three indexed terms connected by OR.
101693    ** The top of the loop looks like this:
101694    **
101695    **          Null       1                # Zero the rowset in reg 1
101696    **
101697    ** Then, for each indexed term, the following. The arguments to
101698    ** RowSetTest are such that the rowid of the current row is inserted
101699    ** into the RowSet. If it is already present, control skips the
101700    ** Gosub opcode and jumps straight to the code generated by WhereEnd().
101701    **
101702    **        sqlite3WhereBegin(<term>)
101703    **          RowSetTest                  # Insert rowid into rowset
101704    **          Gosub      2 A
101705    **        sqlite3WhereEnd()
101706    **
101707    ** Following the above, code to terminate the loop. Label A, the target
101708    ** of the Gosub above, jumps to the instruction right after the Goto.
101709    **
101710    **          Null       1                # Zero the rowset in reg 1
101711    **          Goto       B                # The loop is finished.
101712    **
101713    **       A: <loop body>                 # Return data, whatever.
101714    **
101715    **          Return     2                # Jump back to the Gosub
101716    **
101717    **       B: <after the loop>
101718    **
101719    */
101720    WhereClause *pOrWc;    /* The OR-clause broken out into subterms */
101721    SrcList *pOrTab;       /* Shortened table list or OR-clause generation */
101722
101723    int regReturn = ++pParse->nMem;           /* Register used with OP_Gosub */
101724    int regRowset = 0;                        /* Register for RowSet object */
101725    int regRowid = 0;                         /* Register holding rowid */
101726    int iLoopBody = sqlite3VdbeMakeLabel(v);  /* Start of loop body */
101727    int iRetInit;                             /* Address of regReturn init */
101728    int untestedTerms = 0;             /* Some terms not completely tested */
101729    int ii;
101730
101731    pTerm = pLevel->plan.u.pTerm;
101732    assert( pTerm!=0 );
101733    assert( pTerm->eOperator==WO_OR );
101734    assert( (pTerm->wtFlags & TERM_ORINFO)!=0 );
101735    pOrWc = &pTerm->u.pOrInfo->wc;
101736    pLevel->op = OP_Return;
101737    pLevel->p1 = regReturn;
101738
101739    /* Set up a new SrcList ni pOrTab containing the table being scanned
101740    ** by this loop in the a[0] slot and all notReady tables in a[1..] slots.
101741    ** This becomes the SrcList in the recursive call to sqlite3WhereBegin().
101742    */
101743    if( pWInfo->nLevel>1 ){
101744      int nNotReady;                 /* The number of notReady tables */
101745      struct SrcList_item *origSrc;     /* Original list of tables */
101746      nNotReady = pWInfo->nLevel - iLevel - 1;
101747      pOrTab = sqlite3StackAllocRaw(pParse->db,
101748                            sizeof(*pOrTab)+ nNotReady*sizeof(pOrTab->a[0]));
101749      if( pOrTab==0 ) return notReady;
101750      pOrTab->nAlloc = (i16)(nNotReady + 1);
101751      pOrTab->nSrc = pOrTab->nAlloc;
101752      memcpy(pOrTab->a, pTabItem, sizeof(*pTabItem));
101753      origSrc = pWInfo->pTabList->a;
101754      for(k=1; k<=nNotReady; k++){
101755        memcpy(&pOrTab->a[k], &origSrc[pLevel[k].iFrom], sizeof(pOrTab->a[k]));
101756      }
101757    }else{
101758      pOrTab = pWInfo->pTabList;
101759    }
101760
101761    /* Initialize the rowset register to contain NULL. An SQL NULL is
101762    ** equivalent to an empty rowset.
101763    **
101764    ** Also initialize regReturn to contain the address of the instruction
101765    ** immediately following the OP_Return at the bottom of the loop. This
101766    ** is required in a few obscure LEFT JOIN cases where control jumps
101767    ** over the top of the loop into the body of it. In this case the
101768    ** correct response for the end-of-loop code (the OP_Return) is to
101769    ** fall through to the next instruction, just as an OP_Next does if
101770    ** called on an uninitialized cursor.
101771    */
101772    if( (wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
101773      regRowset = ++pParse->nMem;
101774      regRowid = ++pParse->nMem;
101775      sqlite3VdbeAddOp2(v, OP_Null, 0, regRowset);
101776    }
101777    iRetInit = sqlite3VdbeAddOp2(v, OP_Integer, 0, regReturn);
101778
101779    for(ii=0; ii<pOrWc->nTerm; ii++){
101780      WhereTerm *pOrTerm = &pOrWc->a[ii];
101781      if( pOrTerm->leftCursor==iCur || pOrTerm->eOperator==WO_AND ){
101782        WhereInfo *pSubWInfo;          /* Info for single OR-term scan */
101783        /* Loop through table entries that match term pOrTerm. */
101784        pSubWInfo = sqlite3WhereBegin(pParse, pOrTab, pOrTerm->pExpr, 0,
101785                        WHERE_OMIT_OPEN | WHERE_OMIT_CLOSE |
101786                        WHERE_FORCE_TABLE | WHERE_ONETABLE_ONLY);
101787        if( pSubWInfo ){
101788          explainOneScan(
101789              pParse, pOrTab, &pSubWInfo->a[0], iLevel, pLevel->iFrom, 0
101790          );
101791          if( (wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
101792            int iSet = ((ii==pOrWc->nTerm-1)?-1:ii);
101793            int r;
101794            r = sqlite3ExprCodeGetColumn(pParse, pTabItem->pTab, -1, iCur,
101795                                         regRowid);
101796            sqlite3VdbeAddOp4Int(v, OP_RowSetTest, regRowset,
101797                                 sqlite3VdbeCurrentAddr(v)+2, r, iSet);
101798          }
101799          sqlite3VdbeAddOp2(v, OP_Gosub, regReturn, iLoopBody);
101800
101801          /* The pSubWInfo->untestedTerms flag means that this OR term
101802          ** contained one or more AND term from a notReady table.  The
101803          ** terms from the notReady table could not be tested and will
101804          ** need to be tested later.
101805          */
101806          if( pSubWInfo->untestedTerms ) untestedTerms = 1;
101807
101808          /* Finish the loop through table entries that match term pOrTerm. */
101809          sqlite3WhereEnd(pSubWInfo);
101810        }
101811      }
101812    }
101813    sqlite3VdbeChangeP1(v, iRetInit, sqlite3VdbeCurrentAddr(v));
101814    sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->addrBrk);
101815    sqlite3VdbeResolveLabel(v, iLoopBody);
101816
101817    if( pWInfo->nLevel>1 ) sqlite3StackFree(pParse->db, pOrTab);
101818    if( !untestedTerms ) disableTerm(pLevel, pTerm);
101819  }else
101820#endif /* SQLITE_OMIT_OR_OPTIMIZATION */
101821
101822  {
101823    /* Case 5:  There is no usable index.  We must do a complete
101824    **          scan of the entire table.
101825    */
101826    static const u8 aStep[] = { OP_Next, OP_Prev };
101827    static const u8 aStart[] = { OP_Rewind, OP_Last };
101828    assert( bRev==0 || bRev==1 );
101829    assert( omitTable==0 );
101830    pLevel->op = aStep[bRev];
101831    pLevel->p1 = iCur;
101832    pLevel->p2 = 1 + sqlite3VdbeAddOp2(v, aStart[bRev], iCur, addrBrk);
101833    pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
101834  }
101835  notReady &= ~getMask(pWC->pMaskSet, iCur);
101836
101837  /* Insert code to test every subexpression that can be completely
101838  ** computed using the current set of tables.
101839  **
101840  ** IMPLEMENTATION-OF: R-49525-50935 Terms that cannot be satisfied through
101841  ** the use of indices become tests that are evaluated against each row of
101842  ** the relevant input tables.
101843  */
101844  for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){
101845    Expr *pE;
101846    testcase( pTerm->wtFlags & TERM_VIRTUAL ); /* IMP: R-30575-11662 */
101847    testcase( pTerm->wtFlags & TERM_CODED );
101848    if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
101849    if( (pTerm->prereqAll & notReady)!=0 ){
101850      testcase( pWInfo->untestedTerms==0
101851               && (pWInfo->wctrlFlags & WHERE_ONETABLE_ONLY)!=0 );
101852      pWInfo->untestedTerms = 1;
101853      continue;
101854    }
101855    pE = pTerm->pExpr;
101856    assert( pE!=0 );
101857    if( pLevel->iLeftJoin && !ExprHasProperty(pE, EP_FromJoin) ){
101858      continue;
101859    }
101860    sqlite3ExprIfFalse(pParse, pE, addrCont, SQLITE_JUMPIFNULL);
101861    pTerm->wtFlags |= TERM_CODED;
101862  }
101863
101864  /* For a LEFT OUTER JOIN, generate code that will record the fact that
101865  ** at least one row of the right table has matched the left table.
101866  */
101867  if( pLevel->iLeftJoin ){
101868    pLevel->addrFirst = sqlite3VdbeCurrentAddr(v);
101869    sqlite3VdbeAddOp2(v, OP_Integer, 1, pLevel->iLeftJoin);
101870    VdbeComment((v, "record LEFT JOIN hit"));
101871    sqlite3ExprCacheClear(pParse);
101872    for(pTerm=pWC->a, j=0; j<pWC->nTerm; j++, pTerm++){
101873      testcase( pTerm->wtFlags & TERM_VIRTUAL );  /* IMP: R-30575-11662 */
101874      testcase( pTerm->wtFlags & TERM_CODED );
101875      if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
101876      if( (pTerm->prereqAll & notReady)!=0 ){
101877        assert( pWInfo->untestedTerms );
101878        continue;
101879      }
101880      assert( pTerm->pExpr );
101881      sqlite3ExprIfFalse(pParse, pTerm->pExpr, addrCont, SQLITE_JUMPIFNULL);
101882      pTerm->wtFlags |= TERM_CODED;
101883    }
101884  }
101885  sqlite3ReleaseTempReg(pParse, iReleaseReg);
101886
101887  return notReady;
101888}
101889
101890#if defined(SQLITE_TEST)
101891/*
101892** The following variable holds a text description of query plan generated
101893** by the most recent call to sqlite3WhereBegin().  Each call to WhereBegin
101894** overwrites the previous.  This information is used for testing and
101895** analysis only.
101896*/
101897SQLITE_API char sqlite3_query_plan[BMS*2*40];  /* Text of the join */
101898static int nQPlan = 0;              /* Next free slow in _query_plan[] */
101899
101900#endif /* SQLITE_TEST */
101901
101902
101903/*
101904** Free a WhereInfo structure
101905*/
101906static void whereInfoFree(sqlite3 *db, WhereInfo *pWInfo){
101907  if( ALWAYS(pWInfo) ){
101908    int i;
101909    for(i=0; i<pWInfo->nLevel; i++){
101910      sqlite3_index_info *pInfo = pWInfo->a[i].pIdxInfo;
101911      if( pInfo ){
101912        /* assert( pInfo->needToFreeIdxStr==0 || db->mallocFailed ); */
101913        if( pInfo->needToFreeIdxStr ){
101914          sqlite3_free(pInfo->idxStr);
101915        }
101916        sqlite3DbFree(db, pInfo);
101917      }
101918      if( pWInfo->a[i].plan.wsFlags & WHERE_TEMP_INDEX ){
101919        Index *pIdx = pWInfo->a[i].plan.u.pIdx;
101920        if( pIdx ){
101921          sqlite3DbFree(db, pIdx->zColAff);
101922          sqlite3DbFree(db, pIdx);
101923        }
101924      }
101925    }
101926    whereClauseClear(pWInfo->pWC);
101927    sqlite3DbFree(db, pWInfo);
101928  }
101929}
101930
101931
101932/*
101933** Generate the beginning of the loop used for WHERE clause processing.
101934** The return value is a pointer to an opaque structure that contains
101935** information needed to terminate the loop.  Later, the calling routine
101936** should invoke sqlite3WhereEnd() with the return value of this function
101937** in order to complete the WHERE clause processing.
101938**
101939** If an error occurs, this routine returns NULL.
101940**
101941** The basic idea is to do a nested loop, one loop for each table in
101942** the FROM clause of a select.  (INSERT and UPDATE statements are the
101943** same as a SELECT with only a single table in the FROM clause.)  For
101944** example, if the SQL is this:
101945**
101946**       SELECT * FROM t1, t2, t3 WHERE ...;
101947**
101948** Then the code generated is conceptually like the following:
101949**
101950**      foreach row1 in t1 do       \    Code generated
101951**        foreach row2 in t2 do      |-- by sqlite3WhereBegin()
101952**          foreach row3 in t3 do   /
101953**            ...
101954**          end                     \    Code generated
101955**        end                        |-- by sqlite3WhereEnd()
101956**      end                         /
101957**
101958** Note that the loops might not be nested in the order in which they
101959** appear in the FROM clause if a different order is better able to make
101960** use of indices.  Note also that when the IN operator appears in
101961** the WHERE clause, it might result in additional nested loops for
101962** scanning through all values on the right-hand side of the IN.
101963**
101964** There are Btree cursors associated with each table.  t1 uses cursor
101965** number pTabList->a[0].iCursor.  t2 uses the cursor pTabList->a[1].iCursor.
101966** And so forth.  This routine generates code to open those VDBE cursors
101967** and sqlite3WhereEnd() generates the code to close them.
101968**
101969** The code that sqlite3WhereBegin() generates leaves the cursors named
101970** in pTabList pointing at their appropriate entries.  The [...] code
101971** can use OP_Column and OP_Rowid opcodes on these cursors to extract
101972** data from the various tables of the loop.
101973**
101974** If the WHERE clause is empty, the foreach loops must each scan their
101975** entire tables.  Thus a three-way join is an O(N^3) operation.  But if
101976** the tables have indices and there are terms in the WHERE clause that
101977** refer to those indices, a complete table scan can be avoided and the
101978** code will run much faster.  Most of the work of this routine is checking
101979** to see if there are indices that can be used to speed up the loop.
101980**
101981** Terms of the WHERE clause are also used to limit which rows actually
101982** make it to the "..." in the middle of the loop.  After each "foreach",
101983** terms of the WHERE clause that use only terms in that loop and outer
101984** loops are evaluated and if false a jump is made around all subsequent
101985** inner loops (or around the "..." if the test occurs within the inner-
101986** most loop)
101987**
101988** OUTER JOINS
101989**
101990** An outer join of tables t1 and t2 is conceptally coded as follows:
101991**
101992**    foreach row1 in t1 do
101993**      flag = 0
101994**      foreach row2 in t2 do
101995**        start:
101996**          ...
101997**          flag = 1
101998**      end
101999**      if flag==0 then
102000**        move the row2 cursor to a null row
102001**        goto start
102002**      fi
102003**    end
102004**
102005** ORDER BY CLAUSE PROCESSING
102006**
102007** *ppOrderBy is a pointer to the ORDER BY clause of a SELECT statement,
102008** if there is one.  If there is no ORDER BY clause or if this routine
102009** is called from an UPDATE or DELETE statement, then ppOrderBy is NULL.
102010**
102011** If an index can be used so that the natural output order of the table
102012** scan is correct for the ORDER BY clause, then that index is used and
102013** *ppOrderBy is set to NULL.  This is an optimization that prevents an
102014** unnecessary sort of the result set if an index appropriate for the
102015** ORDER BY clause already exists.
102016**
102017** If the where clause loops cannot be arranged to provide the correct
102018** output order, then the *ppOrderBy is unchanged.
102019*/
102020SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(
102021  Parse *pParse,        /* The parser context */
102022  SrcList *pTabList,    /* A list of all tables to be scanned */
102023  Expr *pWhere,         /* The WHERE clause */
102024  ExprList **ppOrderBy, /* An ORDER BY clause, or NULL */
102025  u16 wctrlFlags        /* One of the WHERE_* flags defined in sqliteInt.h */
102026){
102027  int i;                     /* Loop counter */
102028  int nByteWInfo;            /* Num. bytes allocated for WhereInfo struct */
102029  int nTabList;              /* Number of elements in pTabList */
102030  WhereInfo *pWInfo;         /* Will become the return value of this function */
102031  Vdbe *v = pParse->pVdbe;   /* The virtual database engine */
102032  Bitmask notReady;          /* Cursors that are not yet positioned */
102033  WhereMaskSet *pMaskSet;    /* The expression mask set */
102034  WhereClause *pWC;               /* Decomposition of the WHERE clause */
102035  struct SrcList_item *pTabItem;  /* A single entry from pTabList */
102036  WhereLevel *pLevel;             /* A single level in the pWInfo list */
102037  int iFrom;                      /* First unused FROM clause element */
102038  int andFlags;              /* AND-ed combination of all pWC->a[].wtFlags */
102039  sqlite3 *db;               /* Database connection */
102040
102041  /* The number of tables in the FROM clause is limited by the number of
102042  ** bits in a Bitmask
102043  */
102044  testcase( pTabList->nSrc==BMS );
102045  if( pTabList->nSrc>BMS ){
102046    sqlite3ErrorMsg(pParse, "at most %d tables in a join", BMS);
102047    return 0;
102048  }
102049
102050  /* This function normally generates a nested loop for all tables in
102051  ** pTabList.  But if the WHERE_ONETABLE_ONLY flag is set, then we should
102052  ** only generate code for the first table in pTabList and assume that
102053  ** any cursors associated with subsequent tables are uninitialized.
102054  */
102055  nTabList = (wctrlFlags & WHERE_ONETABLE_ONLY) ? 1 : pTabList->nSrc;
102056
102057  /* Allocate and initialize the WhereInfo structure that will become the
102058  ** return value. A single allocation is used to store the WhereInfo
102059  ** struct, the contents of WhereInfo.a[], the WhereClause structure
102060  ** and the WhereMaskSet structure. Since WhereClause contains an 8-byte
102061  ** field (type Bitmask) it must be aligned on an 8-byte boundary on
102062  ** some architectures. Hence the ROUND8() below.
102063  */
102064  db = pParse->db;
102065  nByteWInfo = ROUND8(sizeof(WhereInfo)+(nTabList-1)*sizeof(WhereLevel));
102066  pWInfo = sqlite3DbMallocZero(db,
102067      nByteWInfo +
102068      sizeof(WhereClause) +
102069      sizeof(WhereMaskSet)
102070  );
102071  if( db->mallocFailed ){
102072    sqlite3DbFree(db, pWInfo);
102073    pWInfo = 0;
102074    goto whereBeginError;
102075  }
102076  pWInfo->nLevel = nTabList;
102077  pWInfo->pParse = pParse;
102078  pWInfo->pTabList = pTabList;
102079  pWInfo->iBreak = sqlite3VdbeMakeLabel(v);
102080  pWInfo->pWC = pWC = (WhereClause *)&((u8 *)pWInfo)[nByteWInfo];
102081  pWInfo->wctrlFlags = wctrlFlags;
102082  pWInfo->savedNQueryLoop = pParse->nQueryLoop;
102083  pMaskSet = (WhereMaskSet*)&pWC[1];
102084
102085  /* Split the WHERE clause into separate subexpressions where each
102086  ** subexpression is separated by an AND operator.
102087  */
102088  initMaskSet(pMaskSet);
102089  whereClauseInit(pWC, pParse, pMaskSet);
102090  sqlite3ExprCodeConstants(pParse, pWhere);
102091  whereSplit(pWC, pWhere, TK_AND);   /* IMP: R-15842-53296 */
102092
102093  /* Special case: a WHERE clause that is constant.  Evaluate the
102094  ** expression and either jump over all of the code or fall thru.
102095  */
102096  if( pWhere && (nTabList==0 || sqlite3ExprIsConstantNotJoin(pWhere)) ){
102097    sqlite3ExprIfFalse(pParse, pWhere, pWInfo->iBreak, SQLITE_JUMPIFNULL);
102098    pWhere = 0;
102099  }
102100
102101  /* Assign a bit from the bitmask to every term in the FROM clause.
102102  **
102103  ** When assigning bitmask values to FROM clause cursors, it must be
102104  ** the case that if X is the bitmask for the N-th FROM clause term then
102105  ** the bitmask for all FROM clause terms to the left of the N-th term
102106  ** is (X-1).   An expression from the ON clause of a LEFT JOIN can use
102107  ** its Expr.iRightJoinTable value to find the bitmask of the right table
102108  ** of the join.  Subtracting one from the right table bitmask gives a
102109  ** bitmask for all tables to the left of the join.  Knowing the bitmask
102110  ** for all tables to the left of a left join is important.  Ticket #3015.
102111  **
102112  ** Configure the WhereClause.vmask variable so that bits that correspond
102113  ** to virtual table cursors are set. This is used to selectively disable
102114  ** the OR-to-IN transformation in exprAnalyzeOrTerm(). It is not helpful
102115  ** with virtual tables.
102116  **
102117  ** Note that bitmasks are created for all pTabList->nSrc tables in
102118  ** pTabList, not just the first nTabList tables.  nTabList is normally
102119  ** equal to pTabList->nSrc but might be shortened to 1 if the
102120  ** WHERE_ONETABLE_ONLY flag is set.
102121  */
102122  assert( pWC->vmask==0 && pMaskSet->n==0 );
102123  for(i=0; i<pTabList->nSrc; i++){
102124    createMask(pMaskSet, pTabList->a[i].iCursor);
102125#ifndef SQLITE_OMIT_VIRTUALTABLE
102126    if( ALWAYS(pTabList->a[i].pTab) && IsVirtual(pTabList->a[i].pTab) ){
102127      pWC->vmask |= ((Bitmask)1 << i);
102128    }
102129#endif
102130  }
102131#ifndef NDEBUG
102132  {
102133    Bitmask toTheLeft = 0;
102134    for(i=0; i<pTabList->nSrc; i++){
102135      Bitmask m = getMask(pMaskSet, pTabList->a[i].iCursor);
102136      assert( (m-1)==toTheLeft );
102137      toTheLeft |= m;
102138    }
102139  }
102140#endif
102141
102142  /* Analyze all of the subexpressions.  Note that exprAnalyze() might
102143  ** add new virtual terms onto the end of the WHERE clause.  We do not
102144  ** want to analyze these virtual terms, so start analyzing at the end
102145  ** and work forward so that the added virtual terms are never processed.
102146  */
102147  exprAnalyzeAll(pTabList, pWC);
102148  if( db->mallocFailed ){
102149    goto whereBeginError;
102150  }
102151
102152  /* Chose the best index to use for each table in the FROM clause.
102153  **
102154  ** This loop fills in the following fields:
102155  **
102156  **   pWInfo->a[].pIdx      The index to use for this level of the loop.
102157  **   pWInfo->a[].wsFlags   WHERE_xxx flags associated with pIdx
102158  **   pWInfo->a[].nEq       The number of == and IN constraints
102159  **   pWInfo->a[].iFrom     Which term of the FROM clause is being coded
102160  **   pWInfo->a[].iTabCur   The VDBE cursor for the database table
102161  **   pWInfo->a[].iIdxCur   The VDBE cursor for the index
102162  **   pWInfo->a[].pTerm     When wsFlags==WO_OR, the OR-clause term
102163  **
102164  ** This loop also figures out the nesting order of tables in the FROM
102165  ** clause.
102166  */
102167  notReady = ~(Bitmask)0;
102168  andFlags = ~0;
102169  WHERETRACE(("*** Optimizer Start ***\n"));
102170  for(i=iFrom=0, pLevel=pWInfo->a; i<nTabList; i++, pLevel++){
102171    WhereCost bestPlan;         /* Most efficient plan seen so far */
102172    Index *pIdx;                /* Index for FROM table at pTabItem */
102173    int j;                      /* For looping over FROM tables */
102174    int bestJ = -1;             /* The value of j */
102175    Bitmask m;                  /* Bitmask value for j or bestJ */
102176    int isOptimal;              /* Iterator for optimal/non-optimal search */
102177    int nUnconstrained;         /* Number tables without INDEXED BY */
102178    Bitmask notIndexed;         /* Mask of tables that cannot use an index */
102179
102180    memset(&bestPlan, 0, sizeof(bestPlan));
102181    bestPlan.rCost = SQLITE_BIG_DBL;
102182    WHERETRACE(("*** Begin search for loop %d ***\n", i));
102183
102184    /* Loop through the remaining entries in the FROM clause to find the
102185    ** next nested loop. The loop tests all FROM clause entries
102186    ** either once or twice.
102187    **
102188    ** The first test is always performed if there are two or more entries
102189    ** remaining and never performed if there is only one FROM clause entry
102190    ** to choose from.  The first test looks for an "optimal" scan.  In
102191    ** this context an optimal scan is one that uses the same strategy
102192    ** for the given FROM clause entry as would be selected if the entry
102193    ** were used as the innermost nested loop.  In other words, a table
102194    ** is chosen such that the cost of running that table cannot be reduced
102195    ** by waiting for other tables to run first.  This "optimal" test works
102196    ** by first assuming that the FROM clause is on the inner loop and finding
102197    ** its query plan, then checking to see if that query plan uses any
102198    ** other FROM clause terms that are notReady.  If no notReady terms are
102199    ** used then the "optimal" query plan works.
102200    **
102201    ** Note that the WhereCost.nRow parameter for an optimal scan might
102202    ** not be as small as it would be if the table really were the innermost
102203    ** join.  The nRow value can be reduced by WHERE clause constraints
102204    ** that do not use indices.  But this nRow reduction only happens if the
102205    ** table really is the innermost join.
102206    **
102207    ** The second loop iteration is only performed if no optimal scan
102208    ** strategies were found by the first iteration. This second iteration
102209    ** is used to search for the lowest cost scan overall.
102210    **
102211    ** Previous versions of SQLite performed only the second iteration -
102212    ** the next outermost loop was always that with the lowest overall
102213    ** cost. However, this meant that SQLite could select the wrong plan
102214    ** for scripts such as the following:
102215    **
102216    **   CREATE TABLE t1(a, b);
102217    **   CREATE TABLE t2(c, d);
102218    **   SELECT * FROM t2, t1 WHERE t2.rowid = t1.a;
102219    **
102220    ** The best strategy is to iterate through table t1 first. However it
102221    ** is not possible to determine this with a simple greedy algorithm.
102222    ** Since the cost of a linear scan through table t2 is the same
102223    ** as the cost of a linear scan through table t1, a simple greedy
102224    ** algorithm may choose to use t2 for the outer loop, which is a much
102225    ** costlier approach.
102226    */
102227    nUnconstrained = 0;
102228    notIndexed = 0;
102229    for(isOptimal=(iFrom<nTabList-1); isOptimal>=0 && bestJ<0; isOptimal--){
102230      Bitmask mask;             /* Mask of tables not yet ready */
102231      for(j=iFrom, pTabItem=&pTabList->a[j]; j<nTabList; j++, pTabItem++){
102232        int doNotReorder;    /* True if this table should not be reordered */
102233        WhereCost sCost;     /* Cost information from best[Virtual]Index() */
102234        ExprList *pOrderBy;  /* ORDER BY clause for index to optimize */
102235
102236        doNotReorder =  (pTabItem->jointype & (JT_LEFT|JT_CROSS))!=0;
102237        if( j!=iFrom && doNotReorder ) break;
102238        m = getMask(pMaskSet, pTabItem->iCursor);
102239        if( (m & notReady)==0 ){
102240          if( j==iFrom ) iFrom++;
102241          continue;
102242        }
102243        mask = (isOptimal ? m : notReady);
102244        pOrderBy = ((i==0 && ppOrderBy )?*ppOrderBy:0);
102245        if( pTabItem->pIndex==0 ) nUnconstrained++;
102246
102247        WHERETRACE(("=== trying table %d with isOptimal=%d ===\n",
102248                    j, isOptimal));
102249        assert( pTabItem->pTab );
102250#ifndef SQLITE_OMIT_VIRTUALTABLE
102251        if( IsVirtual(pTabItem->pTab) ){
102252          sqlite3_index_info **pp = &pWInfo->a[j].pIdxInfo;
102253          bestVirtualIndex(pParse, pWC, pTabItem, mask, notReady, pOrderBy,
102254                           &sCost, pp);
102255        }else
102256#endif
102257        {
102258          bestBtreeIndex(pParse, pWC, pTabItem, mask, notReady, pOrderBy,
102259                         &sCost);
102260        }
102261        assert( isOptimal || (sCost.used&notReady)==0 );
102262
102263        /* If an INDEXED BY clause is present, then the plan must use that
102264        ** index if it uses any index at all */
102265        assert( pTabItem->pIndex==0
102266                  || (sCost.plan.wsFlags & WHERE_NOT_FULLSCAN)==0
102267                  || sCost.plan.u.pIdx==pTabItem->pIndex );
102268
102269        if( isOptimal && (sCost.plan.wsFlags & WHERE_NOT_FULLSCAN)==0 ){
102270          notIndexed |= m;
102271        }
102272
102273        /* Conditions under which this table becomes the best so far:
102274        **
102275        **   (1) The table must not depend on other tables that have not
102276        **       yet run.
102277        **
102278        **   (2) A full-table-scan plan cannot supercede indexed plan unless
102279        **       the full-table-scan is an "optimal" plan as defined above.
102280        **
102281        **   (3) All tables have an INDEXED BY clause or this table lacks an
102282        **       INDEXED BY clause or this table uses the specific
102283        **       index specified by its INDEXED BY clause.  This rule ensures
102284        **       that a best-so-far is always selected even if an impossible
102285        **       combination of INDEXED BY clauses are given.  The error
102286        **       will be detected and relayed back to the application later.
102287        **       The NEVER() comes about because rule (2) above prevents
102288        **       An indexable full-table-scan from reaching rule (3).
102289        **
102290        **   (4) The plan cost must be lower than prior plans or else the
102291        **       cost must be the same and the number of rows must be lower.
102292        */
102293        if( (sCost.used&notReady)==0                       /* (1) */
102294            && (bestJ<0 || (notIndexed&m)!=0               /* (2) */
102295                || (bestPlan.plan.wsFlags & WHERE_NOT_FULLSCAN)==0
102296                || (sCost.plan.wsFlags & WHERE_NOT_FULLSCAN)!=0)
102297            && (nUnconstrained==0 || pTabItem->pIndex==0   /* (3) */
102298                || NEVER((sCost.plan.wsFlags & WHERE_NOT_FULLSCAN)!=0))
102299            && (bestJ<0 || sCost.rCost<bestPlan.rCost      /* (4) */
102300                || (sCost.rCost<=bestPlan.rCost
102301                 && sCost.plan.nRow<bestPlan.plan.nRow))
102302        ){
102303          WHERETRACE(("=== table %d is best so far"
102304                      " with cost=%g and nRow=%g\n",
102305                      j, sCost.rCost, sCost.plan.nRow));
102306          bestPlan = sCost;
102307          bestJ = j;
102308        }
102309        if( doNotReorder ) break;
102310      }
102311    }
102312    assert( bestJ>=0 );
102313    assert( notReady & getMask(pMaskSet, pTabList->a[bestJ].iCursor) );
102314    WHERETRACE(("*** Optimizer selects table %d for loop %d"
102315                " with cost=%g and nRow=%g\n",
102316                bestJ, pLevel-pWInfo->a, bestPlan.rCost, bestPlan.plan.nRow));
102317    if( (bestPlan.plan.wsFlags & WHERE_ORDERBY)!=0 ){
102318      *ppOrderBy = 0;
102319    }
102320    andFlags &= bestPlan.plan.wsFlags;
102321    pLevel->plan = bestPlan.plan;
102322    testcase( bestPlan.plan.wsFlags & WHERE_INDEXED );
102323    testcase( bestPlan.plan.wsFlags & WHERE_TEMP_INDEX );
102324    if( bestPlan.plan.wsFlags & (WHERE_INDEXED|WHERE_TEMP_INDEX) ){
102325      pLevel->iIdxCur = pParse->nTab++;
102326    }else{
102327      pLevel->iIdxCur = -1;
102328    }
102329    notReady &= ~getMask(pMaskSet, pTabList->a[bestJ].iCursor);
102330    pLevel->iFrom = (u8)bestJ;
102331    if( bestPlan.plan.nRow>=(double)1 ){
102332      pParse->nQueryLoop *= bestPlan.plan.nRow;
102333    }
102334
102335    /* Check that if the table scanned by this loop iteration had an
102336    ** INDEXED BY clause attached to it, that the named index is being
102337    ** used for the scan. If not, then query compilation has failed.
102338    ** Return an error.
102339    */
102340    pIdx = pTabList->a[bestJ].pIndex;
102341    if( pIdx ){
102342      if( (bestPlan.plan.wsFlags & WHERE_INDEXED)==0 ){
102343        sqlite3ErrorMsg(pParse, "cannot use index: %s", pIdx->zName);
102344        goto whereBeginError;
102345      }else{
102346        /* If an INDEXED BY clause is used, the bestIndex() function is
102347        ** guaranteed to find the index specified in the INDEXED BY clause
102348        ** if it find an index at all. */
102349        assert( bestPlan.plan.u.pIdx==pIdx );
102350      }
102351    }
102352  }
102353  WHERETRACE(("*** Optimizer Finished ***\n"));
102354  if( pParse->nErr || db->mallocFailed ){
102355    goto whereBeginError;
102356  }
102357
102358  /* If the total query only selects a single row, then the ORDER BY
102359  ** clause is irrelevant.
102360  */
102361  if( (andFlags & WHERE_UNIQUE)!=0 && ppOrderBy ){
102362    *ppOrderBy = 0;
102363  }
102364
102365  /* If the caller is an UPDATE or DELETE statement that is requesting
102366  ** to use a one-pass algorithm, determine if this is appropriate.
102367  ** The one-pass algorithm only works if the WHERE clause constraints
102368  ** the statement to update a single row.
102369  */
102370  assert( (wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || pWInfo->nLevel==1 );
102371  if( (wctrlFlags & WHERE_ONEPASS_DESIRED)!=0 && (andFlags & WHERE_UNIQUE)!=0 ){
102372    pWInfo->okOnePass = 1;
102373    pWInfo->a[0].plan.wsFlags &= ~WHERE_IDX_ONLY;
102374  }
102375
102376  /* Open all tables in the pTabList and any indices selected for
102377  ** searching those tables.
102378  */
102379  sqlite3CodeVerifySchema(pParse, -1); /* Insert the cookie verifier Goto */
102380  notReady = ~(Bitmask)0;
102381  pWInfo->nRowOut = (double)1;
102382  for(i=0, pLevel=pWInfo->a; i<nTabList; i++, pLevel++){
102383    Table *pTab;     /* Table to open */
102384    int iDb;         /* Index of database containing table/index */
102385
102386    pTabItem = &pTabList->a[pLevel->iFrom];
102387    pTab = pTabItem->pTab;
102388    pLevel->iTabCur = pTabItem->iCursor;
102389    pWInfo->nRowOut *= pLevel->plan.nRow;
102390    iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
102391    if( (pTab->tabFlags & TF_Ephemeral)!=0 || pTab->pSelect ){
102392      /* Do nothing */
102393    }else
102394#ifndef SQLITE_OMIT_VIRTUALTABLE
102395    if( (pLevel->plan.wsFlags & WHERE_VIRTUALTABLE)!=0 ){
102396      const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
102397      int iCur = pTabItem->iCursor;
102398      sqlite3VdbeAddOp4(v, OP_VOpen, iCur, 0, 0, pVTab, P4_VTAB);
102399    }else
102400#endif
102401    if( (pLevel->plan.wsFlags & WHERE_IDX_ONLY)==0
102402         && (wctrlFlags & WHERE_OMIT_OPEN)==0 ){
102403      int op = pWInfo->okOnePass ? OP_OpenWrite : OP_OpenRead;
102404      sqlite3OpenTable(pParse, pTabItem->iCursor, iDb, pTab, op);
102405      testcase( pTab->nCol==BMS-1 );
102406      testcase( pTab->nCol==BMS );
102407      if( !pWInfo->okOnePass && pTab->nCol<BMS ){
102408        Bitmask b = pTabItem->colUsed;
102409        int n = 0;
102410        for(; b; b=b>>1, n++){}
102411        sqlite3VdbeChangeP4(v, sqlite3VdbeCurrentAddr(v)-1,
102412                            SQLITE_INT_TO_PTR(n), P4_INT32);
102413        assert( n<=pTab->nCol );
102414      }
102415    }else{
102416      sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
102417    }
102418#ifndef SQLITE_OMIT_AUTOMATIC_INDEX
102419    if( (pLevel->plan.wsFlags & WHERE_TEMP_INDEX)!=0 ){
102420      constructAutomaticIndex(pParse, pWC, pTabItem, notReady, pLevel);
102421    }else
102422#endif
102423    if( (pLevel->plan.wsFlags & WHERE_INDEXED)!=0 ){
102424      Index *pIx = pLevel->plan.u.pIdx;
102425      KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIx);
102426      int iIdxCur = pLevel->iIdxCur;
102427      assert( pIx->pSchema==pTab->pSchema );
102428      assert( iIdxCur>=0 );
102429      sqlite3VdbeAddOp4(v, OP_OpenRead, iIdxCur, pIx->tnum, iDb,
102430                        (char*)pKey, P4_KEYINFO_HANDOFF);
102431      VdbeComment((v, "%s", pIx->zName));
102432    }
102433    sqlite3CodeVerifySchema(pParse, iDb);
102434    notReady &= ~getMask(pWC->pMaskSet, pTabItem->iCursor);
102435  }
102436  pWInfo->iTop = sqlite3VdbeCurrentAddr(v);
102437  if( db->mallocFailed ) goto whereBeginError;
102438
102439  /* Generate the code to do the search.  Each iteration of the for
102440  ** loop below generates code for a single nested loop of the VM
102441  ** program.
102442  */
102443  notReady = ~(Bitmask)0;
102444  for(i=0; i<nTabList; i++){
102445    pLevel = &pWInfo->a[i];
102446    explainOneScan(pParse, pTabList, pLevel, i, pLevel->iFrom, wctrlFlags);
102447    notReady = codeOneLoopStart(pWInfo, i, wctrlFlags, notReady);
102448    pWInfo->iContinue = pLevel->addrCont;
102449  }
102450
102451#ifdef SQLITE_TEST  /* For testing and debugging use only */
102452  /* Record in the query plan information about the current table
102453  ** and the index used to access it (if any).  If the table itself
102454  ** is not used, its name is just '{}'.  If no index is used
102455  ** the index is listed as "{}".  If the primary key is used the
102456  ** index name is '*'.
102457  */
102458  for(i=0; i<nTabList; i++){
102459    char *z;
102460    int n;
102461    pLevel = &pWInfo->a[i];
102462    pTabItem = &pTabList->a[pLevel->iFrom];
102463    z = pTabItem->zAlias;
102464    if( z==0 ) z = pTabItem->pTab->zName;
102465    n = sqlite3Strlen30(z);
102466    if( n+nQPlan < sizeof(sqlite3_query_plan)-10 ){
102467      if( pLevel->plan.wsFlags & WHERE_IDX_ONLY ){
102468        memcpy(&sqlite3_query_plan[nQPlan], "{}", 2);
102469        nQPlan += 2;
102470      }else{
102471        memcpy(&sqlite3_query_plan[nQPlan], z, n);
102472        nQPlan += n;
102473      }
102474      sqlite3_query_plan[nQPlan++] = ' ';
102475    }
102476    testcase( pLevel->plan.wsFlags & WHERE_ROWID_EQ );
102477    testcase( pLevel->plan.wsFlags & WHERE_ROWID_RANGE );
102478    if( pLevel->plan.wsFlags & (WHERE_ROWID_EQ|WHERE_ROWID_RANGE) ){
102479      memcpy(&sqlite3_query_plan[nQPlan], "* ", 2);
102480      nQPlan += 2;
102481    }else if( (pLevel->plan.wsFlags & WHERE_INDEXED)!=0 ){
102482      n = sqlite3Strlen30(pLevel->plan.u.pIdx->zName);
102483      if( n+nQPlan < sizeof(sqlite3_query_plan)-2 ){
102484        memcpy(&sqlite3_query_plan[nQPlan], pLevel->plan.u.pIdx->zName, n);
102485        nQPlan += n;
102486        sqlite3_query_plan[nQPlan++] = ' ';
102487      }
102488    }else{
102489      memcpy(&sqlite3_query_plan[nQPlan], "{} ", 3);
102490      nQPlan += 3;
102491    }
102492  }
102493  while( nQPlan>0 && sqlite3_query_plan[nQPlan-1]==' ' ){
102494    sqlite3_query_plan[--nQPlan] = 0;
102495  }
102496  sqlite3_query_plan[nQPlan] = 0;
102497  nQPlan = 0;
102498#endif /* SQLITE_TEST // Testing and debugging use only */
102499
102500  /* Record the continuation address in the WhereInfo structure.  Then
102501  ** clean up and return.
102502  */
102503  return pWInfo;
102504
102505  /* Jump here if malloc fails */
102506whereBeginError:
102507  if( pWInfo ){
102508    pParse->nQueryLoop = pWInfo->savedNQueryLoop;
102509    whereInfoFree(db, pWInfo);
102510  }
102511  return 0;
102512}
102513
102514/*
102515** Generate the end of the WHERE loop.  See comments on
102516** sqlite3WhereBegin() for additional information.
102517*/
102518SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo *pWInfo){
102519  Parse *pParse = pWInfo->pParse;
102520  Vdbe *v = pParse->pVdbe;
102521  int i;
102522  WhereLevel *pLevel;
102523  SrcList *pTabList = pWInfo->pTabList;
102524  sqlite3 *db = pParse->db;
102525
102526  /* Generate loop termination code.
102527  */
102528  sqlite3ExprCacheClear(pParse);
102529  for(i=pWInfo->nLevel-1; i>=0; i--){
102530    pLevel = &pWInfo->a[i];
102531    sqlite3VdbeResolveLabel(v, pLevel->addrCont);
102532    if( pLevel->op!=OP_Noop ){
102533      sqlite3VdbeAddOp2(v, pLevel->op, pLevel->p1, pLevel->p2);
102534      sqlite3VdbeChangeP5(v, pLevel->p5);
102535    }
102536    if( pLevel->plan.wsFlags & WHERE_IN_ABLE && pLevel->u.in.nIn>0 ){
102537      struct InLoop *pIn;
102538      int j;
102539      sqlite3VdbeResolveLabel(v, pLevel->addrNxt);
102540      for(j=pLevel->u.in.nIn, pIn=&pLevel->u.in.aInLoop[j-1]; j>0; j--, pIn--){
102541        sqlite3VdbeJumpHere(v, pIn->addrInTop+1);
102542        sqlite3VdbeAddOp2(v, OP_Next, pIn->iCur, pIn->addrInTop);
102543        sqlite3VdbeJumpHere(v, pIn->addrInTop-1);
102544      }
102545      sqlite3DbFree(db, pLevel->u.in.aInLoop);
102546    }
102547    sqlite3VdbeResolveLabel(v, pLevel->addrBrk);
102548    if( pLevel->iLeftJoin ){
102549      int addr;
102550      addr = sqlite3VdbeAddOp1(v, OP_IfPos, pLevel->iLeftJoin);
102551      assert( (pLevel->plan.wsFlags & WHERE_IDX_ONLY)==0
102552           || (pLevel->plan.wsFlags & WHERE_INDEXED)!=0 );
102553      if( (pLevel->plan.wsFlags & WHERE_IDX_ONLY)==0 ){
102554        sqlite3VdbeAddOp1(v, OP_NullRow, pTabList->a[i].iCursor);
102555      }
102556      if( pLevel->iIdxCur>=0 ){
102557        sqlite3VdbeAddOp1(v, OP_NullRow, pLevel->iIdxCur);
102558      }
102559      if( pLevel->op==OP_Return ){
102560        sqlite3VdbeAddOp2(v, OP_Gosub, pLevel->p1, pLevel->addrFirst);
102561      }else{
102562        sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->addrFirst);
102563      }
102564      sqlite3VdbeJumpHere(v, addr);
102565    }
102566  }
102567
102568  /* The "break" point is here, just past the end of the outer loop.
102569  ** Set it.
102570  */
102571  sqlite3VdbeResolveLabel(v, pWInfo->iBreak);
102572
102573  /* Close all of the cursors that were opened by sqlite3WhereBegin.
102574  */
102575  assert( pWInfo->nLevel==1 || pWInfo->nLevel==pTabList->nSrc );
102576  for(i=0, pLevel=pWInfo->a; i<pWInfo->nLevel; i++, pLevel++){
102577    struct SrcList_item *pTabItem = &pTabList->a[pLevel->iFrom];
102578    Table *pTab = pTabItem->pTab;
102579    assert( pTab!=0 );
102580    if( (pTab->tabFlags & TF_Ephemeral)==0
102581     && pTab->pSelect==0
102582     && (pWInfo->wctrlFlags & WHERE_OMIT_CLOSE)==0
102583    ){
102584      int ws = pLevel->plan.wsFlags;
102585      if( !pWInfo->okOnePass && (ws & WHERE_IDX_ONLY)==0 ){
102586        sqlite3VdbeAddOp1(v, OP_Close, pTabItem->iCursor);
102587      }
102588      if( (ws & WHERE_INDEXED)!=0 && (ws & WHERE_TEMP_INDEX)==0 ){
102589        sqlite3VdbeAddOp1(v, OP_Close, pLevel->iIdxCur);
102590      }
102591    }
102592
102593    /* If this scan uses an index, make code substitutions to read data
102594    ** from the index in preference to the table. Sometimes, this means
102595    ** the table need never be read from. This is a performance boost,
102596    ** as the vdbe level waits until the table is read before actually
102597    ** seeking the table cursor to the record corresponding to the current
102598    ** position in the index.
102599    **
102600    ** Calls to the code generator in between sqlite3WhereBegin and
102601    ** sqlite3WhereEnd will have created code that references the table
102602    ** directly.  This loop scans all that code looking for opcodes
102603    ** that reference the table and converts them into opcodes that
102604    ** reference the index.
102605    */
102606    if( (pLevel->plan.wsFlags & WHERE_INDEXED)!=0 && !db->mallocFailed){
102607      int k, j, last;
102608      VdbeOp *pOp;
102609      Index *pIdx = pLevel->plan.u.pIdx;
102610
102611      assert( pIdx!=0 );
102612      pOp = sqlite3VdbeGetOp(v, pWInfo->iTop);
102613      last = sqlite3VdbeCurrentAddr(v);
102614      for(k=pWInfo->iTop; k<last; k++, pOp++){
102615        if( pOp->p1!=pLevel->iTabCur ) continue;
102616        if( pOp->opcode==OP_Column ){
102617          for(j=0; j<pIdx->nColumn; j++){
102618            if( pOp->p2==pIdx->aiColumn[j] ){
102619              pOp->p2 = j;
102620              pOp->p1 = pLevel->iIdxCur;
102621              break;
102622            }
102623          }
102624          assert( (pLevel->plan.wsFlags & WHERE_IDX_ONLY)==0
102625               || j<pIdx->nColumn );
102626        }else if( pOp->opcode==OP_Rowid ){
102627          pOp->p1 = pLevel->iIdxCur;
102628          pOp->opcode = OP_IdxRowid;
102629        }
102630      }
102631    }
102632  }
102633
102634  /* Final cleanup
102635  */
102636  pParse->nQueryLoop = pWInfo->savedNQueryLoop;
102637  whereInfoFree(db, pWInfo);
102638  return;
102639}
102640
102641/************** End of where.c ***********************************************/
102642/************** Begin file parse.c *******************************************/
102643/* Driver template for the LEMON parser generator.
102644** The author disclaims copyright to this source code.
102645**
102646** This version of "lempar.c" is modified, slightly, for use by SQLite.
102647** The only modifications are the addition of a couple of NEVER()
102648** macros to disable tests that are needed in the case of a general
102649** LALR(1) grammar but which are always false in the
102650** specific grammar used by SQLite.
102651*/
102652/* First off, code is included that follows the "include" declaration
102653** in the input grammar file. */
102654
102655
102656/*
102657** Disable all error recovery processing in the parser push-down
102658** automaton.
102659*/
102660#define YYNOERRORRECOVERY 1
102661
102662/*
102663** Make yytestcase() the same as testcase()
102664*/
102665#define yytestcase(X) testcase(X)
102666
102667/*
102668** An instance of this structure holds information about the
102669** LIMIT clause of a SELECT statement.
102670*/
102671struct LimitVal {
102672  Expr *pLimit;    /* The LIMIT expression.  NULL if there is no limit */
102673  Expr *pOffset;   /* The OFFSET expression.  NULL if there is none */
102674};
102675
102676/*
102677** An instance of this structure is used to store the LIKE,
102678** GLOB, NOT LIKE, and NOT GLOB operators.
102679*/
102680struct LikeOp {
102681  Token eOperator;  /* "like" or "glob" or "regexp" */
102682  int not;         /* True if the NOT keyword is present */
102683};
102684
102685/*
102686** An instance of the following structure describes the event of a
102687** TRIGGER.  "a" is the event type, one of TK_UPDATE, TK_INSERT,
102688** TK_DELETE, or TK_INSTEAD.  If the event is of the form
102689**
102690**      UPDATE ON (a,b,c)
102691**
102692** Then the "b" IdList records the list "a,b,c".
102693*/
102694struct TrigEvent { int a; IdList * b; };
102695
102696/*
102697** An instance of this structure holds the ATTACH key and the key type.
102698*/
102699struct AttachKey { int type;  Token key; };
102700
102701
102702  /* This is a utility routine used to set the ExprSpan.zStart and
102703  ** ExprSpan.zEnd values of pOut so that the span covers the complete
102704  ** range of text beginning with pStart and going to the end of pEnd.
102705  */
102706  static void spanSet(ExprSpan *pOut, Token *pStart, Token *pEnd){
102707    pOut->zStart = pStart->z;
102708    pOut->zEnd = &pEnd->z[pEnd->n];
102709  }
102710
102711  /* Construct a new Expr object from a single identifier.  Use the
102712  ** new Expr to populate pOut.  Set the span of pOut to be the identifier
102713  ** that created the expression.
102714  */
102715  static void spanExpr(ExprSpan *pOut, Parse *pParse, int op, Token *pValue){
102716    pOut->pExpr = sqlite3PExpr(pParse, op, 0, 0, pValue);
102717    pOut->zStart = pValue->z;
102718    pOut->zEnd = &pValue->z[pValue->n];
102719  }
102720
102721  /* This routine constructs a binary expression node out of two ExprSpan
102722  ** objects and uses the result to populate a new ExprSpan object.
102723  */
102724  static void spanBinaryExpr(
102725    ExprSpan *pOut,     /* Write the result here */
102726    Parse *pParse,      /* The parsing context.  Errors accumulate here */
102727    int op,             /* The binary operation */
102728    ExprSpan *pLeft,    /* The left operand */
102729    ExprSpan *pRight    /* The right operand */
102730  ){
102731    pOut->pExpr = sqlite3PExpr(pParse, op, pLeft->pExpr, pRight->pExpr, 0);
102732    pOut->zStart = pLeft->zStart;
102733    pOut->zEnd = pRight->zEnd;
102734  }
102735
102736  /* Construct an expression node for a unary postfix operator
102737  */
102738  static void spanUnaryPostfix(
102739    ExprSpan *pOut,        /* Write the new expression node here */
102740    Parse *pParse,         /* Parsing context to record errors */
102741    int op,                /* The operator */
102742    ExprSpan *pOperand,    /* The operand */
102743    Token *pPostOp         /* The operand token for setting the span */
102744  ){
102745    pOut->pExpr = sqlite3PExpr(pParse, op, pOperand->pExpr, 0, 0);
102746    pOut->zStart = pOperand->zStart;
102747    pOut->zEnd = &pPostOp->z[pPostOp->n];
102748  }
102749
102750  /* A routine to convert a binary TK_IS or TK_ISNOT expression into a
102751  ** unary TK_ISNULL or TK_NOTNULL expression. */
102752  static void binaryToUnaryIfNull(Parse *pParse, Expr *pY, Expr *pA, int op){
102753    sqlite3 *db = pParse->db;
102754    if( db->mallocFailed==0 && pY->op==TK_NULL ){
102755      pA->op = (u8)op;
102756      sqlite3ExprDelete(db, pA->pRight);
102757      pA->pRight = 0;
102758    }
102759  }
102760
102761  /* Construct an expression node for a unary prefix operator
102762  */
102763  static void spanUnaryPrefix(
102764    ExprSpan *pOut,        /* Write the new expression node here */
102765    Parse *pParse,         /* Parsing context to record errors */
102766    int op,                /* The operator */
102767    ExprSpan *pOperand,    /* The operand */
102768    Token *pPreOp         /* The operand token for setting the span */
102769  ){
102770    pOut->pExpr = sqlite3PExpr(pParse, op, pOperand->pExpr, 0, 0);
102771    pOut->zStart = pPreOp->z;
102772    pOut->zEnd = pOperand->zEnd;
102773  }
102774/* Next is all token values, in a form suitable for use by makeheaders.
102775** This section will be null unless lemon is run with the -m switch.
102776*/
102777/*
102778** These constants (all generated automatically by the parser generator)
102779** specify the various kinds of tokens (terminals) that the parser
102780** understands.
102781**
102782** Each symbol here is a terminal symbol in the grammar.
102783*/
102784/* Make sure the INTERFACE macro is defined.
102785*/
102786#ifndef INTERFACE
102787# define INTERFACE 1
102788#endif
102789/* The next thing included is series of defines which control
102790** various aspects of the generated parser.
102791**    YYCODETYPE         is the data type used for storing terminal
102792**                       and nonterminal numbers.  "unsigned char" is
102793**                       used if there are fewer than 250 terminals
102794**                       and nonterminals.  "int" is used otherwise.
102795**    YYNOCODE           is a number of type YYCODETYPE which corresponds
102796**                       to no legal terminal or nonterminal number.  This
102797**                       number is used to fill in empty slots of the hash
102798**                       table.
102799**    YYFALLBACK         If defined, this indicates that one or more tokens
102800**                       have fall-back values which should be used if the
102801**                       original value of the token will not parse.
102802**    YYACTIONTYPE       is the data type used for storing terminal
102803**                       and nonterminal numbers.  "unsigned char" is
102804**                       used if there are fewer than 250 rules and
102805**                       states combined.  "int" is used otherwise.
102806**    sqlite3ParserTOKENTYPE     is the data type used for minor tokens given
102807**                       directly to the parser from the tokenizer.
102808**    YYMINORTYPE        is the data type used for all minor tokens.
102809**                       This is typically a union of many types, one of
102810**                       which is sqlite3ParserTOKENTYPE.  The entry in the union
102811**                       for base tokens is called "yy0".
102812**    YYSTACKDEPTH       is the maximum depth of the parser's stack.  If
102813**                       zero the stack is dynamically sized using realloc()
102814**    sqlite3ParserARG_SDECL     A static variable declaration for the %extra_argument
102815**    sqlite3ParserARG_PDECL     A parameter declaration for the %extra_argument
102816**    sqlite3ParserARG_STORE     Code to store %extra_argument into yypParser
102817**    sqlite3ParserARG_FETCH     Code to extract %extra_argument from yypParser
102818**    YYNSTATE           the combined number of states.
102819**    YYNRULE            the number of rules in the grammar
102820**    YYERRORSYMBOL      is the code number of the error symbol.  If not
102821**                       defined, then do no error processing.
102822*/
102823#define YYCODETYPE unsigned char
102824#define YYNOCODE 253
102825#define YYACTIONTYPE unsigned short int
102826#define YYWILDCARD 67
102827#define sqlite3ParserTOKENTYPE Token
102828typedef union {
102829  int yyinit;
102830  sqlite3ParserTOKENTYPE yy0;
102831  int yy4;
102832  struct TrigEvent yy90;
102833  ExprSpan yy118;
102834  TriggerStep* yy203;
102835  u8 yy210;
102836  struct {int value; int mask;} yy215;
102837  SrcList* yy259;
102838  struct LimitVal yy292;
102839  Expr* yy314;
102840  ExprList* yy322;
102841  struct LikeOp yy342;
102842  IdList* yy384;
102843  Select* yy387;
102844} YYMINORTYPE;
102845#ifndef YYSTACKDEPTH
102846#define YYSTACKDEPTH 100
102847#endif
102848#define sqlite3ParserARG_SDECL Parse *pParse;
102849#define sqlite3ParserARG_PDECL ,Parse *pParse
102850#define sqlite3ParserARG_FETCH Parse *pParse = yypParser->pParse
102851#define sqlite3ParserARG_STORE yypParser->pParse = pParse
102852#define YYNSTATE 630
102853#define YYNRULE 329
102854#define YYFALLBACK 1
102855#define YY_NO_ACTION      (YYNSTATE+YYNRULE+2)
102856#define YY_ACCEPT_ACTION  (YYNSTATE+YYNRULE+1)
102857#define YY_ERROR_ACTION   (YYNSTATE+YYNRULE)
102858
102859/* The yyzerominor constant is used to initialize instances of
102860** YYMINORTYPE objects to zero. */
102861static const YYMINORTYPE yyzerominor = { 0 };
102862
102863/* Define the yytestcase() macro to be a no-op if is not already defined
102864** otherwise.
102865**
102866** Applications can choose to define yytestcase() in the %include section
102867** to a macro that can assist in verifying code coverage.  For production
102868** code the yytestcase() macro should be turned off.  But it is useful
102869** for testing.
102870*/
102871#ifndef yytestcase
102872# define yytestcase(X)
102873#endif
102874
102875
102876/* Next are the tables used to determine what action to take based on the
102877** current state and lookahead token.  These tables are used to implement
102878** functions that take a state number and lookahead value and return an
102879** action integer.
102880**
102881** Suppose the action integer is N.  Then the action is determined as
102882** follows
102883**
102884**   0 <= N < YYNSTATE                  Shift N.  That is, push the lookahead
102885**                                      token onto the stack and goto state N.
102886**
102887**   YYNSTATE <= N < YYNSTATE+YYNRULE   Reduce by rule N-YYNSTATE.
102888**
102889**   N == YYNSTATE+YYNRULE              A syntax error has occurred.
102890**
102891**   N == YYNSTATE+YYNRULE+1            The parser accepts its input.
102892**
102893**   N == YYNSTATE+YYNRULE+2            No such action.  Denotes unused
102894**                                      slots in the yy_action[] table.
102895**
102896** The action table is constructed as a single large table named yy_action[].
102897** Given state S and lookahead X, the action is computed as
102898**
102899**      yy_action[ yy_shift_ofst[S] + X ]
102900**
102901** If the index value yy_shift_ofst[S]+X is out of range or if the value
102902** yy_lookahead[yy_shift_ofst[S]+X] is not equal to X or if yy_shift_ofst[S]
102903** is equal to YY_SHIFT_USE_DFLT, it means that the action is not in the table
102904** and that yy_default[S] should be used instead.
102905**
102906** The formula above is for computing the action when the lookahead is
102907** a terminal symbol.  If the lookahead is a non-terminal (as occurs after
102908** a reduce action) then the yy_reduce_ofst[] array is used in place of
102909** the yy_shift_ofst[] array and YY_REDUCE_USE_DFLT is used in place of
102910** YY_SHIFT_USE_DFLT.
102911**
102912** The following are the tables generated in this section:
102913**
102914**  yy_action[]        A single table containing all actions.
102915**  yy_lookahead[]     A table containing the lookahead for each entry in
102916**                     yy_action.  Used to detect hash collisions.
102917**  yy_shift_ofst[]    For each state, the offset into yy_action for
102918**                     shifting terminals.
102919**  yy_reduce_ofst[]   For each state, the offset into yy_action for
102920**                     shifting non-terminals after a reduce.
102921**  yy_default[]       Default action for each state.
102922*/
102923#define YY_ACTTAB_COUNT (1557)
102924static const YYACTIONTYPE yy_action[] = {
102925 /*     0 */   313,  960,  186,  419,    2,  172,  627,  597,   55,   55,
102926 /*    10 */    55,   55,   48,   53,   53,   53,   53,   52,   52,   51,
102927 /*    20 */    51,   51,   50,  238,  302,  283,  623,  622,  516,  515,
102928 /*    30 */   590,  584,   55,   55,   55,   55,  282,   53,   53,   53,
102929 /*    40 */    53,   52,   52,   51,   51,   51,   50,  238,    6,   56,
102930 /*    50 */    57,   47,  582,  581,  583,  583,   54,   54,   55,   55,
102931 /*    60 */    55,   55,  608,   53,   53,   53,   53,   52,   52,   51,
102932 /*    70 */    51,   51,   50,  238,  313,  597,  409,  330,  579,  579,
102933 /*    80 */    32,   53,   53,   53,   53,   52,   52,   51,   51,   51,
102934 /*    90 */    50,  238,  330,  217,  620,  619,  166,  411,  624,  382,
102935 /*   100 */   379,  378,    7,  491,  590,  584,  200,  199,  198,   58,
102936 /*   110 */   377,  300,  414,  621,  481,   66,  623,  622,  621,  580,
102937 /*   120 */   254,  601,   94,   56,   57,   47,  582,  581,  583,  583,
102938 /*   130 */    54,   54,   55,   55,   55,   55,  671,   53,   53,   53,
102939 /*   140 */    53,   52,   52,   51,   51,   51,   50,  238,  313,  532,
102940 /*   150 */   226,  506,  507,  133,  177,  139,  284,  385,  279,  384,
102941 /*   160 */   169,  197,  342,  398,  251,  226,  253,  275,  388,  167,
102942 /*   170 */   139,  284,  385,  279,  384,  169,  570,  236,  590,  584,
102943 /*   180 */   672,  240,  275,  157,  620,  619,  554,  437,   51,   51,
102944 /*   190 */    51,   50,  238,  343,  439,  553,  438,   56,   57,   47,
102945 /*   200 */   582,  581,  583,  583,   54,   54,   55,   55,   55,   55,
102946 /*   210 */   465,   53,   53,   53,   53,   52,   52,   51,   51,   51,
102947 /*   220 */    50,  238,  313,  390,   52,   52,   51,   51,   51,   50,
102948 /*   230 */   238,  391,  166,  491,  566,  382,  379,  378,  409,  440,
102949 /*   240 */   579,  579,  252,  440,  607,   66,  377,  513,  621,   49,
102950 /*   250 */    46,  147,  590,  584,  621,   16,  466,  189,  621,  441,
102951 /*   260 */   442,  673,  526,  441,  340,  577,  595,   64,  194,  482,
102952 /*   270 */   434,   56,   57,   47,  582,  581,  583,  583,   54,   54,
102953 /*   280 */    55,   55,   55,   55,   30,   53,   53,   53,   53,   52,
102954 /*   290 */    52,   51,   51,   51,   50,  238,  313,  593,  593,  593,
102955 /*   300 */   387,  578,  606,  493,  259,  351,  258,  411,    1,  623,
102956 /*   310 */   622,  496,  623,  622,   65,  240,  623,  622,  597,  443,
102957 /*   320 */   237,  239,  414,  341,  237,  602,  590,  584,   18,  603,
102958 /*   330 */   166,  601,   87,  382,  379,  378,   67,  623,  622,   38,
102959 /*   340 */   623,  622,  176,  270,  377,   56,   57,   47,  582,  581,
102960 /*   350 */   583,  583,   54,   54,   55,   55,   55,   55,  175,   53,
102961 /*   360 */    53,   53,   53,   52,   52,   51,   51,   51,   50,  238,
102962 /*   370 */   313,  396,  233,  411,  531,  565,  317,  620,  619,   44,
102963 /*   380 */   620,  619,  240,  206,  620,  619,  597,  266,  414,  268,
102964 /*   390 */   409,  597,  579,  579,  352,  184,  505,  601,   73,  533,
102965 /*   400 */   590,  584,  466,  548,  190,  620,  619,  576,  620,  619,
102966 /*   410 */   547,  383,  551,   35,  332,  575,  574,  600,  504,   56,
102967 /*   420 */    57,   47,  582,  581,  583,  583,   54,   54,   55,   55,
102968 /*   430 */    55,   55,  567,   53,   53,   53,   53,   52,   52,   51,
102969 /*   440 */    51,   51,   50,  238,  313,  411,  561,  561,  528,  364,
102970 /*   450 */   259,  351,  258,  183,  361,  549,  524,  374,  411,  597,
102971 /*   460 */   414,  240,  560,  560,  409,  604,  579,  579,  328,  601,
102972 /*   470 */    93,  623,  622,  414,  590,  584,  237,  564,  559,  559,
102973 /*   480 */   520,  402,  601,   87,  409,  210,  579,  579,  168,  421,
102974 /*   490 */   950,  519,  950,   56,   57,   47,  582,  581,  583,  583,
102975 /*   500 */    54,   54,   55,   55,   55,   55,  192,   53,   53,   53,
102976 /*   510 */    53,   52,   52,   51,   51,   51,   50,  238,  313,  600,
102977 /*   520 */   293,  563,  511,  234,  357,  146,  475,  475,  367,  411,
102978 /*   530 */   562,  411,  358,  542,  425,  171,  411,  215,  144,  620,
102979 /*   540 */   619,  544,  318,  353,  414,  203,  414,  275,  590,  584,
102980 /*   550 */   549,  414,  174,  601,   94,  601,   79,  558,  471,   61,
102981 /*   560 */   601,   79,  421,  949,  350,  949,   34,   56,   57,   47,
102982 /*   570 */   582,  581,  583,  583,   54,   54,   55,   55,   55,   55,
102983 /*   580 */   535,   53,   53,   53,   53,   52,   52,   51,   51,   51,
102984 /*   590 */    50,  238,  313,  307,  424,  394,  272,   49,   46,  147,
102985 /*   600 */   349,  322,    4,  411,  491,  312,  321,  425,  568,  492,
102986 /*   610 */   216,  264,  407,  575,  574,  429,   66,  549,  414,  621,
102987 /*   620 */   540,  602,  590,  584,   13,  603,  621,  601,   72,   12,
102988 /*   630 */   618,  617,  616,  202,  210,  621,  546,  469,  422,  319,
102989 /*   640 */   148,   56,   57,   47,  582,  581,  583,  583,   54,   54,
102990 /*   650 */    55,   55,   55,   55,  338,   53,   53,   53,   53,   52,
102991 /*   660 */    52,   51,   51,   51,   50,  238,  313,  600,  600,  411,
102992 /*   670 */    39,   21,   37,  170,  237,  875,  411,  572,  572,  201,
102993 /*   680 */   144,  473,  538,  331,  414,  474,  143,  146,  630,  628,
102994 /*   690 */   334,  414,  353,  601,   68,  168,  590,  584,  132,  365,
102995 /*   700 */   601,   96,  307,  423,  530,  336,   49,   46,  147,  568,
102996 /*   710 */   406,  216,  549,  360,  529,   56,   57,   47,  582,  581,
102997 /*   720 */   583,  583,   54,   54,   55,   55,   55,   55,  411,   53,
102998 /*   730 */    53,   53,   53,   52,   52,   51,   51,   51,   50,  238,
102999 /*   740 */   313,  411,  605,  414,  484,  510,  172,  422,  597,  318,
103000 /*   750 */   496,  485,  601,   99,  411,  142,  414,  411,  231,  411,
103001 /*   760 */   540,  411,  359,  629,    2,  601,   97,  426,  308,  414,
103002 /*   770 */   590,  584,  414,   20,  414,  621,  414,  621,  601,  106,
103003 /*   780 */   503,  601,  105,  601,  108,  601,  109,  204,   28,   56,
103004 /*   790 */    57,   47,  582,  581,  583,  583,   54,   54,   55,   55,
103005 /*   800 */    55,   55,  411,   53,   53,   53,   53,   52,   52,   51,
103006 /*   810 */    51,   51,   50,  238,  313,  411,  597,  414,  411,  276,
103007 /*   820 */   214,  600,  411,  366,  213,  381,  601,  134,  274,  500,
103008 /*   830 */   414,  167,  130,  414,  621,  411,  354,  414,  376,  601,
103009 /*   840 */   135,  129,  601,  100,  590,  584,  601,  104,  522,  521,
103010 /*   850 */   414,  621,  224,  273,  600,  167,  327,  282,  600,  601,
103011 /*   860 */   103,  468,  521,   56,   57,   47,  582,  581,  583,  583,
103012 /*   870 */    54,   54,   55,   55,   55,   55,  411,   53,   53,   53,
103013 /*   880 */    53,   52,   52,   51,   51,   51,   50,  238,  313,  411,
103014 /*   890 */    27,  414,  411,  375,  276,  167,  359,  544,   50,  238,
103015 /*   900 */   601,   95,  128,  223,  414,  411,  165,  414,  411,  621,
103016 /*   910 */   411,  621,  612,  601,  102,  372,  601,   76,  590,  584,
103017 /*   920 */   414,  570,  236,  414,  470,  414,  167,  621,  188,  601,
103018 /*   930 */    98,  225,  601,  138,  601,  137,  232,   56,   45,   47,
103019 /*   940 */   582,  581,  583,  583,   54,   54,   55,   55,   55,   55,
103020 /*   950 */   411,   53,   53,   53,   53,   52,   52,   51,   51,   51,
103021 /*   960 */    50,  238,  313,  276,  276,  414,  411,  276,  544,  459,
103022 /*   970 */   359,  171,  209,  479,  601,  136,  628,  334,  621,  621,
103023 /*   980 */   125,  414,  621,  368,  411,  621,  257,  540,  589,  588,
103024 /*   990 */   601,   75,  590,  584,  458,  446,   23,   23,  124,  414,
103025 /*  1000 */   326,  325,  621,  427,  324,  309,  600,  288,  601,   92,
103026 /*  1010 */   586,  585,   57,   47,  582,  581,  583,  583,   54,   54,
103027 /*  1020 */    55,   55,   55,   55,  411,   53,   53,   53,   53,   52,
103028 /*  1030 */    52,   51,   51,   51,   50,  238,  313,  587,  411,  414,
103029 /*  1040 */   411,  207,  611,  476,  171,  472,  160,  123,  601,   91,
103030 /*  1050 */   323,  261,   15,  414,  464,  414,  411,  621,  411,  354,
103031 /*  1060 */   222,  411,  601,   74,  601,   90,  590,  584,  159,  264,
103032 /*  1070 */   158,  414,  461,  414,  621,  600,  414,  121,  120,   25,
103033 /*  1080 */   601,   89,  601,  101,  621,  601,   88,   47,  582,  581,
103034 /*  1090 */   583,  583,   54,   54,   55,   55,   55,   55,  544,   53,
103035 /*  1100 */    53,   53,   53,   52,   52,   51,   51,   51,   50,  238,
103036 /*  1110 */    43,  405,  263,    3,  610,  264,  140,  415,  622,   24,
103037 /*  1120 */   410,   11,  456,  594,  118,  155,  219,  452,  408,  621,
103038 /*  1130 */   621,  621,  156,   43,  405,  621,    3,  286,  621,  113,
103039 /*  1140 */   415,  622,  111,  445,  411,  400,  557,  403,  545,   10,
103040 /*  1150 */   411,  408,  264,  110,  205,  436,  541,  566,  453,  414,
103041 /*  1160 */   621,  621,   63,  621,  435,  414,  411,  621,  601,   94,
103042 /*  1170 */   403,  621,  411,  337,  601,   86,  150,   40,   41,  534,
103043 /*  1180 */   566,  414,  242,  264,   42,  413,  412,  414,  600,  595,
103044 /*  1190 */   601,   85,  191,  333,  107,  451,  601,   84,  621,  539,
103045 /*  1200 */    40,   41,  420,  230,  411,  149,  316,   42,  413,  412,
103046 /*  1210 */   398,  127,  595,  315,  621,  399,  278,  625,  181,  414,
103047 /*  1220 */   593,  593,  593,  592,  591,   14,  450,  411,  601,   71,
103048 /*  1230 */   240,  621,   43,  405,  264,    3,  615,  180,  264,  415,
103049 /*  1240 */   622,  614,  414,  593,  593,  593,  592,  591,   14,  621,
103050 /*  1250 */   408,  601,   70,  621,  417,   33,  405,  613,    3,  411,
103051 /*  1260 */   264,  411,  415,  622,  418,  626,  178,  509,    8,  403,
103052 /*  1270 */   241,  416,  126,  408,  414,  621,  414,  449,  208,  566,
103053 /*  1280 */   240,  221,  621,  601,   83,  601,   82,  599,  297,  277,
103054 /*  1290 */   296,   30,  403,   31,  395,  264,  295,  397,  489,   40,
103055 /*  1300 */    41,  411,  566,  220,  621,  294,   42,  413,  412,  271,
103056 /*  1310 */   621,  595,  600,  621,   59,   60,  414,  269,  267,  623,
103057 /*  1320 */   622,   36,   40,   41,  621,  601,   81,  598,  235,   42,
103058 /*  1330 */   413,  412,  621,  621,  595,  265,  344,  411,  248,  556,
103059 /*  1340 */   173,  185,  593,  593,  593,  592,  591,   14,  218,   29,
103060 /*  1350 */   621,  543,  414,  305,  304,  303,  179,  301,  411,  566,
103061 /*  1360 */   454,  601,   80,  289,  335,  593,  593,  593,  592,  591,
103062 /*  1370 */    14,  411,  287,  414,  151,  392,  246,  260,  411,  196,
103063 /*  1380 */   195,  523,  601,   69,  411,  245,  414,  526,  537,  285,
103064 /*  1390 */   389,  595,  621,  414,  536,  601,   17,  362,  153,  414,
103065 /*  1400 */   466,  463,  601,   78,  154,  414,  462,  152,  601,   77,
103066 /*  1410 */   355,  255,  621,  455,  601,    9,  621,  386,  444,  517,
103067 /*  1420 */   247,  621,  593,  593,  593,  621,  621,  244,  621,  243,
103068 /*  1430 */   430,  518,  292,  621,  329,  621,  145,  393,  280,  513,
103069 /*  1440 */   291,  131,  621,  514,  621,  621,  311,  621,  259,  346,
103070 /*  1450 */   249,  621,  621,  229,  314,  621,  228,  512,  227,  240,
103071 /*  1460 */   494,  488,  310,  164,  487,  486,  373,  480,  163,  262,
103072 /*  1470 */   369,  371,  162,   26,  212,  478,  477,  161,  141,  363,
103073 /*  1480 */   467,  122,  339,  187,  119,  348,  347,  117,  116,  115,
103074 /*  1490 */   114,  112,  182,  457,  320,   22,  433,  432,  448,   19,
103075 /*  1500 */   609,  431,  428,   62,  193,  596,  573,  298,  555,  552,
103076 /*  1510 */   571,  404,  290,  380,  498,  510,  495,  306,  281,  499,
103077 /*  1520 */   250,    5,  497,  460,  345,  447,  569,  550,  238,  299,
103078 /*  1530 */   527,  525,  508,  961,  502,  501,  961,  401,  961,  211,
103079 /*  1540 */   490,  356,  256,  961,  483,  961,  961,  961,  961,  961,
103080 /*  1550 */   961,  961,  961,  961,  961,  961,  370,
103081};
103082static const YYCODETYPE yy_lookahead[] = {
103083 /*     0 */    19,  142,  143,  144,  145,   24,    1,   26,   77,   78,
103084 /*    10 */    79,   80,   81,   82,   83,   84,   85,   86,   87,   88,
103085 /*    20 */    89,   90,   91,   92,   15,   98,   26,   27,    7,    8,
103086 /*    30 */    49,   50,   77,   78,   79,   80,  109,   82,   83,   84,
103087 /*    40 */    85,   86,   87,   88,   89,   90,   91,   92,   22,   68,
103088 /*    50 */    69,   70,   71,   72,   73,   74,   75,   76,   77,   78,
103089 /*    60 */    79,   80,   23,   82,   83,   84,   85,   86,   87,   88,
103090 /*    70 */    89,   90,   91,   92,   19,   94,  112,   19,  114,  115,
103091 /*    80 */    25,   82,   83,   84,   85,   86,   87,   88,   89,   90,
103092 /*    90 */    91,   92,   19,   22,   94,   95,   96,  150,  150,   99,
103093 /*   100 */   100,  101,   76,  150,   49,   50,  105,  106,  107,   54,
103094 /*   110 */   110,  158,  165,  165,  161,  162,   26,   27,  165,  113,
103095 /*   120 */    16,  174,  175,   68,   69,   70,   71,   72,   73,   74,
103096 /*   130 */    75,   76,   77,   78,   79,   80,  118,   82,   83,   84,
103097 /*   140 */    85,   86,   87,   88,   89,   90,   91,   92,   19,   23,
103098 /*   150 */    92,   97,   98,   24,   96,   97,   98,   99,  100,  101,
103099 /*   160 */   102,   25,   97,  216,   60,   92,   62,  109,  221,   25,
103100 /*   170 */    97,   98,   99,  100,  101,  102,   86,   87,   49,   50,
103101 /*   180 */   118,  116,  109,   25,   94,   95,   32,   97,   88,   89,
103102 /*   190 */    90,   91,   92,  128,  104,   41,  106,   68,   69,   70,
103103 /*   200 */    71,   72,   73,   74,   75,   76,   77,   78,   79,   80,
103104 /*   210 */    11,   82,   83,   84,   85,   86,   87,   88,   89,   90,
103105 /*   220 */    91,   92,   19,   19,   86,   87,   88,   89,   90,   91,
103106 /*   230 */    92,   27,   96,  150,   66,   99,  100,  101,  112,  150,
103107 /*   240 */   114,  115,  138,  150,  161,  162,  110,  103,  165,  222,
103108 /*   250 */   223,  224,   49,   50,  165,   22,   57,   24,  165,  170,
103109 /*   260 */   171,  118,   94,  170,  171,   23,   98,   25,  185,  186,
103110 /*   270 */   243,   68,   69,   70,   71,   72,   73,   74,   75,   76,
103111 /*   280 */    77,   78,   79,   80,  126,   82,   83,   84,   85,   86,
103112 /*   290 */    87,   88,   89,   90,   91,   92,   19,  129,  130,  131,
103113 /*   300 */    88,   23,  172,  173,  105,  106,  107,  150,   22,   26,
103114 /*   310 */    27,  181,   26,   27,   22,  116,   26,   27,   26,  230,
103115 /*   320 */   231,  197,  165,  230,  231,  113,   49,   50,  204,  117,
103116 /*   330 */    96,  174,  175,   99,  100,  101,   22,   26,   27,  136,
103117 /*   340 */    26,   27,  118,   16,  110,   68,   69,   70,   71,   72,
103118 /*   350 */    73,   74,   75,   76,   77,   78,   79,   80,  118,   82,
103119 /*   360 */    83,   84,   85,   86,   87,   88,   89,   90,   91,   92,
103120 /*   370 */    19,  214,  215,  150,   23,   23,  155,   94,   95,   22,
103121 /*   380 */    94,   95,  116,  160,   94,   95,   94,   60,  165,   62,
103122 /*   390 */   112,   26,  114,  115,  128,   23,   36,  174,  175,   88,
103123 /*   400 */    49,   50,   57,  120,   22,   94,   95,   23,   94,   95,
103124 /*   410 */   120,   51,   25,  136,  169,  170,  171,  194,   58,   68,
103125 /*   420 */    69,   70,   71,   72,   73,   74,   75,   76,   77,   78,
103126 /*   430 */    79,   80,   23,   82,   83,   84,   85,   86,   87,   88,
103127 /*   440 */    89,   90,   91,   92,   19,  150,   12,   12,   23,  228,
103128 /*   450 */   105,  106,  107,   23,  233,   25,  165,   19,  150,   94,
103129 /*   460 */   165,  116,   28,   28,  112,  174,  114,  115,  108,  174,
103130 /*   470 */   175,   26,   27,  165,   49,   50,  231,   11,   44,   44,
103131 /*   480 */    46,   46,  174,  175,  112,  160,  114,  115,   50,   22,
103132 /*   490 */    23,   57,   25,   68,   69,   70,   71,   72,   73,   74,
103133 /*   500 */    75,   76,   77,   78,   79,   80,  119,   82,   83,   84,
103134 /*   510 */    85,   86,   87,   88,   89,   90,   91,   92,   19,  194,
103135 /*   520 */   225,   23,   23,  215,   19,   95,  105,  106,  107,  150,
103136 /*   530 */    23,  150,   27,   23,   67,   25,  150,  206,  207,   94,
103137 /*   540 */    95,  166,  104,  218,  165,   22,  165,  109,   49,   50,
103138 /*   550 */   120,  165,   25,  174,  175,  174,  175,   23,   21,  234,
103139 /*   560 */   174,  175,   22,   23,  239,   25,   25,   68,   69,   70,
103140 /*   570 */    71,   72,   73,   74,   75,   76,   77,   78,   79,   80,
103141 /*   580 */   205,   82,   83,   84,   85,   86,   87,   88,   89,   90,
103142 /*   590 */    91,   92,   19,   22,   23,  216,   23,  222,  223,  224,
103143 /*   600 */    63,  220,   35,  150,  150,  163,  220,   67,  166,  167,
103144 /*   610 */   168,  150,  169,  170,  171,  161,  162,   25,  165,  165,
103145 /*   620 */   150,  113,   49,   50,   25,  117,  165,  174,  175,   35,
103146 /*   630 */     7,    8,    9,  160,  160,  165,  120,  100,   67,  247,
103147 /*   640 */   248,   68,   69,   70,   71,   72,   73,   74,   75,   76,
103148 /*   650 */    77,   78,   79,   80,  193,   82,   83,   84,   85,   86,
103149 /*   660 */    87,   88,   89,   90,   91,   92,   19,  194,  194,  150,
103150 /*   670 */   135,   24,  137,   35,  231,  138,  150,  129,  130,  206,
103151 /*   680 */   207,   30,   27,  213,  165,   34,  118,   95,    0,    1,
103152 /*   690 */     2,  165,  218,  174,  175,   50,   49,   50,   22,   48,
103153 /*   700 */   174,  175,   22,   23,   23,  244,  222,  223,  224,  166,
103154 /*   710 */   167,  168,  120,  239,   23,   68,   69,   70,   71,   72,
103155 /*   720 */    73,   74,   75,   76,   77,   78,   79,   80,  150,   82,
103156 /*   730 */    83,   84,   85,   86,   87,   88,   89,   90,   91,   92,
103157 /*   740 */    19,  150,  173,  165,  181,  182,   24,   67,   26,  104,
103158 /*   750 */   181,  188,  174,  175,  150,   39,  165,  150,   52,  150,
103159 /*   760 */   150,  150,  150,  144,  145,  174,  175,  249,  250,  165,
103160 /*   770 */    49,   50,  165,   52,  165,  165,  165,  165,  174,  175,
103161 /*   780 */    29,  174,  175,  174,  175,  174,  175,  160,   22,   68,
103162 /*   790 */    69,   70,   71,   72,   73,   74,   75,   76,   77,   78,
103163 /*   800 */    79,   80,  150,   82,   83,   84,   85,   86,   87,   88,
103164 /*   810 */    89,   90,   91,   92,   19,  150,   94,  165,  150,  150,
103165 /*   820 */   160,  194,  150,  213,  160,   52,  174,  175,   23,   23,
103166 /*   830 */   165,   25,   22,  165,  165,  150,  150,  165,   52,  174,
103167 /*   840 */   175,   22,  174,  175,   49,   50,  174,  175,  190,  191,
103168 /*   850 */   165,  165,  240,   23,  194,   25,  187,  109,  194,  174,
103169 /*   860 */   175,  190,  191,   68,   69,   70,   71,   72,   73,   74,
103170 /*   870 */    75,   76,   77,   78,   79,   80,  150,   82,   83,   84,
103171 /*   880 */    85,   86,   87,   88,   89,   90,   91,   92,   19,  150,
103172 /*   890 */    22,  165,  150,   23,  150,   25,  150,  166,   91,   92,
103173 /*   900 */   174,  175,   22,  217,  165,  150,  102,  165,  150,  165,
103174 /*   910 */   150,  165,  150,  174,  175,   19,  174,  175,   49,   50,
103175 /*   920 */   165,   86,   87,  165,   23,  165,   25,  165,   24,  174,
103176 /*   930 */   175,  187,  174,  175,  174,  175,  205,   68,   69,   70,
103177 /*   940 */    71,   72,   73,   74,   75,   76,   77,   78,   79,   80,
103178 /*   950 */   150,   82,   83,   84,   85,   86,   87,   88,   89,   90,
103179 /*   960 */    91,   92,   19,  150,  150,  165,  150,  150,  166,   23,
103180 /*   970 */   150,   25,  160,   20,  174,  175,    1,    2,  165,  165,
103181 /*   980 */   104,  165,  165,   43,  150,  165,  240,  150,   49,   50,
103182 /*   990 */   174,  175,   49,   50,   23,   23,   25,   25,   53,  165,
103183 /*  1000 */   187,  187,  165,   23,  187,   25,  194,  205,  174,  175,
103184 /*  1010 */    71,   72,   69,   70,   71,   72,   73,   74,   75,   76,
103185 /*  1020 */    77,   78,   79,   80,  150,   82,   83,   84,   85,   86,
103186 /*  1030 */    87,   88,   89,   90,   91,   92,   19,   98,  150,  165,
103187 /*  1040 */   150,  160,  150,   59,   25,   53,  104,   22,  174,  175,
103188 /*  1050 */   213,  138,    5,  165,    1,  165,  150,  165,  150,  150,
103189 /*  1060 */   240,  150,  174,  175,  174,  175,   49,   50,  118,  150,
103190 /*  1070 */    35,  165,   27,  165,  165,  194,  165,  108,  127,   76,
103191 /*  1080 */   174,  175,  174,  175,  165,  174,  175,   70,   71,   72,
103192 /*  1090 */    73,   74,   75,   76,   77,   78,   79,   80,  166,   82,
103193 /*  1100 */    83,   84,   85,   86,   87,   88,   89,   90,   91,   92,
103194 /*  1110 */    19,   20,  193,   22,  150,  150,  150,   26,   27,   76,
103195 /*  1120 */   150,   22,    1,  150,  119,  121,  217,   20,   37,  165,
103196 /*  1130 */   165,  165,   16,   19,   20,  165,   22,  205,  165,  119,
103197 /*  1140 */    26,   27,  108,  128,  150,  150,  150,   56,  150,   22,
103198 /*  1150 */   150,   37,  150,  127,  160,   23,  150,   66,  193,  165,
103199 /*  1160 */   165,  165,   16,  165,   23,  165,  150,  165,  174,  175,
103200 /*  1170 */    56,  165,  150,   65,  174,  175,   15,   86,   87,   88,
103201 /*  1180 */    66,  165,  140,  150,   93,   94,   95,  165,  194,   98,
103202 /*  1190 */   174,  175,   22,    3,  164,  193,  174,  175,  165,  150,
103203 /*  1200 */    86,   87,    4,  180,  150,  248,  251,   93,   94,   95,
103204 /*  1210 */   216,  180,   98,  251,  165,  221,  150,  149,    6,  165,
103205 /*  1220 */   129,  130,  131,  132,  133,  134,  193,  150,  174,  175,
103206 /*  1230 */   116,  165,   19,   20,  150,   22,  149,  151,  150,   26,
103207 /*  1240 */    27,  149,  165,  129,  130,  131,  132,  133,  134,  165,
103208 /*  1250 */    37,  174,  175,  165,  149,   19,   20,   13,   22,  150,
103209 /*  1260 */   150,  150,   26,   27,  146,  147,  151,  150,   25,   56,
103210 /*  1270 */   152,  159,  154,   37,  165,  165,  165,  193,  160,   66,
103211 /*  1280 */   116,  193,  165,  174,  175,  174,  175,  194,  199,  150,
103212 /*  1290 */   200,  126,   56,  124,  123,  150,  201,  122,  150,   86,
103213 /*  1300 */    87,  150,   66,  193,  165,  202,   93,   94,   95,  150,
103214 /*  1310 */   165,   98,  194,  165,  125,   22,  165,  150,  150,   26,
103215 /*  1320 */    27,  135,   86,   87,  165,  174,  175,  203,  226,   93,
103216 /*  1330 */    94,   95,  165,  165,   98,  150,  218,  150,  193,  157,
103217 /*  1340 */   118,  157,  129,  130,  131,  132,  133,  134,    5,  104,
103218 /*  1350 */   165,  211,  165,   10,   11,   12,   13,   14,  150,   66,
103219 /*  1360 */    17,  174,  175,  210,  246,  129,  130,  131,  132,  133,
103220 /*  1370 */   134,  150,  210,  165,   31,  121,   33,  150,  150,   86,
103221 /*  1380 */    87,  176,  174,  175,  150,   42,  165,   94,  211,  210,
103222 /*  1390 */   150,   98,  165,  165,  211,  174,  175,  150,   55,  165,
103223 /*  1400 */    57,  150,  174,  175,   61,  165,  150,   64,  174,  175,
103224 /*  1410 */   150,  150,  165,  150,  174,  175,  165,  104,  150,  184,
103225 /*  1420 */   150,  165,  129,  130,  131,  165,  165,  150,  165,  150,
103226 /*  1430 */   150,  176,  150,  165,   47,  165,  150,  150,  176,  103,
103227 /*  1440 */   150,   22,  165,  178,  165,  165,  179,  165,  105,  106,
103228 /*  1450 */   107,  165,  165,  229,  111,  165,   92,  176,  229,  116,
103229 /*  1460 */   184,  176,  179,  156,  176,  176,   18,  157,  156,  237,
103230 /*  1470 */    45,  157,  156,  135,  157,  157,  238,  156,   68,  157,
103231 /*  1480 */   189,  189,  139,  219,   22,  157,   18,  192,  192,  192,
103232 /*  1490 */   192,  189,  219,  199,  157,  242,   40,  157,  199,  242,
103233 /*  1500 */   153,  157,   38,  245,  196,  166,  232,  198,  177,  177,
103234 /*  1510 */   232,  227,  209,  178,  166,  182,  166,  148,  177,  177,
103235 /*  1520 */   209,  196,  177,  199,  209,  199,  166,  208,   92,  195,
103236 /*  1530 */   174,  174,  183,  252,  183,  183,  252,  191,  252,  235,
103237 /*  1540 */   186,  241,  241,  252,  186,  252,  252,  252,  252,  252,
103238 /*  1550 */   252,  252,  252,  252,  252,  252,  236,
103239};
103240#define YY_SHIFT_USE_DFLT (-74)
103241#define YY_SHIFT_COUNT (418)
103242#define YY_SHIFT_MIN   (-73)
103243#define YY_SHIFT_MAX   (1468)
103244static const short yy_shift_ofst[] = {
103245 /*     0 */   975, 1114, 1343, 1114, 1213, 1213,   90,   90,    0,  -19,
103246 /*    10 */  1213, 1213, 1213, 1213, 1213,  345,  445,  721, 1091, 1213,
103247 /*    20 */  1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213,
103248 /*    30 */  1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213,
103249 /*    40 */  1213, 1213, 1213, 1213, 1213, 1213, 1213, 1236, 1213, 1213,
103250 /*    50 */  1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213,
103251 /*    60 */  1213,  199,  445,  445,  835,  835,  365, 1164,   55,  647,
103252 /*    70 */   573,  499,  425,  351,  277,  203,  129,  795,  795,  795,
103253 /*    80 */   795,  795,  795,  795,  795,  795,  795,  795,  795,  795,
103254 /*    90 */   795,  795,  795,  795,  795,  869,  795,  943, 1017, 1017,
103255 /*   100 */   -69,  -45,  -45,  -45,  -45,  -45,   -1,   58,  138,  100,
103256 /*   110 */   445,  445,  445,  445,  445,  445,  445,  445,  445,  445,
103257 /*   120 */   445,  445,  445,  445,  445,  445,  537,  438,  445,  445,
103258 /*   130 */   445,  445,  445,  365,  807, 1436,  -74,  -74,  -74, 1293,
103259 /*   140 */    73,  434,  434,  311,  314,  290,  283,  286,  540,  467,
103260 /*   150 */   445,  445,  445,  445,  445,  445,  445,  445,  445,  445,
103261 /*   160 */   445,  445,  445,  445,  445,  445,  445,  445,  445,  445,
103262 /*   170 */   445,  445,  445,  445,  445,  445,  445,  445,  445,  445,
103263 /*   180 */   445,  445,   65,  722,  722,  722,  688,  266, 1164, 1164,
103264 /*   190 */  1164,  -74,  -74,  -74,  136,  168,  168,  234,  360,  360,
103265 /*   200 */   360,  430,  372,  435,  352,  278,  126,  -36,  -36,  -36,
103266 /*   210 */   -36,  421,  651,  -36,  -36,  592,  292,  212,  623,  158,
103267 /*   220 */   204,  204,  505,  158,  505,  144,  365,  154,  365,  154,
103268 /*   230 */   645,  154,  204,  154,  154,  535,  548,  548,  365,  387,
103269 /*   240 */   508,  233, 1464, 1222, 1222, 1456, 1456, 1222, 1462, 1410,
103270 /*   250 */  1165, 1468, 1468, 1468, 1468, 1222, 1165, 1462, 1410, 1410,
103271 /*   260 */  1222, 1448, 1338, 1425, 1222, 1222, 1448, 1222, 1448, 1222,
103272 /*   270 */  1448, 1419, 1313, 1313, 1313, 1387, 1364, 1364, 1419, 1313,
103273 /*   280 */  1336, 1313, 1387, 1313, 1313, 1254, 1245, 1254, 1245, 1254,
103274 /*   290 */  1245, 1222, 1222, 1186, 1189, 1175, 1169, 1171, 1165, 1164,
103275 /*   300 */  1243, 1244, 1244, 1212, 1212, 1212, 1212,  -74,  -74,  -74,
103276 /*   310 */   -74,  -74,  -74,  939,  104,  680,  571,  327,    1,  980,
103277 /*   320 */    26,  972,  971,  946,  901,  870,  830,  806,   54,   21,
103278 /*   330 */   -73,  510,  242, 1198, 1190, 1170, 1042, 1161, 1108, 1146,
103279 /*   340 */  1141, 1132, 1015, 1127, 1026, 1034, 1020, 1107, 1004, 1116,
103280 /*   350 */  1121, 1005, 1099,  951, 1043, 1003,  969, 1045, 1035,  950,
103281 /*   360 */  1053, 1047, 1025,  942,  913,  992, 1019,  945,  984,  940,
103282 /*   370 */   876,  904,  953,  896,  748,  804,  880,  786,  868,  819,
103283 /*   380 */   805,  810,  773,  751,  766,  706,  716,  691,  681,  568,
103284 /*   390 */   655,  638,  676,  516,  541,  594,  599,  567,  541,  534,
103285 /*   400 */   507,  527,  498,  523,  466,  382,  409,  384,  357,    6,
103286 /*   410 */   240,  224,  143,   62,   18,   71,   39,    9,    5,
103287};
103288#define YY_REDUCE_USE_DFLT (-142)
103289#define YY_REDUCE_COUNT (312)
103290#define YY_REDUCE_MIN   (-141)
103291#define YY_REDUCE_MAX   (1369)
103292static const short yy_reduce_ofst[] = {
103293 /*     0 */  -141,  994, 1118,  223,  157,  -53,   93,   89,   83,  375,
103294 /*    10 */   386,  381,  379,  308,  295,  325,  -47,   27, 1240, 1234,
103295 /*    20 */  1228, 1221, 1208, 1187, 1151, 1111, 1109, 1077, 1054, 1022,
103296 /*    30 */  1016, 1000,  911,  908,  906,  890,  888,  874,  834,  816,
103297 /*    40 */   800,  760,  758,  755,  742,  739,  726,  685,  672,  668,
103298 /*    50 */   665,  652,  611,  609,  607,  604,  591,  578,  526,  519,
103299 /*    60 */   453,  474,  454,  461,  443,  245,  442,  473,  484,  484,
103300 /*    70 */   484,  484,  484,  484,  484,  484,  484,  484,  484,  484,
103301 /*    80 */   484,  484,  484,  484,  484,  484,  484,  484,  484,  484,
103302 /*    90 */   484,  484,  484,  484,  484,  484,  484,  484,  484,  484,
103303 /*   100 */   484,  484,  484,  484,  484,  484,  484,  130,  484,  484,
103304 /*   110 */  1145,  909, 1110, 1088, 1084, 1033, 1002,  965,  820,  837,
103305 /*   120 */   746,  686,  612,  817,  610,  919,  221,  563,  814,  813,
103306 /*   130 */   744,  669,  470,  543,  484,  484,  484,  484,  484,  291,
103307 /*   140 */   569,  671,  658,  970, 1290, 1287, 1286, 1282,  518,  518,
103308 /*   150 */  1280, 1279, 1277, 1270, 1268, 1263, 1261, 1260, 1256, 1251,
103309 /*   160 */  1247, 1227, 1185, 1168, 1167, 1159, 1148, 1139, 1117, 1066,
103310 /*   170 */  1049, 1006,  998,  996,  995,  973,  970,  966,  964,  892,
103311 /*   180 */   762,  -52,  881,  932,  802,  731,  619,  812,  664,  660,
103312 /*   190 */   627,  392,  331,  124, 1358, 1357, 1356, 1354, 1352, 1351,
103313 /*   200 */  1349, 1319, 1334, 1346, 1334, 1334, 1334, 1334, 1334, 1334,
103314 /*   210 */  1334, 1320, 1304, 1334, 1334, 1319, 1360, 1325, 1369, 1326,
103315 /*   220 */  1315, 1311, 1301, 1324, 1300, 1335, 1350, 1345, 1348, 1342,
103316 /*   230 */  1333, 1341, 1303, 1332, 1331, 1284, 1278, 1274, 1339, 1309,
103317 /*   240 */  1308, 1347, 1258, 1344, 1340, 1257, 1253, 1337, 1273, 1302,
103318 /*   250 */  1299, 1298, 1297, 1296, 1295, 1328, 1294, 1264, 1292, 1291,
103319 /*   260 */  1322, 1321, 1238, 1232, 1318, 1317, 1316, 1314, 1312, 1310,
103320 /*   270 */  1307, 1283, 1289, 1288, 1285, 1276, 1229, 1224, 1267, 1281,
103321 /*   280 */  1265, 1262, 1235, 1255, 1205, 1183, 1179, 1177, 1162, 1140,
103322 /*   290 */  1153, 1184, 1182, 1102, 1124, 1103, 1095, 1090, 1089, 1093,
103323 /*   300 */  1112, 1115, 1086, 1105, 1092, 1087, 1068,  962,  955,  957,
103324 /*   310 */  1031, 1023, 1030,
103325};
103326static const YYACTIONTYPE yy_default[] = {
103327 /*     0 */   635,  870,  959,  959,  959,  870,  899,  899,  959,  759,
103328 /*    10 */   959,  959,  959,  959,  868,  959,  959,  933,  959,  959,
103329 /*    20 */   959,  959,  959,  959,  959,  959,  959,  959,  959,  959,
103330 /*    30 */   959,  959,  959,  959,  959,  959,  959,  959,  959,  959,
103331 /*    40 */   959,  959,  959,  959,  959,  959,  959,  959,  959,  959,
103332 /*    50 */   959,  959,  959,  959,  959,  959,  959,  959,  959,  959,
103333 /*    60 */   959,  959,  959,  959,  899,  899,  674,  763,  794,  959,
103334 /*    70 */   959,  959,  959,  959,  959,  959,  959,  932,  934,  809,
103335 /*    80 */   808,  802,  801,  912,  774,  799,  792,  785,  796,  871,
103336 /*    90 */   864,  865,  863,  867,  872,  959,  795,  831,  848,  830,
103337 /*   100 */   842,  847,  854,  846,  843,  833,  832,  666,  834,  835,
103338 /*   110 */   959,  959,  959,  959,  959,  959,  959,  959,  959,  959,
103339 /*   120 */   959,  959,  959,  959,  959,  959,  661,  728,  959,  959,
103340 /*   130 */   959,  959,  959,  959,  836,  837,  851,  850,  849,  959,
103341 /*   140 */   959,  959,  959,  959,  959,  959,  959,  959,  959,  959,
103342 /*   150 */   959,  939,  937,  959,  883,  959,  959,  959,  959,  959,
103343 /*   160 */   959,  959,  959,  959,  959,  959,  959,  959,  959,  959,
103344 /*   170 */   959,  959,  959,  959,  959,  959,  959,  959,  959,  959,
103345 /*   180 */   959,  641,  959,  759,  759,  759,  635,  959,  959,  959,
103346 /*   190 */   959,  951,  763,  753,  719,  959,  959,  959,  959,  959,
103347 /*   200 */   959,  959,  959,  959,  959,  959,  959,  804,  742,  922,
103348 /*   210 */   924,  959,  905,  740,  663,  761,  676,  751,  643,  798,
103349 /*   220 */   776,  776,  917,  798,  917,  700,  959,  788,  959,  788,
103350 /*   230 */   697,  788,  776,  788,  788,  866,  959,  959,  959,  760,
103351 /*   240 */   751,  959,  944,  767,  767,  936,  936,  767,  810,  732,
103352 /*   250 */   798,  739,  739,  739,  739,  767,  798,  810,  732,  732,
103353 /*   260 */   767,  658,  911,  909,  767,  767,  658,  767,  658,  767,
103354 /*   270 */   658,  876,  730,  730,  730,  715,  880,  880,  876,  730,
103355 /*   280 */   700,  730,  715,  730,  730,  780,  775,  780,  775,  780,
103356 /*   290 */   775,  767,  767,  959,  793,  781,  791,  789,  798,  959,
103357 /*   300 */   718,  651,  651,  640,  640,  640,  640,  956,  956,  951,
103358 /*   310 */   702,  702,  684,  959,  959,  959,  959,  959,  959,  959,
103359 /*   320 */   885,  959,  959,  959,  959,  959,  959,  959,  959,  959,
103360 /*   330 */   959,  959,  959,  959,  636,  946,  959,  959,  943,  959,
103361 /*   340 */   959,  959,  959,  959,  959,  959,  959,  959,  959,  959,
103362 /*   350 */   959,  959,  959,  959,  959,  959,  959,  959,  959,  915,
103363 /*   360 */   959,  959,  959,  959,  959,  959,  908,  907,  959,  959,
103364 /*   370 */   959,  959,  959,  959,  959,  959,  959,  959,  959,  959,
103365 /*   380 */   959,  959,  959,  959,  959,  959,  959,  959,  959,  959,
103366 /*   390 */   959,  959,  959,  959,  790,  959,  782,  959,  869,  959,
103367 /*   400 */   959,  959,  959,  959,  959,  959,  959,  959,  959,  745,
103368 /*   410 */   819,  959,  818,  822,  817,  668,  959,  649,  959,  632,
103369 /*   420 */   637,  955,  958,  957,  954,  953,  952,  947,  945,  942,
103370 /*   430 */   941,  940,  938,  935,  931,  889,  887,  894,  893,  892,
103371 /*   440 */   891,  890,  888,  886,  884,  805,  803,  800,  797,  930,
103372 /*   450 */   882,  741,  738,  737,  657,  948,  914,  923,  921,  811,
103373 /*   460 */   920,  919,  918,  916,  913,  900,  807,  806,  733,  874,
103374 /*   470 */   873,  660,  904,  903,  902,  906,  910,  901,  769,  659,
103375 /*   480 */   656,  665,  722,  721,  729,  727,  726,  725,  724,  723,
103376 /*   490 */   720,  667,  675,  686,  714,  699,  698,  879,  881,  878,
103377 /*   500 */   877,  707,  706,  712,  711,  710,  709,  708,  705,  704,
103378 /*   510 */   703,  696,  695,  701,  694,  717,  716,  713,  693,  736,
103379 /*   520 */   735,  734,  731,  692,  691,  690,  822,  689,  688,  828,
103380 /*   530 */   827,  815,  858,  756,  755,  754,  766,  765,  778,  777,
103381 /*   540 */   813,  812,  779,  764,  758,  757,  773,  772,  771,  770,
103382 /*   550 */   762,  752,  784,  787,  786,  783,  860,  768,  857,  929,
103383 /*   560 */   928,  927,  926,  925,  862,  861,  829,  826,  679,  680,
103384 /*   570 */   898,  896,  897,  895,  682,  681,  678,  677,  859,  747,
103385 /*   580 */   746,  855,  852,  844,  840,  856,  853,  845,  841,  839,
103386 /*   590 */   838,  824,  823,  821,  820,  816,  825,  670,  748,  744,
103387 /*   600 */   743,  814,  750,  749,  687,  685,  683,  664,  662,  655,
103388 /*   610 */   653,  652,  654,  650,  648,  647,  646,  645,  644,  673,
103389 /*   620 */   672,  671,  669,  668,  642,  639,  638,  634,  633,  631,
103390};
103391
103392/* The next table maps tokens into fallback tokens.  If a construct
103393** like the following:
103394**
103395**      %fallback ID X Y Z.
103396**
103397** appears in the grammar, then ID becomes a fallback token for X, Y,
103398** and Z.  Whenever one of the tokens X, Y, or Z is input to the parser
103399** but it does not parse, the type of the token is changed to ID and
103400** the parse is retried before an error is thrown.
103401*/
103402#ifdef YYFALLBACK
103403static const YYCODETYPE yyFallback[] = {
103404    0,  /*          $ => nothing */
103405    0,  /*       SEMI => nothing */
103406   26,  /*    EXPLAIN => ID */
103407   26,  /*      QUERY => ID */
103408   26,  /*       PLAN => ID */
103409   26,  /*      BEGIN => ID */
103410    0,  /* TRANSACTION => nothing */
103411   26,  /*   DEFERRED => ID */
103412   26,  /*  IMMEDIATE => ID */
103413   26,  /*  EXCLUSIVE => ID */
103414    0,  /*     COMMIT => nothing */
103415   26,  /*        END => ID */
103416   26,  /*   ROLLBACK => ID */
103417   26,  /*  SAVEPOINT => ID */
103418   26,  /*    RELEASE => ID */
103419    0,  /*         TO => nothing */
103420    0,  /*      TABLE => nothing */
103421    0,  /*     CREATE => nothing */
103422   26,  /*         IF => ID */
103423    0,  /*        NOT => nothing */
103424    0,  /*     EXISTS => nothing */
103425   26,  /*       TEMP => ID */
103426    0,  /*         LP => nothing */
103427    0,  /*         RP => nothing */
103428    0,  /*         AS => nothing */
103429    0,  /*      COMMA => nothing */
103430    0,  /*         ID => nothing */
103431    0,  /*    INDEXED => nothing */
103432   26,  /*      ABORT => ID */
103433   26,  /*     ACTION => ID */
103434   26,  /*      AFTER => ID */
103435   26,  /*    ANALYZE => ID */
103436   26,  /*        ASC => ID */
103437   26,  /*     ATTACH => ID */
103438   26,  /*     BEFORE => ID */
103439   26,  /*         BY => ID */
103440   26,  /*    CASCADE => ID */
103441   26,  /*       CAST => ID */
103442   26,  /*   COLUMNKW => ID */
103443   26,  /*   CONFLICT => ID */
103444   26,  /*   DATABASE => ID */
103445   26,  /*       DESC => ID */
103446   26,  /*     DETACH => ID */
103447   26,  /*       EACH => ID */
103448   26,  /*       FAIL => ID */
103449   26,  /*        FOR => ID */
103450   26,  /*     IGNORE => ID */
103451   26,  /*  INITIALLY => ID */
103452   26,  /*    INSTEAD => ID */
103453   26,  /*    LIKE_KW => ID */
103454   26,  /*      MATCH => ID */
103455   26,  /*         NO => ID */
103456   26,  /*        KEY => ID */
103457   26,  /*         OF => ID */
103458   26,  /*     OFFSET => ID */
103459   26,  /*     PRAGMA => ID */
103460   26,  /*      RAISE => ID */
103461   26,  /*    REPLACE => ID */
103462   26,  /*   RESTRICT => ID */
103463   26,  /*        ROW => ID */
103464   26,  /*    TRIGGER => ID */
103465   26,  /*     VACUUM => ID */
103466   26,  /*       VIEW => ID */
103467   26,  /*    VIRTUAL => ID */
103468   26,  /*    REINDEX => ID */
103469   26,  /*     RENAME => ID */
103470   26,  /*   CTIME_KW => ID */
103471};
103472#endif /* YYFALLBACK */
103473
103474/* The following structure represents a single element of the
103475** parser's stack.  Information stored includes:
103476**
103477**   +  The state number for the parser at this level of the stack.
103478**
103479**   +  The value of the token stored at this level of the stack.
103480**      (In other words, the "major" token.)
103481**
103482**   +  The semantic value stored at this level of the stack.  This is
103483**      the information used by the action routines in the grammar.
103484**      It is sometimes called the "minor" token.
103485*/
103486struct yyStackEntry {
103487  YYACTIONTYPE stateno;  /* The state-number */
103488  YYCODETYPE major;      /* The major token value.  This is the code
103489                         ** number for the token at this stack level */
103490  YYMINORTYPE minor;     /* The user-supplied minor token value.  This
103491                         ** is the value of the token  */
103492};
103493typedef struct yyStackEntry yyStackEntry;
103494
103495/* The state of the parser is completely contained in an instance of
103496** the following structure */
103497struct yyParser {
103498  int yyidx;                    /* Index of top element in stack */
103499#ifdef YYTRACKMAXSTACKDEPTH
103500  int yyidxMax;                 /* Maximum value of yyidx */
103501#endif
103502  int yyerrcnt;                 /* Shifts left before out of the error */
103503  sqlite3ParserARG_SDECL                /* A place to hold %extra_argument */
103504#if YYSTACKDEPTH<=0
103505  int yystksz;                  /* Current side of the stack */
103506  yyStackEntry *yystack;        /* The parser's stack */
103507#else
103508  yyStackEntry yystack[YYSTACKDEPTH];  /* The parser's stack */
103509#endif
103510};
103511typedef struct yyParser yyParser;
103512
103513#ifndef NDEBUG
103514static FILE *yyTraceFILE = 0;
103515static char *yyTracePrompt = 0;
103516#endif /* NDEBUG */
103517
103518#ifndef NDEBUG
103519/*
103520** Turn parser tracing on by giving a stream to which to write the trace
103521** and a prompt to preface each trace message.  Tracing is turned off
103522** by making either argument NULL
103523**
103524** Inputs:
103525** <ul>
103526** <li> A FILE* to which trace output should be written.
103527**      If NULL, then tracing is turned off.
103528** <li> A prefix string written at the beginning of every
103529**      line of trace output.  If NULL, then tracing is
103530**      turned off.
103531** </ul>
103532**
103533** Outputs:
103534** None.
103535*/
103536SQLITE_PRIVATE void sqlite3ParserTrace(FILE *TraceFILE, char *zTracePrompt){
103537  yyTraceFILE = TraceFILE;
103538  yyTracePrompt = zTracePrompt;
103539  if( yyTraceFILE==0 ) yyTracePrompt = 0;
103540  else if( yyTracePrompt==0 ) yyTraceFILE = 0;
103541}
103542#endif /* NDEBUG */
103543
103544#ifndef NDEBUG
103545/* For tracing shifts, the names of all terminals and nonterminals
103546** are required.  The following table supplies these names */
103547static const char *const yyTokenName[] = {
103548  "$",             "SEMI",          "EXPLAIN",       "QUERY",
103549  "PLAN",          "BEGIN",         "TRANSACTION",   "DEFERRED",
103550  "IMMEDIATE",     "EXCLUSIVE",     "COMMIT",        "END",
103551  "ROLLBACK",      "SAVEPOINT",     "RELEASE",       "TO",
103552  "TABLE",         "CREATE",        "IF",            "NOT",
103553  "EXISTS",        "TEMP",          "LP",            "RP",
103554  "AS",            "COMMA",         "ID",            "INDEXED",
103555  "ABORT",         "ACTION",        "AFTER",         "ANALYZE",
103556  "ASC",           "ATTACH",        "BEFORE",        "BY",
103557  "CASCADE",       "CAST",          "COLUMNKW",      "CONFLICT",
103558  "DATABASE",      "DESC",          "DETACH",        "EACH",
103559  "FAIL",          "FOR",           "IGNORE",        "INITIALLY",
103560  "INSTEAD",       "LIKE_KW",       "MATCH",         "NO",
103561  "KEY",           "OF",            "OFFSET",        "PRAGMA",
103562  "RAISE",         "REPLACE",       "RESTRICT",      "ROW",
103563  "TRIGGER",       "VACUUM",        "VIEW",          "VIRTUAL",
103564  "REINDEX",       "RENAME",        "CTIME_KW",      "ANY",
103565  "OR",            "AND",           "IS",            "BETWEEN",
103566  "IN",            "ISNULL",        "NOTNULL",       "NE",
103567  "EQ",            "GT",            "LE",            "LT",
103568  "GE",            "ESCAPE",        "BITAND",        "BITOR",
103569  "LSHIFT",        "RSHIFT",        "PLUS",          "MINUS",
103570  "STAR",          "SLASH",         "REM",           "CONCAT",
103571  "COLLATE",       "BITNOT",        "STRING",        "JOIN_KW",
103572  "CONSTRAINT",    "DEFAULT",       "NULL",          "PRIMARY",
103573  "UNIQUE",        "CHECK",         "REFERENCES",    "AUTOINCR",
103574  "ON",            "INSERT",        "DELETE",        "UPDATE",
103575  "SET",           "DEFERRABLE",    "FOREIGN",       "DROP",
103576  "UNION",         "ALL",           "EXCEPT",        "INTERSECT",
103577  "SELECT",        "DISTINCT",      "DOT",           "FROM",
103578  "JOIN",          "USING",         "ORDER",         "GROUP",
103579  "HAVING",        "LIMIT",         "WHERE",         "INTO",
103580  "VALUES",        "INTEGER",       "FLOAT",         "BLOB",
103581  "REGISTER",      "VARIABLE",      "CASE",          "WHEN",
103582  "THEN",          "ELSE",          "INDEX",         "ALTER",
103583  "ADD",           "error",         "input",         "cmdlist",
103584  "ecmd",          "explain",       "cmdx",          "cmd",
103585  "transtype",     "trans_opt",     "nm",            "savepoint_opt",
103586  "create_table",  "create_table_args",  "createkw",      "temp",
103587  "ifnotexists",   "dbnm",          "columnlist",    "conslist_opt",
103588  "select",        "column",        "columnid",      "type",
103589  "carglist",      "id",            "ids",           "typetoken",
103590  "typename",      "signed",        "plus_num",      "minus_num",
103591  "carg",          "ccons",         "term",          "expr",
103592  "onconf",        "sortorder",     "autoinc",       "idxlist_opt",
103593  "refargs",       "defer_subclause",  "refarg",        "refact",
103594  "init_deferred_pred_opt",  "conslist",      "tcons",         "idxlist",
103595  "defer_subclause_opt",  "orconf",        "resolvetype",   "raisetype",
103596  "ifexists",      "fullname",      "oneselect",     "multiselect_op",
103597  "distinct",      "selcollist",    "from",          "where_opt",
103598  "groupby_opt",   "having_opt",    "orderby_opt",   "limit_opt",
103599  "sclp",          "as",            "seltablist",    "stl_prefix",
103600  "joinop",        "indexed_opt",   "on_opt",        "using_opt",
103601  "joinop2",       "inscollist",    "sortlist",      "sortitem",
103602  "nexprlist",     "setlist",       "insert_cmd",    "inscollist_opt",
103603  "itemlist",      "exprlist",      "likeop",        "between_op",
103604  "in_op",         "case_operand",  "case_exprlist",  "case_else",
103605  "uniqueflag",    "collate",       "nmnum",         "plus_opt",
103606  "number",        "trigger_decl",  "trigger_cmd_list",  "trigger_time",
103607  "trigger_event",  "foreach_clause",  "when_clause",   "trigger_cmd",
103608  "trnm",          "tridxby",       "database_kw_opt",  "key_opt",
103609  "add_column_fullname",  "kwcolumn_opt",  "create_vtab",   "vtabarglist",
103610  "vtabarg",       "vtabargtoken",  "lp",            "anylist",
103611};
103612#endif /* NDEBUG */
103613
103614#ifndef NDEBUG
103615/* For tracing reduce actions, the names of all rules are required.
103616*/
103617static const char *const yyRuleName[] = {
103618 /*   0 */ "input ::= cmdlist",
103619 /*   1 */ "cmdlist ::= cmdlist ecmd",
103620 /*   2 */ "cmdlist ::= ecmd",
103621 /*   3 */ "ecmd ::= SEMI",
103622 /*   4 */ "ecmd ::= explain cmdx SEMI",
103623 /*   5 */ "explain ::=",
103624 /*   6 */ "explain ::= EXPLAIN",
103625 /*   7 */ "explain ::= EXPLAIN QUERY PLAN",
103626 /*   8 */ "cmdx ::= cmd",
103627 /*   9 */ "cmd ::= BEGIN transtype trans_opt",
103628 /*  10 */ "trans_opt ::=",
103629 /*  11 */ "trans_opt ::= TRANSACTION",
103630 /*  12 */ "trans_opt ::= TRANSACTION nm",
103631 /*  13 */ "transtype ::=",
103632 /*  14 */ "transtype ::= DEFERRED",
103633 /*  15 */ "transtype ::= IMMEDIATE",
103634 /*  16 */ "transtype ::= EXCLUSIVE",
103635 /*  17 */ "cmd ::= COMMIT trans_opt",
103636 /*  18 */ "cmd ::= END trans_opt",
103637 /*  19 */ "cmd ::= ROLLBACK trans_opt",
103638 /*  20 */ "savepoint_opt ::= SAVEPOINT",
103639 /*  21 */ "savepoint_opt ::=",
103640 /*  22 */ "cmd ::= SAVEPOINT nm",
103641 /*  23 */ "cmd ::= RELEASE savepoint_opt nm",
103642 /*  24 */ "cmd ::= ROLLBACK trans_opt TO savepoint_opt nm",
103643 /*  25 */ "cmd ::= create_table create_table_args",
103644 /*  26 */ "create_table ::= createkw temp TABLE ifnotexists nm dbnm",
103645 /*  27 */ "createkw ::= CREATE",
103646 /*  28 */ "ifnotexists ::=",
103647 /*  29 */ "ifnotexists ::= IF NOT EXISTS",
103648 /*  30 */ "temp ::= TEMP",
103649 /*  31 */ "temp ::=",
103650 /*  32 */ "create_table_args ::= LP columnlist conslist_opt RP",
103651 /*  33 */ "create_table_args ::= AS select",
103652 /*  34 */ "columnlist ::= columnlist COMMA column",
103653 /*  35 */ "columnlist ::= column",
103654 /*  36 */ "column ::= columnid type carglist",
103655 /*  37 */ "columnid ::= nm",
103656 /*  38 */ "id ::= ID",
103657 /*  39 */ "id ::= INDEXED",
103658 /*  40 */ "ids ::= ID|STRING",
103659 /*  41 */ "nm ::= id",
103660 /*  42 */ "nm ::= STRING",
103661 /*  43 */ "nm ::= JOIN_KW",
103662 /*  44 */ "type ::=",
103663 /*  45 */ "type ::= typetoken",
103664 /*  46 */ "typetoken ::= typename",
103665 /*  47 */ "typetoken ::= typename LP signed RP",
103666 /*  48 */ "typetoken ::= typename LP signed COMMA signed RP",
103667 /*  49 */ "typename ::= ids",
103668 /*  50 */ "typename ::= typename ids",
103669 /*  51 */ "signed ::= plus_num",
103670 /*  52 */ "signed ::= minus_num",
103671 /*  53 */ "carglist ::= carglist carg",
103672 /*  54 */ "carglist ::=",
103673 /*  55 */ "carg ::= CONSTRAINT nm ccons",
103674 /*  56 */ "carg ::= ccons",
103675 /*  57 */ "ccons ::= DEFAULT term",
103676 /*  58 */ "ccons ::= DEFAULT LP expr RP",
103677 /*  59 */ "ccons ::= DEFAULT PLUS term",
103678 /*  60 */ "ccons ::= DEFAULT MINUS term",
103679 /*  61 */ "ccons ::= DEFAULT id",
103680 /*  62 */ "ccons ::= NULL onconf",
103681 /*  63 */ "ccons ::= NOT NULL onconf",
103682 /*  64 */ "ccons ::= PRIMARY KEY sortorder onconf autoinc",
103683 /*  65 */ "ccons ::= UNIQUE onconf",
103684 /*  66 */ "ccons ::= CHECK LP expr RP",
103685 /*  67 */ "ccons ::= REFERENCES nm idxlist_opt refargs",
103686 /*  68 */ "ccons ::= defer_subclause",
103687 /*  69 */ "ccons ::= COLLATE ids",
103688 /*  70 */ "autoinc ::=",
103689 /*  71 */ "autoinc ::= AUTOINCR",
103690 /*  72 */ "refargs ::=",
103691 /*  73 */ "refargs ::= refargs refarg",
103692 /*  74 */ "refarg ::= MATCH nm",
103693 /*  75 */ "refarg ::= ON INSERT refact",
103694 /*  76 */ "refarg ::= ON DELETE refact",
103695 /*  77 */ "refarg ::= ON UPDATE refact",
103696 /*  78 */ "refact ::= SET NULL",
103697 /*  79 */ "refact ::= SET DEFAULT",
103698 /*  80 */ "refact ::= CASCADE",
103699 /*  81 */ "refact ::= RESTRICT",
103700 /*  82 */ "refact ::= NO ACTION",
103701 /*  83 */ "defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt",
103702 /*  84 */ "defer_subclause ::= DEFERRABLE init_deferred_pred_opt",
103703 /*  85 */ "init_deferred_pred_opt ::=",
103704 /*  86 */ "init_deferred_pred_opt ::= INITIALLY DEFERRED",
103705 /*  87 */ "init_deferred_pred_opt ::= INITIALLY IMMEDIATE",
103706 /*  88 */ "conslist_opt ::=",
103707 /*  89 */ "conslist_opt ::= COMMA conslist",
103708 /*  90 */ "conslist ::= conslist COMMA tcons",
103709 /*  91 */ "conslist ::= conslist tcons",
103710 /*  92 */ "conslist ::= tcons",
103711 /*  93 */ "tcons ::= CONSTRAINT nm",
103712 /*  94 */ "tcons ::= PRIMARY KEY LP idxlist autoinc RP onconf",
103713 /*  95 */ "tcons ::= UNIQUE LP idxlist RP onconf",
103714 /*  96 */ "tcons ::= CHECK LP expr RP onconf",
103715 /*  97 */ "tcons ::= FOREIGN KEY LP idxlist RP REFERENCES nm idxlist_opt refargs defer_subclause_opt",
103716 /*  98 */ "defer_subclause_opt ::=",
103717 /*  99 */ "defer_subclause_opt ::= defer_subclause",
103718 /* 100 */ "onconf ::=",
103719 /* 101 */ "onconf ::= ON CONFLICT resolvetype",
103720 /* 102 */ "orconf ::=",
103721 /* 103 */ "orconf ::= OR resolvetype",
103722 /* 104 */ "resolvetype ::= raisetype",
103723 /* 105 */ "resolvetype ::= IGNORE",
103724 /* 106 */ "resolvetype ::= REPLACE",
103725 /* 107 */ "cmd ::= DROP TABLE ifexists fullname",
103726 /* 108 */ "ifexists ::= IF EXISTS",
103727 /* 109 */ "ifexists ::=",
103728 /* 110 */ "cmd ::= createkw temp VIEW ifnotexists nm dbnm AS select",
103729 /* 111 */ "cmd ::= DROP VIEW ifexists fullname",
103730 /* 112 */ "cmd ::= select",
103731 /* 113 */ "select ::= oneselect",
103732 /* 114 */ "select ::= select multiselect_op oneselect",
103733 /* 115 */ "multiselect_op ::= UNION",
103734 /* 116 */ "multiselect_op ::= UNION ALL",
103735 /* 117 */ "multiselect_op ::= EXCEPT|INTERSECT",
103736 /* 118 */ "oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt",
103737 /* 119 */ "distinct ::= DISTINCT",
103738 /* 120 */ "distinct ::= ALL",
103739 /* 121 */ "distinct ::=",
103740 /* 122 */ "sclp ::= selcollist COMMA",
103741 /* 123 */ "sclp ::=",
103742 /* 124 */ "selcollist ::= sclp expr as",
103743 /* 125 */ "selcollist ::= sclp STAR",
103744 /* 126 */ "selcollist ::= sclp nm DOT STAR",
103745 /* 127 */ "as ::= AS nm",
103746 /* 128 */ "as ::= ids",
103747 /* 129 */ "as ::=",
103748 /* 130 */ "from ::=",
103749 /* 131 */ "from ::= FROM seltablist",
103750 /* 132 */ "stl_prefix ::= seltablist joinop",
103751 /* 133 */ "stl_prefix ::=",
103752 /* 134 */ "seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt",
103753 /* 135 */ "seltablist ::= stl_prefix LP select RP as on_opt using_opt",
103754 /* 136 */ "seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt",
103755 /* 137 */ "dbnm ::=",
103756 /* 138 */ "dbnm ::= DOT nm",
103757 /* 139 */ "fullname ::= nm dbnm",
103758 /* 140 */ "joinop ::= COMMA|JOIN",
103759 /* 141 */ "joinop ::= JOIN_KW JOIN",
103760 /* 142 */ "joinop ::= JOIN_KW nm JOIN",
103761 /* 143 */ "joinop ::= JOIN_KW nm nm JOIN",
103762 /* 144 */ "on_opt ::= ON expr",
103763 /* 145 */ "on_opt ::=",
103764 /* 146 */ "indexed_opt ::=",
103765 /* 147 */ "indexed_opt ::= INDEXED BY nm",
103766 /* 148 */ "indexed_opt ::= NOT INDEXED",
103767 /* 149 */ "using_opt ::= USING LP inscollist RP",
103768 /* 150 */ "using_opt ::=",
103769 /* 151 */ "orderby_opt ::=",
103770 /* 152 */ "orderby_opt ::= ORDER BY sortlist",
103771 /* 153 */ "sortlist ::= sortlist COMMA sortitem sortorder",
103772 /* 154 */ "sortlist ::= sortitem sortorder",
103773 /* 155 */ "sortitem ::= expr",
103774 /* 156 */ "sortorder ::= ASC",
103775 /* 157 */ "sortorder ::= DESC",
103776 /* 158 */ "sortorder ::=",
103777 /* 159 */ "groupby_opt ::=",
103778 /* 160 */ "groupby_opt ::= GROUP BY nexprlist",
103779 /* 161 */ "having_opt ::=",
103780 /* 162 */ "having_opt ::= HAVING expr",
103781 /* 163 */ "limit_opt ::=",
103782 /* 164 */ "limit_opt ::= LIMIT expr",
103783 /* 165 */ "limit_opt ::= LIMIT expr OFFSET expr",
103784 /* 166 */ "limit_opt ::= LIMIT expr COMMA expr",
103785 /* 167 */ "cmd ::= DELETE FROM fullname indexed_opt where_opt",
103786 /* 168 */ "where_opt ::=",
103787 /* 169 */ "where_opt ::= WHERE expr",
103788 /* 170 */ "cmd ::= UPDATE orconf fullname indexed_opt SET setlist where_opt",
103789 /* 171 */ "setlist ::= setlist COMMA nm EQ expr",
103790 /* 172 */ "setlist ::= nm EQ expr",
103791 /* 173 */ "cmd ::= insert_cmd INTO fullname inscollist_opt VALUES LP itemlist RP",
103792 /* 174 */ "cmd ::= insert_cmd INTO fullname inscollist_opt select",
103793 /* 175 */ "cmd ::= insert_cmd INTO fullname inscollist_opt DEFAULT VALUES",
103794 /* 176 */ "insert_cmd ::= INSERT orconf",
103795 /* 177 */ "insert_cmd ::= REPLACE",
103796 /* 178 */ "itemlist ::= itemlist COMMA expr",
103797 /* 179 */ "itemlist ::= expr",
103798 /* 180 */ "inscollist_opt ::=",
103799 /* 181 */ "inscollist_opt ::= LP inscollist RP",
103800 /* 182 */ "inscollist ::= inscollist COMMA nm",
103801 /* 183 */ "inscollist ::= nm",
103802 /* 184 */ "expr ::= term",
103803 /* 185 */ "expr ::= LP expr RP",
103804 /* 186 */ "term ::= NULL",
103805 /* 187 */ "expr ::= id",
103806 /* 188 */ "expr ::= JOIN_KW",
103807 /* 189 */ "expr ::= nm DOT nm",
103808 /* 190 */ "expr ::= nm DOT nm DOT nm",
103809 /* 191 */ "term ::= INTEGER|FLOAT|BLOB",
103810 /* 192 */ "term ::= STRING",
103811 /* 193 */ "expr ::= REGISTER",
103812 /* 194 */ "expr ::= VARIABLE",
103813 /* 195 */ "expr ::= expr COLLATE ids",
103814 /* 196 */ "expr ::= CAST LP expr AS typetoken RP",
103815 /* 197 */ "expr ::= ID LP distinct exprlist RP",
103816 /* 198 */ "expr ::= ID LP STAR RP",
103817 /* 199 */ "term ::= CTIME_KW",
103818 /* 200 */ "expr ::= expr AND expr",
103819 /* 201 */ "expr ::= expr OR expr",
103820 /* 202 */ "expr ::= expr LT|GT|GE|LE expr",
103821 /* 203 */ "expr ::= expr EQ|NE expr",
103822 /* 204 */ "expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr",
103823 /* 205 */ "expr ::= expr PLUS|MINUS expr",
103824 /* 206 */ "expr ::= expr STAR|SLASH|REM expr",
103825 /* 207 */ "expr ::= expr CONCAT expr",
103826 /* 208 */ "likeop ::= LIKE_KW",
103827 /* 209 */ "likeop ::= NOT LIKE_KW",
103828 /* 210 */ "likeop ::= MATCH",
103829 /* 211 */ "likeop ::= NOT MATCH",
103830 /* 212 */ "expr ::= expr likeop expr",
103831 /* 213 */ "expr ::= expr likeop expr ESCAPE expr",
103832 /* 214 */ "expr ::= expr ISNULL|NOTNULL",
103833 /* 215 */ "expr ::= expr NOT NULL",
103834 /* 216 */ "expr ::= expr IS expr",
103835 /* 217 */ "expr ::= expr IS NOT expr",
103836 /* 218 */ "expr ::= NOT expr",
103837 /* 219 */ "expr ::= BITNOT expr",
103838 /* 220 */ "expr ::= MINUS expr",
103839 /* 221 */ "expr ::= PLUS expr",
103840 /* 222 */ "between_op ::= BETWEEN",
103841 /* 223 */ "between_op ::= NOT BETWEEN",
103842 /* 224 */ "expr ::= expr between_op expr AND expr",
103843 /* 225 */ "in_op ::= IN",
103844 /* 226 */ "in_op ::= NOT IN",
103845 /* 227 */ "expr ::= expr in_op LP exprlist RP",
103846 /* 228 */ "expr ::= LP select RP",
103847 /* 229 */ "expr ::= expr in_op LP select RP",
103848 /* 230 */ "expr ::= expr in_op nm dbnm",
103849 /* 231 */ "expr ::= EXISTS LP select RP",
103850 /* 232 */ "expr ::= CASE case_operand case_exprlist case_else END",
103851 /* 233 */ "case_exprlist ::= case_exprlist WHEN expr THEN expr",
103852 /* 234 */ "case_exprlist ::= WHEN expr THEN expr",
103853 /* 235 */ "case_else ::= ELSE expr",
103854 /* 236 */ "case_else ::=",
103855 /* 237 */ "case_operand ::= expr",
103856 /* 238 */ "case_operand ::=",
103857 /* 239 */ "exprlist ::= nexprlist",
103858 /* 240 */ "exprlist ::=",
103859 /* 241 */ "nexprlist ::= nexprlist COMMA expr",
103860 /* 242 */ "nexprlist ::= expr",
103861 /* 243 */ "cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP idxlist RP",
103862 /* 244 */ "uniqueflag ::= UNIQUE",
103863 /* 245 */ "uniqueflag ::=",
103864 /* 246 */ "idxlist_opt ::=",
103865 /* 247 */ "idxlist_opt ::= LP idxlist RP",
103866 /* 248 */ "idxlist ::= idxlist COMMA nm collate sortorder",
103867 /* 249 */ "idxlist ::= nm collate sortorder",
103868 /* 250 */ "collate ::=",
103869 /* 251 */ "collate ::= COLLATE ids",
103870 /* 252 */ "cmd ::= DROP INDEX ifexists fullname",
103871 /* 253 */ "cmd ::= VACUUM",
103872 /* 254 */ "cmd ::= VACUUM nm",
103873 /* 255 */ "cmd ::= PRAGMA nm dbnm",
103874 /* 256 */ "cmd ::= PRAGMA nm dbnm EQ nmnum",
103875 /* 257 */ "cmd ::= PRAGMA nm dbnm LP nmnum RP",
103876 /* 258 */ "cmd ::= PRAGMA nm dbnm EQ minus_num",
103877 /* 259 */ "cmd ::= PRAGMA nm dbnm LP minus_num RP",
103878 /* 260 */ "nmnum ::= plus_num",
103879 /* 261 */ "nmnum ::= nm",
103880 /* 262 */ "nmnum ::= ON",
103881 /* 263 */ "nmnum ::= DELETE",
103882 /* 264 */ "nmnum ::= DEFAULT",
103883 /* 265 */ "plus_num ::= plus_opt number",
103884 /* 266 */ "minus_num ::= MINUS number",
103885 /* 267 */ "number ::= INTEGER|FLOAT",
103886 /* 268 */ "plus_opt ::= PLUS",
103887 /* 269 */ "plus_opt ::=",
103888 /* 270 */ "cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END",
103889 /* 271 */ "trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause",
103890 /* 272 */ "trigger_time ::= BEFORE",
103891 /* 273 */ "trigger_time ::= AFTER",
103892 /* 274 */ "trigger_time ::= INSTEAD OF",
103893 /* 275 */ "trigger_time ::=",
103894 /* 276 */ "trigger_event ::= DELETE|INSERT",
103895 /* 277 */ "trigger_event ::= UPDATE",
103896 /* 278 */ "trigger_event ::= UPDATE OF inscollist",
103897 /* 279 */ "foreach_clause ::=",
103898 /* 280 */ "foreach_clause ::= FOR EACH ROW",
103899 /* 281 */ "when_clause ::=",
103900 /* 282 */ "when_clause ::= WHEN expr",
103901 /* 283 */ "trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI",
103902 /* 284 */ "trigger_cmd_list ::= trigger_cmd SEMI",
103903 /* 285 */ "trnm ::= nm",
103904 /* 286 */ "trnm ::= nm DOT nm",
103905 /* 287 */ "tridxby ::=",
103906 /* 288 */ "tridxby ::= INDEXED BY nm",
103907 /* 289 */ "tridxby ::= NOT INDEXED",
103908 /* 290 */ "trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist where_opt",
103909 /* 291 */ "trigger_cmd ::= insert_cmd INTO trnm inscollist_opt VALUES LP itemlist RP",
103910 /* 292 */ "trigger_cmd ::= insert_cmd INTO trnm inscollist_opt select",
103911 /* 293 */ "trigger_cmd ::= DELETE FROM trnm tridxby where_opt",
103912 /* 294 */ "trigger_cmd ::= select",
103913 /* 295 */ "expr ::= RAISE LP IGNORE RP",
103914 /* 296 */ "expr ::= RAISE LP raisetype COMMA nm RP",
103915 /* 297 */ "raisetype ::= ROLLBACK",
103916 /* 298 */ "raisetype ::= ABORT",
103917 /* 299 */ "raisetype ::= FAIL",
103918 /* 300 */ "cmd ::= DROP TRIGGER ifexists fullname",
103919 /* 301 */ "cmd ::= ATTACH database_kw_opt expr AS expr key_opt",
103920 /* 302 */ "cmd ::= DETACH database_kw_opt expr",
103921 /* 303 */ "key_opt ::=",
103922 /* 304 */ "key_opt ::= KEY expr",
103923 /* 305 */ "database_kw_opt ::= DATABASE",
103924 /* 306 */ "database_kw_opt ::=",
103925 /* 307 */ "cmd ::= REINDEX",
103926 /* 308 */ "cmd ::= REINDEX nm dbnm",
103927 /* 309 */ "cmd ::= ANALYZE",
103928 /* 310 */ "cmd ::= ANALYZE nm dbnm",
103929 /* 311 */ "cmd ::= ALTER TABLE fullname RENAME TO nm",
103930 /* 312 */ "cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt column",
103931 /* 313 */ "add_column_fullname ::= fullname",
103932 /* 314 */ "kwcolumn_opt ::=",
103933 /* 315 */ "kwcolumn_opt ::= COLUMNKW",
103934 /* 316 */ "cmd ::= create_vtab",
103935 /* 317 */ "cmd ::= create_vtab LP vtabarglist RP",
103936 /* 318 */ "create_vtab ::= createkw VIRTUAL TABLE nm dbnm USING nm",
103937 /* 319 */ "vtabarglist ::= vtabarg",
103938 /* 320 */ "vtabarglist ::= vtabarglist COMMA vtabarg",
103939 /* 321 */ "vtabarg ::=",
103940 /* 322 */ "vtabarg ::= vtabarg vtabargtoken",
103941 /* 323 */ "vtabargtoken ::= ANY",
103942 /* 324 */ "vtabargtoken ::= lp anylist RP",
103943 /* 325 */ "lp ::= LP",
103944 /* 326 */ "anylist ::=",
103945 /* 327 */ "anylist ::= anylist LP anylist RP",
103946 /* 328 */ "anylist ::= anylist ANY",
103947};
103948#endif /* NDEBUG */
103949
103950
103951#if YYSTACKDEPTH<=0
103952/*
103953** Try to increase the size of the parser stack.
103954*/
103955static void yyGrowStack(yyParser *p){
103956  int newSize;
103957  yyStackEntry *pNew;
103958
103959  newSize = p->yystksz*2 + 100;
103960  pNew = realloc(p->yystack, newSize*sizeof(pNew[0]));
103961  if( pNew ){
103962    p->yystack = pNew;
103963    p->yystksz = newSize;
103964#ifndef NDEBUG
103965    if( yyTraceFILE ){
103966      fprintf(yyTraceFILE,"%sStack grows to %d entries!\n",
103967              yyTracePrompt, p->yystksz);
103968    }
103969#endif
103970  }
103971}
103972#endif
103973
103974/*
103975** This function allocates a new parser.
103976** The only argument is a pointer to a function which works like
103977** malloc.
103978**
103979** Inputs:
103980** A pointer to the function used to allocate memory.
103981**
103982** Outputs:
103983** A pointer to a parser.  This pointer is used in subsequent calls
103984** to sqlite3Parser and sqlite3ParserFree.
103985*/
103986SQLITE_PRIVATE void *sqlite3ParserAlloc(void *(*mallocProc)(size_t)){
103987  yyParser *pParser;
103988  pParser = (yyParser*)(*mallocProc)( (size_t)sizeof(yyParser) );
103989  if( pParser ){
103990    pParser->yyidx = -1;
103991#ifdef YYTRACKMAXSTACKDEPTH
103992    pParser->yyidxMax = 0;
103993#endif
103994#if YYSTACKDEPTH<=0
103995    pParser->yystack = NULL;
103996    pParser->yystksz = 0;
103997    yyGrowStack(pParser);
103998#endif
103999  }
104000  return pParser;
104001}
104002
104003/* The following function deletes the value associated with a
104004** symbol.  The symbol can be either a terminal or nonterminal.
104005** "yymajor" is the symbol code, and "yypminor" is a pointer to
104006** the value.
104007*/
104008static void yy_destructor(
104009  yyParser *yypParser,    /* The parser */
104010  YYCODETYPE yymajor,     /* Type code for object to destroy */
104011  YYMINORTYPE *yypminor   /* The object to be destroyed */
104012){
104013  sqlite3ParserARG_FETCH;
104014  switch( yymajor ){
104015    /* Here is inserted the actions which take place when a
104016    ** terminal or non-terminal is destroyed.  This can happen
104017    ** when the symbol is popped from the stack during a
104018    ** reduce or during error processing or when a parser is
104019    ** being destroyed before it is finished parsing.
104020    **
104021    ** Note: during a reduce, the only symbols destroyed are those
104022    ** which appear on the RHS of the rule, but which are not used
104023    ** inside the C code.
104024    */
104025    case 160: /* select */
104026    case 194: /* oneselect */
104027{
104028sqlite3SelectDelete(pParse->db, (yypminor->yy387));
104029}
104030      break;
104031    case 174: /* term */
104032    case 175: /* expr */
104033{
104034sqlite3ExprDelete(pParse->db, (yypminor->yy118).pExpr);
104035}
104036      break;
104037    case 179: /* idxlist_opt */
104038    case 187: /* idxlist */
104039    case 197: /* selcollist */
104040    case 200: /* groupby_opt */
104041    case 202: /* orderby_opt */
104042    case 204: /* sclp */
104043    case 214: /* sortlist */
104044    case 216: /* nexprlist */
104045    case 217: /* setlist */
104046    case 220: /* itemlist */
104047    case 221: /* exprlist */
104048    case 226: /* case_exprlist */
104049{
104050sqlite3ExprListDelete(pParse->db, (yypminor->yy322));
104051}
104052      break;
104053    case 193: /* fullname */
104054    case 198: /* from */
104055    case 206: /* seltablist */
104056    case 207: /* stl_prefix */
104057{
104058sqlite3SrcListDelete(pParse->db, (yypminor->yy259));
104059}
104060      break;
104061    case 199: /* where_opt */
104062    case 201: /* having_opt */
104063    case 210: /* on_opt */
104064    case 215: /* sortitem */
104065    case 225: /* case_operand */
104066    case 227: /* case_else */
104067    case 238: /* when_clause */
104068    case 243: /* key_opt */
104069{
104070sqlite3ExprDelete(pParse->db, (yypminor->yy314));
104071}
104072      break;
104073    case 211: /* using_opt */
104074    case 213: /* inscollist */
104075    case 219: /* inscollist_opt */
104076{
104077sqlite3IdListDelete(pParse->db, (yypminor->yy384));
104078}
104079      break;
104080    case 234: /* trigger_cmd_list */
104081    case 239: /* trigger_cmd */
104082{
104083sqlite3DeleteTriggerStep(pParse->db, (yypminor->yy203));
104084}
104085      break;
104086    case 236: /* trigger_event */
104087{
104088sqlite3IdListDelete(pParse->db, (yypminor->yy90).b);
104089}
104090      break;
104091    default:  break;   /* If no destructor action specified: do nothing */
104092  }
104093}
104094
104095/*
104096** Pop the parser's stack once.
104097**
104098** If there is a destructor routine associated with the token which
104099** is popped from the stack, then call it.
104100**
104101** Return the major token number for the symbol popped.
104102*/
104103static int yy_pop_parser_stack(yyParser *pParser){
104104  YYCODETYPE yymajor;
104105  yyStackEntry *yytos = &pParser->yystack[pParser->yyidx];
104106
104107  /* There is no mechanism by which the parser stack can be popped below
104108  ** empty in SQLite.  */
104109  if( NEVER(pParser->yyidx<0) ) return 0;
104110#ifndef NDEBUG
104111  if( yyTraceFILE && pParser->yyidx>=0 ){
104112    fprintf(yyTraceFILE,"%sPopping %s\n",
104113      yyTracePrompt,
104114      yyTokenName[yytos->major]);
104115  }
104116#endif
104117  yymajor = yytos->major;
104118  yy_destructor(pParser, yymajor, &yytos->minor);
104119  pParser->yyidx--;
104120  return yymajor;
104121}
104122
104123/*
104124** Deallocate and destroy a parser.  Destructors are all called for
104125** all stack elements before shutting the parser down.
104126**
104127** Inputs:
104128** <ul>
104129** <li>  A pointer to the parser.  This should be a pointer
104130**       obtained from sqlite3ParserAlloc.
104131** <li>  A pointer to a function used to reclaim memory obtained
104132**       from malloc.
104133** </ul>
104134*/
104135SQLITE_PRIVATE void sqlite3ParserFree(
104136  void *p,                    /* The parser to be deleted */
104137  void (*freeProc)(void*)     /* Function used to reclaim memory */
104138){
104139  yyParser *pParser = (yyParser*)p;
104140  /* In SQLite, we never try to destroy a parser that was not successfully
104141  ** created in the first place. */
104142  if( NEVER(pParser==0) ) return;
104143  while( pParser->yyidx>=0 ) yy_pop_parser_stack(pParser);
104144#if YYSTACKDEPTH<=0
104145  free(pParser->yystack);
104146#endif
104147  (*freeProc)((void*)pParser);
104148}
104149
104150/*
104151** Return the peak depth of the stack for a parser.
104152*/
104153#ifdef YYTRACKMAXSTACKDEPTH
104154SQLITE_PRIVATE int sqlite3ParserStackPeak(void *p){
104155  yyParser *pParser = (yyParser*)p;
104156  return pParser->yyidxMax;
104157}
104158#endif
104159
104160/*
104161** Find the appropriate action for a parser given the terminal
104162** look-ahead token iLookAhead.
104163**
104164** If the look-ahead token is YYNOCODE, then check to see if the action is
104165** independent of the look-ahead.  If it is, return the action, otherwise
104166** return YY_NO_ACTION.
104167*/
104168static int yy_find_shift_action(
104169  yyParser *pParser,        /* The parser */
104170  YYCODETYPE iLookAhead     /* The look-ahead token */
104171){
104172  int i;
104173  int stateno = pParser->yystack[pParser->yyidx].stateno;
104174
104175  if( stateno>YY_SHIFT_COUNT
104176   || (i = yy_shift_ofst[stateno])==YY_SHIFT_USE_DFLT ){
104177    return yy_default[stateno];
104178  }
104179  assert( iLookAhead!=YYNOCODE );
104180  i += iLookAhead;
104181  if( i<0 || i>=YY_ACTTAB_COUNT || yy_lookahead[i]!=iLookAhead ){
104182    if( iLookAhead>0 ){
104183#ifdef YYFALLBACK
104184      YYCODETYPE iFallback;            /* Fallback token */
104185      if( iLookAhead<sizeof(yyFallback)/sizeof(yyFallback[0])
104186             && (iFallback = yyFallback[iLookAhead])!=0 ){
104187#ifndef NDEBUG
104188        if( yyTraceFILE ){
104189          fprintf(yyTraceFILE, "%sFALLBACK %s => %s\n",
104190             yyTracePrompt, yyTokenName[iLookAhead], yyTokenName[iFallback]);
104191        }
104192#endif
104193        return yy_find_shift_action(pParser, iFallback);
104194      }
104195#endif
104196#ifdef YYWILDCARD
104197      {
104198        int j = i - iLookAhead + YYWILDCARD;
104199        if(
104200#if YY_SHIFT_MIN+YYWILDCARD<0
104201          j>=0 &&
104202#endif
104203#if YY_SHIFT_MAX+YYWILDCARD>=YY_ACTTAB_COUNT
104204          j<YY_ACTTAB_COUNT &&
104205#endif
104206          yy_lookahead[j]==YYWILDCARD
104207        ){
104208#ifndef NDEBUG
104209          if( yyTraceFILE ){
104210            fprintf(yyTraceFILE, "%sWILDCARD %s => %s\n",
104211               yyTracePrompt, yyTokenName[iLookAhead], yyTokenName[YYWILDCARD]);
104212          }
104213#endif /* NDEBUG */
104214          return yy_action[j];
104215        }
104216      }
104217#endif /* YYWILDCARD */
104218    }
104219    return yy_default[stateno];
104220  }else{
104221    return yy_action[i];
104222  }
104223}
104224
104225/*
104226** Find the appropriate action for a parser given the non-terminal
104227** look-ahead token iLookAhead.
104228**
104229** If the look-ahead token is YYNOCODE, then check to see if the action is
104230** independent of the look-ahead.  If it is, return the action, otherwise
104231** return YY_NO_ACTION.
104232*/
104233static int yy_find_reduce_action(
104234  int stateno,              /* Current state number */
104235  YYCODETYPE iLookAhead     /* The look-ahead token */
104236){
104237  int i;
104238#ifdef YYERRORSYMBOL
104239  if( stateno>YY_REDUCE_COUNT ){
104240    return yy_default[stateno];
104241  }
104242#else
104243  assert( stateno<=YY_REDUCE_COUNT );
104244#endif
104245  i = yy_reduce_ofst[stateno];
104246  assert( i!=YY_REDUCE_USE_DFLT );
104247  assert( iLookAhead!=YYNOCODE );
104248  i += iLookAhead;
104249#ifdef YYERRORSYMBOL
104250  if( i<0 || i>=YY_ACTTAB_COUNT || yy_lookahead[i]!=iLookAhead ){
104251    return yy_default[stateno];
104252  }
104253#else
104254  assert( i>=0 && i<YY_ACTTAB_COUNT );
104255  assert( yy_lookahead[i]==iLookAhead );
104256#endif
104257  return yy_action[i];
104258}
104259
104260/*
104261** The following routine is called if the stack overflows.
104262*/
104263static void yyStackOverflow(yyParser *yypParser, YYMINORTYPE *yypMinor){
104264   sqlite3ParserARG_FETCH;
104265   yypParser->yyidx--;
104266#ifndef NDEBUG
104267   if( yyTraceFILE ){
104268     fprintf(yyTraceFILE,"%sStack Overflow!\n",yyTracePrompt);
104269   }
104270#endif
104271   while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
104272   /* Here code is inserted which will execute if the parser
104273   ** stack every overflows */
104274
104275  UNUSED_PARAMETER(yypMinor); /* Silence some compiler warnings */
104276  sqlite3ErrorMsg(pParse, "parser stack overflow");
104277  pParse->parseError = 1;
104278   sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument var */
104279}
104280
104281/*
104282** Perform a shift action.
104283*/
104284static void yy_shift(
104285  yyParser *yypParser,          /* The parser to be shifted */
104286  int yyNewState,               /* The new state to shift in */
104287  int yyMajor,                  /* The major token to shift in */
104288  YYMINORTYPE *yypMinor         /* Pointer to the minor token to shift in */
104289){
104290  yyStackEntry *yytos;
104291  yypParser->yyidx++;
104292#ifdef YYTRACKMAXSTACKDEPTH
104293  if( yypParser->yyidx>yypParser->yyidxMax ){
104294    yypParser->yyidxMax = yypParser->yyidx;
104295  }
104296#endif
104297#if YYSTACKDEPTH>0
104298  if( yypParser->yyidx>=YYSTACKDEPTH ){
104299    yyStackOverflow(yypParser, yypMinor);
104300    return;
104301  }
104302#else
104303  if( yypParser->yyidx>=yypParser->yystksz ){
104304    yyGrowStack(yypParser);
104305    if( yypParser->yyidx>=yypParser->yystksz ){
104306      yyStackOverflow(yypParser, yypMinor);
104307      return;
104308    }
104309  }
104310#endif
104311  yytos = &yypParser->yystack[yypParser->yyidx];
104312  yytos->stateno = (YYACTIONTYPE)yyNewState;
104313  yytos->major = (YYCODETYPE)yyMajor;
104314  yytos->minor = *yypMinor;
104315#ifndef NDEBUG
104316  if( yyTraceFILE && yypParser->yyidx>0 ){
104317    int i;
104318    fprintf(yyTraceFILE,"%sShift %d\n",yyTracePrompt,yyNewState);
104319    fprintf(yyTraceFILE,"%sStack:",yyTracePrompt);
104320    for(i=1; i<=yypParser->yyidx; i++)
104321      fprintf(yyTraceFILE," %s",yyTokenName[yypParser->yystack[i].major]);
104322    fprintf(yyTraceFILE,"\n");
104323  }
104324#endif
104325}
104326
104327/* The following table contains information about every rule that
104328** is used during the reduce.
104329*/
104330static const struct {
104331  YYCODETYPE lhs;         /* Symbol on the left-hand side of the rule */
104332  unsigned char nrhs;     /* Number of right-hand side symbols in the rule */
104333} yyRuleInfo[] = {
104334  { 142, 1 },
104335  { 143, 2 },
104336  { 143, 1 },
104337  { 144, 1 },
104338  { 144, 3 },
104339  { 145, 0 },
104340  { 145, 1 },
104341  { 145, 3 },
104342  { 146, 1 },
104343  { 147, 3 },
104344  { 149, 0 },
104345  { 149, 1 },
104346  { 149, 2 },
104347  { 148, 0 },
104348  { 148, 1 },
104349  { 148, 1 },
104350  { 148, 1 },
104351  { 147, 2 },
104352  { 147, 2 },
104353  { 147, 2 },
104354  { 151, 1 },
104355  { 151, 0 },
104356  { 147, 2 },
104357  { 147, 3 },
104358  { 147, 5 },
104359  { 147, 2 },
104360  { 152, 6 },
104361  { 154, 1 },
104362  { 156, 0 },
104363  { 156, 3 },
104364  { 155, 1 },
104365  { 155, 0 },
104366  { 153, 4 },
104367  { 153, 2 },
104368  { 158, 3 },
104369  { 158, 1 },
104370  { 161, 3 },
104371  { 162, 1 },
104372  { 165, 1 },
104373  { 165, 1 },
104374  { 166, 1 },
104375  { 150, 1 },
104376  { 150, 1 },
104377  { 150, 1 },
104378  { 163, 0 },
104379  { 163, 1 },
104380  { 167, 1 },
104381  { 167, 4 },
104382  { 167, 6 },
104383  { 168, 1 },
104384  { 168, 2 },
104385  { 169, 1 },
104386  { 169, 1 },
104387  { 164, 2 },
104388  { 164, 0 },
104389  { 172, 3 },
104390  { 172, 1 },
104391  { 173, 2 },
104392  { 173, 4 },
104393  { 173, 3 },
104394  { 173, 3 },
104395  { 173, 2 },
104396  { 173, 2 },
104397  { 173, 3 },
104398  { 173, 5 },
104399  { 173, 2 },
104400  { 173, 4 },
104401  { 173, 4 },
104402  { 173, 1 },
104403  { 173, 2 },
104404  { 178, 0 },
104405  { 178, 1 },
104406  { 180, 0 },
104407  { 180, 2 },
104408  { 182, 2 },
104409  { 182, 3 },
104410  { 182, 3 },
104411  { 182, 3 },
104412  { 183, 2 },
104413  { 183, 2 },
104414  { 183, 1 },
104415  { 183, 1 },
104416  { 183, 2 },
104417  { 181, 3 },
104418  { 181, 2 },
104419  { 184, 0 },
104420  { 184, 2 },
104421  { 184, 2 },
104422  { 159, 0 },
104423  { 159, 2 },
104424  { 185, 3 },
104425  { 185, 2 },
104426  { 185, 1 },
104427  { 186, 2 },
104428  { 186, 7 },
104429  { 186, 5 },
104430  { 186, 5 },
104431  { 186, 10 },
104432  { 188, 0 },
104433  { 188, 1 },
104434  { 176, 0 },
104435  { 176, 3 },
104436  { 189, 0 },
104437  { 189, 2 },
104438  { 190, 1 },
104439  { 190, 1 },
104440  { 190, 1 },
104441  { 147, 4 },
104442  { 192, 2 },
104443  { 192, 0 },
104444  { 147, 8 },
104445  { 147, 4 },
104446  { 147, 1 },
104447  { 160, 1 },
104448  { 160, 3 },
104449  { 195, 1 },
104450  { 195, 2 },
104451  { 195, 1 },
104452  { 194, 9 },
104453  { 196, 1 },
104454  { 196, 1 },
104455  { 196, 0 },
104456  { 204, 2 },
104457  { 204, 0 },
104458  { 197, 3 },
104459  { 197, 2 },
104460  { 197, 4 },
104461  { 205, 2 },
104462  { 205, 1 },
104463  { 205, 0 },
104464  { 198, 0 },
104465  { 198, 2 },
104466  { 207, 2 },
104467  { 207, 0 },
104468  { 206, 7 },
104469  { 206, 7 },
104470  { 206, 7 },
104471  { 157, 0 },
104472  { 157, 2 },
104473  { 193, 2 },
104474  { 208, 1 },
104475  { 208, 2 },
104476  { 208, 3 },
104477  { 208, 4 },
104478  { 210, 2 },
104479  { 210, 0 },
104480  { 209, 0 },
104481  { 209, 3 },
104482  { 209, 2 },
104483  { 211, 4 },
104484  { 211, 0 },
104485  { 202, 0 },
104486  { 202, 3 },
104487  { 214, 4 },
104488  { 214, 2 },
104489  { 215, 1 },
104490  { 177, 1 },
104491  { 177, 1 },
104492  { 177, 0 },
104493  { 200, 0 },
104494  { 200, 3 },
104495  { 201, 0 },
104496  { 201, 2 },
104497  { 203, 0 },
104498  { 203, 2 },
104499  { 203, 4 },
104500  { 203, 4 },
104501  { 147, 5 },
104502  { 199, 0 },
104503  { 199, 2 },
104504  { 147, 7 },
104505  { 217, 5 },
104506  { 217, 3 },
104507  { 147, 8 },
104508  { 147, 5 },
104509  { 147, 6 },
104510  { 218, 2 },
104511  { 218, 1 },
104512  { 220, 3 },
104513  { 220, 1 },
104514  { 219, 0 },
104515  { 219, 3 },
104516  { 213, 3 },
104517  { 213, 1 },
104518  { 175, 1 },
104519  { 175, 3 },
104520  { 174, 1 },
104521  { 175, 1 },
104522  { 175, 1 },
104523  { 175, 3 },
104524  { 175, 5 },
104525  { 174, 1 },
104526  { 174, 1 },
104527  { 175, 1 },
104528  { 175, 1 },
104529  { 175, 3 },
104530  { 175, 6 },
104531  { 175, 5 },
104532  { 175, 4 },
104533  { 174, 1 },
104534  { 175, 3 },
104535  { 175, 3 },
104536  { 175, 3 },
104537  { 175, 3 },
104538  { 175, 3 },
104539  { 175, 3 },
104540  { 175, 3 },
104541  { 175, 3 },
104542  { 222, 1 },
104543  { 222, 2 },
104544  { 222, 1 },
104545  { 222, 2 },
104546  { 175, 3 },
104547  { 175, 5 },
104548  { 175, 2 },
104549  { 175, 3 },
104550  { 175, 3 },
104551  { 175, 4 },
104552  { 175, 2 },
104553  { 175, 2 },
104554  { 175, 2 },
104555  { 175, 2 },
104556  { 223, 1 },
104557  { 223, 2 },
104558  { 175, 5 },
104559  { 224, 1 },
104560  { 224, 2 },
104561  { 175, 5 },
104562  { 175, 3 },
104563  { 175, 5 },
104564  { 175, 4 },
104565  { 175, 4 },
104566  { 175, 5 },
104567  { 226, 5 },
104568  { 226, 4 },
104569  { 227, 2 },
104570  { 227, 0 },
104571  { 225, 1 },
104572  { 225, 0 },
104573  { 221, 1 },
104574  { 221, 0 },
104575  { 216, 3 },
104576  { 216, 1 },
104577  { 147, 11 },
104578  { 228, 1 },
104579  { 228, 0 },
104580  { 179, 0 },
104581  { 179, 3 },
104582  { 187, 5 },
104583  { 187, 3 },
104584  { 229, 0 },
104585  { 229, 2 },
104586  { 147, 4 },
104587  { 147, 1 },
104588  { 147, 2 },
104589  { 147, 3 },
104590  { 147, 5 },
104591  { 147, 6 },
104592  { 147, 5 },
104593  { 147, 6 },
104594  { 230, 1 },
104595  { 230, 1 },
104596  { 230, 1 },
104597  { 230, 1 },
104598  { 230, 1 },
104599  { 170, 2 },
104600  { 171, 2 },
104601  { 232, 1 },
104602  { 231, 1 },
104603  { 231, 0 },
104604  { 147, 5 },
104605  { 233, 11 },
104606  { 235, 1 },
104607  { 235, 1 },
104608  { 235, 2 },
104609  { 235, 0 },
104610  { 236, 1 },
104611  { 236, 1 },
104612  { 236, 3 },
104613  { 237, 0 },
104614  { 237, 3 },
104615  { 238, 0 },
104616  { 238, 2 },
104617  { 234, 3 },
104618  { 234, 2 },
104619  { 240, 1 },
104620  { 240, 3 },
104621  { 241, 0 },
104622  { 241, 3 },
104623  { 241, 2 },
104624  { 239, 7 },
104625  { 239, 8 },
104626  { 239, 5 },
104627  { 239, 5 },
104628  { 239, 1 },
104629  { 175, 4 },
104630  { 175, 6 },
104631  { 191, 1 },
104632  { 191, 1 },
104633  { 191, 1 },
104634  { 147, 4 },
104635  { 147, 6 },
104636  { 147, 3 },
104637  { 243, 0 },
104638  { 243, 2 },
104639  { 242, 1 },
104640  { 242, 0 },
104641  { 147, 1 },
104642  { 147, 3 },
104643  { 147, 1 },
104644  { 147, 3 },
104645  { 147, 6 },
104646  { 147, 6 },
104647  { 244, 1 },
104648  { 245, 0 },
104649  { 245, 1 },
104650  { 147, 1 },
104651  { 147, 4 },
104652  { 246, 7 },
104653  { 247, 1 },
104654  { 247, 3 },
104655  { 248, 0 },
104656  { 248, 2 },
104657  { 249, 1 },
104658  { 249, 3 },
104659  { 250, 1 },
104660  { 251, 0 },
104661  { 251, 4 },
104662  { 251, 2 },
104663};
104664
104665static void yy_accept(yyParser*);  /* Forward Declaration */
104666
104667/*
104668** Perform a reduce action and the shift that must immediately
104669** follow the reduce.
104670*/
104671static void yy_reduce(
104672  yyParser *yypParser,         /* The parser */
104673  int yyruleno                 /* Number of the rule by which to reduce */
104674){
104675  int yygoto;                     /* The next state */
104676  int yyact;                      /* The next action */
104677  YYMINORTYPE yygotominor;        /* The LHS of the rule reduced */
104678  yyStackEntry *yymsp;            /* The top of the parser's stack */
104679  int yysize;                     /* Amount to pop the stack */
104680  sqlite3ParserARG_FETCH;
104681  yymsp = &yypParser->yystack[yypParser->yyidx];
104682#ifndef NDEBUG
104683  if( yyTraceFILE && yyruleno>=0
104684        && yyruleno<(int)(sizeof(yyRuleName)/sizeof(yyRuleName[0])) ){
104685    fprintf(yyTraceFILE, "%sReduce [%s].\n", yyTracePrompt,
104686      yyRuleName[yyruleno]);
104687  }
104688#endif /* NDEBUG */
104689
104690  /* Silence complaints from purify about yygotominor being uninitialized
104691  ** in some cases when it is copied into the stack after the following
104692  ** switch.  yygotominor is uninitialized when a rule reduces that does
104693  ** not set the value of its left-hand side nonterminal.  Leaving the
104694  ** value of the nonterminal uninitialized is utterly harmless as long
104695  ** as the value is never used.  So really the only thing this code
104696  ** accomplishes is to quieten purify.
104697  **
104698  ** 2007-01-16:  The wireshark project (www.wireshark.org) reports that
104699  ** without this code, their parser segfaults.  I'm not sure what there
104700  ** parser is doing to make this happen.  This is the second bug report
104701  ** from wireshark this week.  Clearly they are stressing Lemon in ways
104702  ** that it has not been previously stressed...  (SQLite ticket #2172)
104703  */
104704  /*memset(&yygotominor, 0, sizeof(yygotominor));*/
104705  yygotominor = yyzerominor;
104706
104707
104708  switch( yyruleno ){
104709  /* Beginning here are the reduction cases.  A typical example
104710  ** follows:
104711  **   case 0:
104712  **  #line <lineno> <grammarfile>
104713  **     { ... }           // User supplied code
104714  **  #line <lineno> <thisfile>
104715  **     break;
104716  */
104717      case 5: /* explain ::= */
104718{ sqlite3BeginParse(pParse, 0); }
104719        break;
104720      case 6: /* explain ::= EXPLAIN */
104721{ sqlite3BeginParse(pParse, 1); }
104722        break;
104723      case 7: /* explain ::= EXPLAIN QUERY PLAN */
104724{ sqlite3BeginParse(pParse, 2); }
104725        break;
104726      case 8: /* cmdx ::= cmd */
104727{ sqlite3FinishCoding(pParse); }
104728        break;
104729      case 9: /* cmd ::= BEGIN transtype trans_opt */
104730{sqlite3BeginTransaction(pParse, yymsp[-1].minor.yy4);}
104731        break;
104732      case 13: /* transtype ::= */
104733{yygotominor.yy4 = TK_DEFERRED;}
104734        break;
104735      case 14: /* transtype ::= DEFERRED */
104736      case 15: /* transtype ::= IMMEDIATE */ yytestcase(yyruleno==15);
104737      case 16: /* transtype ::= EXCLUSIVE */ yytestcase(yyruleno==16);
104738      case 115: /* multiselect_op ::= UNION */ yytestcase(yyruleno==115);
104739      case 117: /* multiselect_op ::= EXCEPT|INTERSECT */ yytestcase(yyruleno==117);
104740{yygotominor.yy4 = yymsp[0].major;}
104741        break;
104742      case 17: /* cmd ::= COMMIT trans_opt */
104743      case 18: /* cmd ::= END trans_opt */ yytestcase(yyruleno==18);
104744{sqlite3CommitTransaction(pParse);}
104745        break;
104746      case 19: /* cmd ::= ROLLBACK trans_opt */
104747{sqlite3RollbackTransaction(pParse);}
104748        break;
104749      case 22: /* cmd ::= SAVEPOINT nm */
104750{
104751  sqlite3Savepoint(pParse, SAVEPOINT_BEGIN, &yymsp[0].minor.yy0);
104752}
104753        break;
104754      case 23: /* cmd ::= RELEASE savepoint_opt nm */
104755{
104756  sqlite3Savepoint(pParse, SAVEPOINT_RELEASE, &yymsp[0].minor.yy0);
104757}
104758        break;
104759      case 24: /* cmd ::= ROLLBACK trans_opt TO savepoint_opt nm */
104760{
104761  sqlite3Savepoint(pParse, SAVEPOINT_ROLLBACK, &yymsp[0].minor.yy0);
104762}
104763        break;
104764      case 26: /* create_table ::= createkw temp TABLE ifnotexists nm dbnm */
104765{
104766   sqlite3StartTable(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,yymsp[-4].minor.yy4,0,0,yymsp[-2].minor.yy4);
104767}
104768        break;
104769      case 27: /* createkw ::= CREATE */
104770{
104771  pParse->db->lookaside.bEnabled = 0;
104772  yygotominor.yy0 = yymsp[0].minor.yy0;
104773}
104774        break;
104775      case 28: /* ifnotexists ::= */
104776      case 31: /* temp ::= */ yytestcase(yyruleno==31);
104777      case 70: /* autoinc ::= */ yytestcase(yyruleno==70);
104778      case 83: /* defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt */ yytestcase(yyruleno==83);
104779      case 85: /* init_deferred_pred_opt ::= */ yytestcase(yyruleno==85);
104780      case 87: /* init_deferred_pred_opt ::= INITIALLY IMMEDIATE */ yytestcase(yyruleno==87);
104781      case 98: /* defer_subclause_opt ::= */ yytestcase(yyruleno==98);
104782      case 109: /* ifexists ::= */ yytestcase(yyruleno==109);
104783      case 120: /* distinct ::= ALL */ yytestcase(yyruleno==120);
104784      case 121: /* distinct ::= */ yytestcase(yyruleno==121);
104785      case 222: /* between_op ::= BETWEEN */ yytestcase(yyruleno==222);
104786      case 225: /* in_op ::= IN */ yytestcase(yyruleno==225);
104787{yygotominor.yy4 = 0;}
104788        break;
104789      case 29: /* ifnotexists ::= IF NOT EXISTS */
104790      case 30: /* temp ::= TEMP */ yytestcase(yyruleno==30);
104791      case 71: /* autoinc ::= AUTOINCR */ yytestcase(yyruleno==71);
104792      case 86: /* init_deferred_pred_opt ::= INITIALLY DEFERRED */ yytestcase(yyruleno==86);
104793      case 108: /* ifexists ::= IF EXISTS */ yytestcase(yyruleno==108);
104794      case 119: /* distinct ::= DISTINCT */ yytestcase(yyruleno==119);
104795      case 223: /* between_op ::= NOT BETWEEN */ yytestcase(yyruleno==223);
104796      case 226: /* in_op ::= NOT IN */ yytestcase(yyruleno==226);
104797{yygotominor.yy4 = 1;}
104798        break;
104799      case 32: /* create_table_args ::= LP columnlist conslist_opt RP */
104800{
104801  sqlite3EndTable(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,0);
104802}
104803        break;
104804      case 33: /* create_table_args ::= AS select */
104805{
104806  sqlite3EndTable(pParse,0,0,yymsp[0].minor.yy387);
104807  sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy387);
104808}
104809        break;
104810      case 36: /* column ::= columnid type carglist */
104811{
104812  yygotominor.yy0.z = yymsp[-2].minor.yy0.z;
104813  yygotominor.yy0.n = (int)(pParse->sLastToken.z-yymsp[-2].minor.yy0.z) + pParse->sLastToken.n;
104814}
104815        break;
104816      case 37: /* columnid ::= nm */
104817{
104818  sqlite3AddColumn(pParse,&yymsp[0].minor.yy0);
104819  yygotominor.yy0 = yymsp[0].minor.yy0;
104820}
104821        break;
104822      case 38: /* id ::= ID */
104823      case 39: /* id ::= INDEXED */ yytestcase(yyruleno==39);
104824      case 40: /* ids ::= ID|STRING */ yytestcase(yyruleno==40);
104825      case 41: /* nm ::= id */ yytestcase(yyruleno==41);
104826      case 42: /* nm ::= STRING */ yytestcase(yyruleno==42);
104827      case 43: /* nm ::= JOIN_KW */ yytestcase(yyruleno==43);
104828      case 46: /* typetoken ::= typename */ yytestcase(yyruleno==46);
104829      case 49: /* typename ::= ids */ yytestcase(yyruleno==49);
104830      case 127: /* as ::= AS nm */ yytestcase(yyruleno==127);
104831      case 128: /* as ::= ids */ yytestcase(yyruleno==128);
104832      case 138: /* dbnm ::= DOT nm */ yytestcase(yyruleno==138);
104833      case 147: /* indexed_opt ::= INDEXED BY nm */ yytestcase(yyruleno==147);
104834      case 251: /* collate ::= COLLATE ids */ yytestcase(yyruleno==251);
104835      case 260: /* nmnum ::= plus_num */ yytestcase(yyruleno==260);
104836      case 261: /* nmnum ::= nm */ yytestcase(yyruleno==261);
104837      case 262: /* nmnum ::= ON */ yytestcase(yyruleno==262);
104838      case 263: /* nmnum ::= DELETE */ yytestcase(yyruleno==263);
104839      case 264: /* nmnum ::= DEFAULT */ yytestcase(yyruleno==264);
104840      case 265: /* plus_num ::= plus_opt number */ yytestcase(yyruleno==265);
104841      case 266: /* minus_num ::= MINUS number */ yytestcase(yyruleno==266);
104842      case 267: /* number ::= INTEGER|FLOAT */ yytestcase(yyruleno==267);
104843      case 285: /* trnm ::= nm */ yytestcase(yyruleno==285);
104844{yygotominor.yy0 = yymsp[0].minor.yy0;}
104845        break;
104846      case 45: /* type ::= typetoken */
104847{sqlite3AddColumnType(pParse,&yymsp[0].minor.yy0);}
104848        break;
104849      case 47: /* typetoken ::= typename LP signed RP */
104850{
104851  yygotominor.yy0.z = yymsp[-3].minor.yy0.z;
104852  yygotominor.yy0.n = (int)(&yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-3].minor.yy0.z);
104853}
104854        break;
104855      case 48: /* typetoken ::= typename LP signed COMMA signed RP */
104856{
104857  yygotominor.yy0.z = yymsp[-5].minor.yy0.z;
104858  yygotominor.yy0.n = (int)(&yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-5].minor.yy0.z);
104859}
104860        break;
104861      case 50: /* typename ::= typename ids */
104862{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);}
104863        break;
104864      case 57: /* ccons ::= DEFAULT term */
104865      case 59: /* ccons ::= DEFAULT PLUS term */ yytestcase(yyruleno==59);
104866{sqlite3AddDefaultValue(pParse,&yymsp[0].minor.yy118);}
104867        break;
104868      case 58: /* ccons ::= DEFAULT LP expr RP */
104869{sqlite3AddDefaultValue(pParse,&yymsp[-1].minor.yy118);}
104870        break;
104871      case 60: /* ccons ::= DEFAULT MINUS term */
104872{
104873  ExprSpan v;
104874  v.pExpr = sqlite3PExpr(pParse, TK_UMINUS, yymsp[0].minor.yy118.pExpr, 0, 0);
104875  v.zStart = yymsp[-1].minor.yy0.z;
104876  v.zEnd = yymsp[0].minor.yy118.zEnd;
104877  sqlite3AddDefaultValue(pParse,&v);
104878}
104879        break;
104880      case 61: /* ccons ::= DEFAULT id */
104881{
104882  ExprSpan v;
104883  spanExpr(&v, pParse, TK_STRING, &yymsp[0].minor.yy0);
104884  sqlite3AddDefaultValue(pParse,&v);
104885}
104886        break;
104887      case 63: /* ccons ::= NOT NULL onconf */
104888{sqlite3AddNotNull(pParse, yymsp[0].minor.yy4);}
104889        break;
104890      case 64: /* ccons ::= PRIMARY KEY sortorder onconf autoinc */
104891{sqlite3AddPrimaryKey(pParse,0,yymsp[-1].minor.yy4,yymsp[0].minor.yy4,yymsp[-2].minor.yy4);}
104892        break;
104893      case 65: /* ccons ::= UNIQUE onconf */
104894{sqlite3CreateIndex(pParse,0,0,0,0,yymsp[0].minor.yy4,0,0,0,0);}
104895        break;
104896      case 66: /* ccons ::= CHECK LP expr RP */
104897{sqlite3AddCheckConstraint(pParse,yymsp[-1].minor.yy118.pExpr);}
104898        break;
104899      case 67: /* ccons ::= REFERENCES nm idxlist_opt refargs */
104900{sqlite3CreateForeignKey(pParse,0,&yymsp[-2].minor.yy0,yymsp[-1].minor.yy322,yymsp[0].minor.yy4);}
104901        break;
104902      case 68: /* ccons ::= defer_subclause */
104903{sqlite3DeferForeignKey(pParse,yymsp[0].minor.yy4);}
104904        break;
104905      case 69: /* ccons ::= COLLATE ids */
104906{sqlite3AddCollateType(pParse, &yymsp[0].minor.yy0);}
104907        break;
104908      case 72: /* refargs ::= */
104909{ yygotominor.yy4 = OE_None*0x0101; /* EV: R-19803-45884 */}
104910        break;
104911      case 73: /* refargs ::= refargs refarg */
104912{ yygotominor.yy4 = (yymsp[-1].minor.yy4 & ~yymsp[0].minor.yy215.mask) | yymsp[0].minor.yy215.value; }
104913        break;
104914      case 74: /* refarg ::= MATCH nm */
104915      case 75: /* refarg ::= ON INSERT refact */ yytestcase(yyruleno==75);
104916{ yygotominor.yy215.value = 0;     yygotominor.yy215.mask = 0x000000; }
104917        break;
104918      case 76: /* refarg ::= ON DELETE refact */
104919{ yygotominor.yy215.value = yymsp[0].minor.yy4;     yygotominor.yy215.mask = 0x0000ff; }
104920        break;
104921      case 77: /* refarg ::= ON UPDATE refact */
104922{ yygotominor.yy215.value = yymsp[0].minor.yy4<<8;  yygotominor.yy215.mask = 0x00ff00; }
104923        break;
104924      case 78: /* refact ::= SET NULL */
104925{ yygotominor.yy4 = OE_SetNull;  /* EV: R-33326-45252 */}
104926        break;
104927      case 79: /* refact ::= SET DEFAULT */
104928{ yygotominor.yy4 = OE_SetDflt;  /* EV: R-33326-45252 */}
104929        break;
104930      case 80: /* refact ::= CASCADE */
104931{ yygotominor.yy4 = OE_Cascade;  /* EV: R-33326-45252 */}
104932        break;
104933      case 81: /* refact ::= RESTRICT */
104934{ yygotominor.yy4 = OE_Restrict; /* EV: R-33326-45252 */}
104935        break;
104936      case 82: /* refact ::= NO ACTION */
104937{ yygotominor.yy4 = OE_None;     /* EV: R-33326-45252 */}
104938        break;
104939      case 84: /* defer_subclause ::= DEFERRABLE init_deferred_pred_opt */
104940      case 99: /* defer_subclause_opt ::= defer_subclause */ yytestcase(yyruleno==99);
104941      case 101: /* onconf ::= ON CONFLICT resolvetype */ yytestcase(yyruleno==101);
104942      case 104: /* resolvetype ::= raisetype */ yytestcase(yyruleno==104);
104943{yygotominor.yy4 = yymsp[0].minor.yy4;}
104944        break;
104945      case 88: /* conslist_opt ::= */
104946{yygotominor.yy0.n = 0; yygotominor.yy0.z = 0;}
104947        break;
104948      case 89: /* conslist_opt ::= COMMA conslist */
104949{yygotominor.yy0 = yymsp[-1].minor.yy0;}
104950        break;
104951      case 94: /* tcons ::= PRIMARY KEY LP idxlist autoinc RP onconf */
104952{sqlite3AddPrimaryKey(pParse,yymsp[-3].minor.yy322,yymsp[0].minor.yy4,yymsp[-2].minor.yy4,0);}
104953        break;
104954      case 95: /* tcons ::= UNIQUE LP idxlist RP onconf */
104955{sqlite3CreateIndex(pParse,0,0,0,yymsp[-2].minor.yy322,yymsp[0].minor.yy4,0,0,0,0);}
104956        break;
104957      case 96: /* tcons ::= CHECK LP expr RP onconf */
104958{sqlite3AddCheckConstraint(pParse,yymsp[-2].minor.yy118.pExpr);}
104959        break;
104960      case 97: /* tcons ::= FOREIGN KEY LP idxlist RP REFERENCES nm idxlist_opt refargs defer_subclause_opt */
104961{
104962    sqlite3CreateForeignKey(pParse, yymsp[-6].minor.yy322, &yymsp[-3].minor.yy0, yymsp[-2].minor.yy322, yymsp[-1].minor.yy4);
104963    sqlite3DeferForeignKey(pParse, yymsp[0].minor.yy4);
104964}
104965        break;
104966      case 100: /* onconf ::= */
104967{yygotominor.yy4 = OE_Default;}
104968        break;
104969      case 102: /* orconf ::= */
104970{yygotominor.yy210 = OE_Default;}
104971        break;
104972      case 103: /* orconf ::= OR resolvetype */
104973{yygotominor.yy210 = (u8)yymsp[0].minor.yy4;}
104974        break;
104975      case 105: /* resolvetype ::= IGNORE */
104976{yygotominor.yy4 = OE_Ignore;}
104977        break;
104978      case 106: /* resolvetype ::= REPLACE */
104979{yygotominor.yy4 = OE_Replace;}
104980        break;
104981      case 107: /* cmd ::= DROP TABLE ifexists fullname */
104982{
104983  sqlite3DropTable(pParse, yymsp[0].minor.yy259, 0, yymsp[-1].minor.yy4);
104984}
104985        break;
104986      case 110: /* cmd ::= createkw temp VIEW ifnotexists nm dbnm AS select */
104987{
104988  sqlite3CreateView(pParse, &yymsp[-7].minor.yy0, &yymsp[-3].minor.yy0, &yymsp[-2].minor.yy0, yymsp[0].minor.yy387, yymsp[-6].minor.yy4, yymsp[-4].minor.yy4);
104989}
104990        break;
104991      case 111: /* cmd ::= DROP VIEW ifexists fullname */
104992{
104993  sqlite3DropTable(pParse, yymsp[0].minor.yy259, 1, yymsp[-1].minor.yy4);
104994}
104995        break;
104996      case 112: /* cmd ::= select */
104997{
104998  SelectDest dest = {SRT_Output, 0, 0, 0, 0};
104999  sqlite3Select(pParse, yymsp[0].minor.yy387, &dest);
105000  sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy387);
105001}
105002        break;
105003      case 113: /* select ::= oneselect */
105004{yygotominor.yy387 = yymsp[0].minor.yy387;}
105005        break;
105006      case 114: /* select ::= select multiselect_op oneselect */
105007{
105008  if( yymsp[0].minor.yy387 ){
105009    yymsp[0].minor.yy387->op = (u8)yymsp[-1].minor.yy4;
105010    yymsp[0].minor.yy387->pPrior = yymsp[-2].minor.yy387;
105011  }else{
105012    sqlite3SelectDelete(pParse->db, yymsp[-2].minor.yy387);
105013  }
105014  yygotominor.yy387 = yymsp[0].minor.yy387;
105015}
105016        break;
105017      case 116: /* multiselect_op ::= UNION ALL */
105018{yygotominor.yy4 = TK_ALL;}
105019        break;
105020      case 118: /* oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt */
105021{
105022  yygotominor.yy387 = sqlite3SelectNew(pParse,yymsp[-6].minor.yy322,yymsp[-5].minor.yy259,yymsp[-4].minor.yy314,yymsp[-3].minor.yy322,yymsp[-2].minor.yy314,yymsp[-1].minor.yy322,yymsp[-7].minor.yy4,yymsp[0].minor.yy292.pLimit,yymsp[0].minor.yy292.pOffset);
105023}
105024        break;
105025      case 122: /* sclp ::= selcollist COMMA */
105026      case 247: /* idxlist_opt ::= LP idxlist RP */ yytestcase(yyruleno==247);
105027{yygotominor.yy322 = yymsp[-1].minor.yy322;}
105028        break;
105029      case 123: /* sclp ::= */
105030      case 151: /* orderby_opt ::= */ yytestcase(yyruleno==151);
105031      case 159: /* groupby_opt ::= */ yytestcase(yyruleno==159);
105032      case 240: /* exprlist ::= */ yytestcase(yyruleno==240);
105033      case 246: /* idxlist_opt ::= */ yytestcase(yyruleno==246);
105034{yygotominor.yy322 = 0;}
105035        break;
105036      case 124: /* selcollist ::= sclp expr as */
105037{
105038   yygotominor.yy322 = sqlite3ExprListAppend(pParse, yymsp[-2].minor.yy322, yymsp[-1].minor.yy118.pExpr);
105039   if( yymsp[0].minor.yy0.n>0 ) sqlite3ExprListSetName(pParse, yygotominor.yy322, &yymsp[0].minor.yy0, 1);
105040   sqlite3ExprListSetSpan(pParse,yygotominor.yy322,&yymsp[-1].minor.yy118);
105041}
105042        break;
105043      case 125: /* selcollist ::= sclp STAR */
105044{
105045  Expr *p = sqlite3Expr(pParse->db, TK_ALL, 0);
105046  yygotominor.yy322 = sqlite3ExprListAppend(pParse, yymsp[-1].minor.yy322, p);
105047}
105048        break;
105049      case 126: /* selcollist ::= sclp nm DOT STAR */
105050{
105051  Expr *pRight = sqlite3PExpr(pParse, TK_ALL, 0, 0, &yymsp[0].minor.yy0);
105052  Expr *pLeft = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
105053  Expr *pDot = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight, 0);
105054  yygotominor.yy322 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy322, pDot);
105055}
105056        break;
105057      case 129: /* as ::= */
105058{yygotominor.yy0.n = 0;}
105059        break;
105060      case 130: /* from ::= */
105061{yygotominor.yy259 = sqlite3DbMallocZero(pParse->db, sizeof(*yygotominor.yy259));}
105062        break;
105063      case 131: /* from ::= FROM seltablist */
105064{
105065  yygotominor.yy259 = yymsp[0].minor.yy259;
105066  sqlite3SrcListShiftJoinType(yygotominor.yy259);
105067}
105068        break;
105069      case 132: /* stl_prefix ::= seltablist joinop */
105070{
105071   yygotominor.yy259 = yymsp[-1].minor.yy259;
105072   if( ALWAYS(yygotominor.yy259 && yygotominor.yy259->nSrc>0) ) yygotominor.yy259->a[yygotominor.yy259->nSrc-1].jointype = (u8)yymsp[0].minor.yy4;
105073}
105074        break;
105075      case 133: /* stl_prefix ::= */
105076{yygotominor.yy259 = 0;}
105077        break;
105078      case 134: /* seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt */
105079{
105080  yygotominor.yy259 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy259,&yymsp[-5].minor.yy0,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,0,yymsp[-1].minor.yy314,yymsp[0].minor.yy384);
105081  sqlite3SrcListIndexedBy(pParse, yygotominor.yy259, &yymsp[-2].minor.yy0);
105082}
105083        break;
105084      case 135: /* seltablist ::= stl_prefix LP select RP as on_opt using_opt */
105085{
105086    yygotominor.yy259 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy259,0,0,&yymsp[-2].minor.yy0,yymsp[-4].minor.yy387,yymsp[-1].minor.yy314,yymsp[0].minor.yy384);
105087  }
105088        break;
105089      case 136: /* seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt */
105090{
105091    if( yymsp[-6].minor.yy259==0 && yymsp[-2].minor.yy0.n==0 && yymsp[-1].minor.yy314==0 && yymsp[0].minor.yy384==0 ){
105092      yygotominor.yy259 = yymsp[-4].minor.yy259;
105093    }else{
105094      Select *pSubquery;
105095      sqlite3SrcListShiftJoinType(yymsp[-4].minor.yy259);
105096      pSubquery = sqlite3SelectNew(pParse,0,yymsp[-4].minor.yy259,0,0,0,0,0,0,0);
105097      yygotominor.yy259 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy259,0,0,&yymsp[-2].minor.yy0,pSubquery,yymsp[-1].minor.yy314,yymsp[0].minor.yy384);
105098    }
105099  }
105100        break;
105101      case 137: /* dbnm ::= */
105102      case 146: /* indexed_opt ::= */ yytestcase(yyruleno==146);
105103{yygotominor.yy0.z=0; yygotominor.yy0.n=0;}
105104        break;
105105      case 139: /* fullname ::= nm dbnm */
105106{yygotominor.yy259 = sqlite3SrcListAppend(pParse->db,0,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0);}
105107        break;
105108      case 140: /* joinop ::= COMMA|JOIN */
105109{ yygotominor.yy4 = JT_INNER; }
105110        break;
105111      case 141: /* joinop ::= JOIN_KW JOIN */
105112{ yygotominor.yy4 = sqlite3JoinType(pParse,&yymsp[-1].minor.yy0,0,0); }
105113        break;
105114      case 142: /* joinop ::= JOIN_KW nm JOIN */
105115{ yygotominor.yy4 = sqlite3JoinType(pParse,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0,0); }
105116        break;
105117      case 143: /* joinop ::= JOIN_KW nm nm JOIN */
105118{ yygotominor.yy4 = sqlite3JoinType(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0); }
105119        break;
105120      case 144: /* on_opt ::= ON expr */
105121      case 155: /* sortitem ::= expr */ yytestcase(yyruleno==155);
105122      case 162: /* having_opt ::= HAVING expr */ yytestcase(yyruleno==162);
105123      case 169: /* where_opt ::= WHERE expr */ yytestcase(yyruleno==169);
105124      case 235: /* case_else ::= ELSE expr */ yytestcase(yyruleno==235);
105125      case 237: /* case_operand ::= expr */ yytestcase(yyruleno==237);
105126{yygotominor.yy314 = yymsp[0].minor.yy118.pExpr;}
105127        break;
105128      case 145: /* on_opt ::= */
105129      case 161: /* having_opt ::= */ yytestcase(yyruleno==161);
105130      case 168: /* where_opt ::= */ yytestcase(yyruleno==168);
105131      case 236: /* case_else ::= */ yytestcase(yyruleno==236);
105132      case 238: /* case_operand ::= */ yytestcase(yyruleno==238);
105133{yygotominor.yy314 = 0;}
105134        break;
105135      case 148: /* indexed_opt ::= NOT INDEXED */
105136{yygotominor.yy0.z=0; yygotominor.yy0.n=1;}
105137        break;
105138      case 149: /* using_opt ::= USING LP inscollist RP */
105139      case 181: /* inscollist_opt ::= LP inscollist RP */ yytestcase(yyruleno==181);
105140{yygotominor.yy384 = yymsp[-1].minor.yy384;}
105141        break;
105142      case 150: /* using_opt ::= */
105143      case 180: /* inscollist_opt ::= */ yytestcase(yyruleno==180);
105144{yygotominor.yy384 = 0;}
105145        break;
105146      case 152: /* orderby_opt ::= ORDER BY sortlist */
105147      case 160: /* groupby_opt ::= GROUP BY nexprlist */ yytestcase(yyruleno==160);
105148      case 239: /* exprlist ::= nexprlist */ yytestcase(yyruleno==239);
105149{yygotominor.yy322 = yymsp[0].minor.yy322;}
105150        break;
105151      case 153: /* sortlist ::= sortlist COMMA sortitem sortorder */
105152{
105153  yygotominor.yy322 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy322,yymsp[-1].minor.yy314);
105154  if( yygotominor.yy322 ) yygotominor.yy322->a[yygotominor.yy322->nExpr-1].sortOrder = (u8)yymsp[0].minor.yy4;
105155}
105156        break;
105157      case 154: /* sortlist ::= sortitem sortorder */
105158{
105159  yygotominor.yy322 = sqlite3ExprListAppend(pParse,0,yymsp[-1].minor.yy314);
105160  if( yygotominor.yy322 && ALWAYS(yygotominor.yy322->a) ) yygotominor.yy322->a[0].sortOrder = (u8)yymsp[0].minor.yy4;
105161}
105162        break;
105163      case 156: /* sortorder ::= ASC */
105164      case 158: /* sortorder ::= */ yytestcase(yyruleno==158);
105165{yygotominor.yy4 = SQLITE_SO_ASC;}
105166        break;
105167      case 157: /* sortorder ::= DESC */
105168{yygotominor.yy4 = SQLITE_SO_DESC;}
105169        break;
105170      case 163: /* limit_opt ::= */
105171{yygotominor.yy292.pLimit = 0; yygotominor.yy292.pOffset = 0;}
105172        break;
105173      case 164: /* limit_opt ::= LIMIT expr */
105174{yygotominor.yy292.pLimit = yymsp[0].minor.yy118.pExpr; yygotominor.yy292.pOffset = 0;}
105175        break;
105176      case 165: /* limit_opt ::= LIMIT expr OFFSET expr */
105177{yygotominor.yy292.pLimit = yymsp[-2].minor.yy118.pExpr; yygotominor.yy292.pOffset = yymsp[0].minor.yy118.pExpr;}
105178        break;
105179      case 166: /* limit_opt ::= LIMIT expr COMMA expr */
105180{yygotominor.yy292.pOffset = yymsp[-2].minor.yy118.pExpr; yygotominor.yy292.pLimit = yymsp[0].minor.yy118.pExpr;}
105181        break;
105182      case 167: /* cmd ::= DELETE FROM fullname indexed_opt where_opt */
105183{
105184  sqlite3SrcListIndexedBy(pParse, yymsp[-2].minor.yy259, &yymsp[-1].minor.yy0);
105185  sqlite3DeleteFrom(pParse,yymsp[-2].minor.yy259,yymsp[0].minor.yy314);
105186}
105187        break;
105188      case 170: /* cmd ::= UPDATE orconf fullname indexed_opt SET setlist where_opt */
105189{
105190  sqlite3SrcListIndexedBy(pParse, yymsp[-4].minor.yy259, &yymsp[-3].minor.yy0);
105191  sqlite3ExprListCheckLength(pParse,yymsp[-1].minor.yy322,"set list");
105192  sqlite3Update(pParse,yymsp[-4].minor.yy259,yymsp[-1].minor.yy322,yymsp[0].minor.yy314,yymsp[-5].minor.yy210);
105193}
105194        break;
105195      case 171: /* setlist ::= setlist COMMA nm EQ expr */
105196{
105197  yygotominor.yy322 = sqlite3ExprListAppend(pParse, yymsp[-4].minor.yy322, yymsp[0].minor.yy118.pExpr);
105198  sqlite3ExprListSetName(pParse, yygotominor.yy322, &yymsp[-2].minor.yy0, 1);
105199}
105200        break;
105201      case 172: /* setlist ::= nm EQ expr */
105202{
105203  yygotominor.yy322 = sqlite3ExprListAppend(pParse, 0, yymsp[0].minor.yy118.pExpr);
105204  sqlite3ExprListSetName(pParse, yygotominor.yy322, &yymsp[-2].minor.yy0, 1);
105205}
105206        break;
105207      case 173: /* cmd ::= insert_cmd INTO fullname inscollist_opt VALUES LP itemlist RP */
105208{sqlite3Insert(pParse, yymsp[-5].minor.yy259, yymsp[-1].minor.yy322, 0, yymsp[-4].minor.yy384, yymsp[-7].minor.yy210);}
105209        break;
105210      case 174: /* cmd ::= insert_cmd INTO fullname inscollist_opt select */
105211{sqlite3Insert(pParse, yymsp[-2].minor.yy259, 0, yymsp[0].minor.yy387, yymsp[-1].minor.yy384, yymsp[-4].minor.yy210);}
105212        break;
105213      case 175: /* cmd ::= insert_cmd INTO fullname inscollist_opt DEFAULT VALUES */
105214{sqlite3Insert(pParse, yymsp[-3].minor.yy259, 0, 0, yymsp[-2].minor.yy384, yymsp[-5].minor.yy210);}
105215        break;
105216      case 176: /* insert_cmd ::= INSERT orconf */
105217{yygotominor.yy210 = yymsp[0].minor.yy210;}
105218        break;
105219      case 177: /* insert_cmd ::= REPLACE */
105220{yygotominor.yy210 = OE_Replace;}
105221        break;
105222      case 178: /* itemlist ::= itemlist COMMA expr */
105223      case 241: /* nexprlist ::= nexprlist COMMA expr */ yytestcase(yyruleno==241);
105224{yygotominor.yy322 = sqlite3ExprListAppend(pParse,yymsp[-2].minor.yy322,yymsp[0].minor.yy118.pExpr);}
105225        break;
105226      case 179: /* itemlist ::= expr */
105227      case 242: /* nexprlist ::= expr */ yytestcase(yyruleno==242);
105228{yygotominor.yy322 = sqlite3ExprListAppend(pParse,0,yymsp[0].minor.yy118.pExpr);}
105229        break;
105230      case 182: /* inscollist ::= inscollist COMMA nm */
105231{yygotominor.yy384 = sqlite3IdListAppend(pParse->db,yymsp[-2].minor.yy384,&yymsp[0].minor.yy0);}
105232        break;
105233      case 183: /* inscollist ::= nm */
105234{yygotominor.yy384 = sqlite3IdListAppend(pParse->db,0,&yymsp[0].minor.yy0);}
105235        break;
105236      case 184: /* expr ::= term */
105237{yygotominor.yy118 = yymsp[0].minor.yy118;}
105238        break;
105239      case 185: /* expr ::= LP expr RP */
105240{yygotominor.yy118.pExpr = yymsp[-1].minor.yy118.pExpr; spanSet(&yygotominor.yy118,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0);}
105241        break;
105242      case 186: /* term ::= NULL */
105243      case 191: /* term ::= INTEGER|FLOAT|BLOB */ yytestcase(yyruleno==191);
105244      case 192: /* term ::= STRING */ yytestcase(yyruleno==192);
105245{spanExpr(&yygotominor.yy118, pParse, yymsp[0].major, &yymsp[0].minor.yy0);}
105246        break;
105247      case 187: /* expr ::= id */
105248      case 188: /* expr ::= JOIN_KW */ yytestcase(yyruleno==188);
105249{spanExpr(&yygotominor.yy118, pParse, TK_ID, &yymsp[0].minor.yy0);}
105250        break;
105251      case 189: /* expr ::= nm DOT nm */
105252{
105253  Expr *temp1 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
105254  Expr *temp2 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[0].minor.yy0);
105255  yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_DOT, temp1, temp2, 0);
105256  spanSet(&yygotominor.yy118,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0);
105257}
105258        break;
105259      case 190: /* expr ::= nm DOT nm DOT nm */
105260{
105261  Expr *temp1 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-4].minor.yy0);
105262  Expr *temp2 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
105263  Expr *temp3 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[0].minor.yy0);
105264  Expr *temp4 = sqlite3PExpr(pParse, TK_DOT, temp2, temp3, 0);
105265  yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_DOT, temp1, temp4, 0);
105266  spanSet(&yygotominor.yy118,&yymsp[-4].minor.yy0,&yymsp[0].minor.yy0);
105267}
105268        break;
105269      case 193: /* expr ::= REGISTER */
105270{
105271  /* When doing a nested parse, one can include terms in an expression
105272  ** that look like this:   #1 #2 ...  These terms refer to registers
105273  ** in the virtual machine.  #N is the N-th register. */
105274  if( pParse->nested==0 ){
105275    sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &yymsp[0].minor.yy0);
105276    yygotominor.yy118.pExpr = 0;
105277  }else{
105278    yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_REGISTER, 0, 0, &yymsp[0].minor.yy0);
105279    if( yygotominor.yy118.pExpr ) sqlite3GetInt32(&yymsp[0].minor.yy0.z[1], &yygotominor.yy118.pExpr->iTable);
105280  }
105281  spanSet(&yygotominor.yy118, &yymsp[0].minor.yy0, &yymsp[0].minor.yy0);
105282}
105283        break;
105284      case 194: /* expr ::= VARIABLE */
105285{
105286  spanExpr(&yygotominor.yy118, pParse, TK_VARIABLE, &yymsp[0].minor.yy0);
105287  sqlite3ExprAssignVarNumber(pParse, yygotominor.yy118.pExpr);
105288  spanSet(&yygotominor.yy118, &yymsp[0].minor.yy0, &yymsp[0].minor.yy0);
105289}
105290        break;
105291      case 195: /* expr ::= expr COLLATE ids */
105292{
105293  yygotominor.yy118.pExpr = sqlite3ExprSetCollByToken(pParse, yymsp[-2].minor.yy118.pExpr, &yymsp[0].minor.yy0);
105294  yygotominor.yy118.zStart = yymsp[-2].minor.yy118.zStart;
105295  yygotominor.yy118.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
105296}
105297        break;
105298      case 196: /* expr ::= CAST LP expr AS typetoken RP */
105299{
105300  yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_CAST, yymsp[-3].minor.yy118.pExpr, 0, &yymsp[-1].minor.yy0);
105301  spanSet(&yygotominor.yy118,&yymsp[-5].minor.yy0,&yymsp[0].minor.yy0);
105302}
105303        break;
105304      case 197: /* expr ::= ID LP distinct exprlist RP */
105305{
105306  if( yymsp[-1].minor.yy322 && yymsp[-1].minor.yy322->nExpr>pParse->db->aLimit[SQLITE_LIMIT_FUNCTION_ARG] ){
105307    sqlite3ErrorMsg(pParse, "too many arguments on function %T", &yymsp[-4].minor.yy0);
105308  }
105309  yygotominor.yy118.pExpr = sqlite3ExprFunction(pParse, yymsp[-1].minor.yy322, &yymsp[-4].minor.yy0);
105310  spanSet(&yygotominor.yy118,&yymsp[-4].minor.yy0,&yymsp[0].minor.yy0);
105311  if( yymsp[-2].minor.yy4 && yygotominor.yy118.pExpr ){
105312    yygotominor.yy118.pExpr->flags |= EP_Distinct;
105313  }
105314}
105315        break;
105316      case 198: /* expr ::= ID LP STAR RP */
105317{
105318  yygotominor.yy118.pExpr = sqlite3ExprFunction(pParse, 0, &yymsp[-3].minor.yy0);
105319  spanSet(&yygotominor.yy118,&yymsp[-3].minor.yy0,&yymsp[0].minor.yy0);
105320}
105321        break;
105322      case 199: /* term ::= CTIME_KW */
105323{
105324  /* The CURRENT_TIME, CURRENT_DATE, and CURRENT_TIMESTAMP values are
105325  ** treated as functions that return constants */
105326  yygotominor.yy118.pExpr = sqlite3ExprFunction(pParse, 0,&yymsp[0].minor.yy0);
105327  if( yygotominor.yy118.pExpr ){
105328    yygotominor.yy118.pExpr->op = TK_CONST_FUNC;
105329  }
105330  spanSet(&yygotominor.yy118, &yymsp[0].minor.yy0, &yymsp[0].minor.yy0);
105331}
105332        break;
105333      case 200: /* expr ::= expr AND expr */
105334      case 201: /* expr ::= expr OR expr */ yytestcase(yyruleno==201);
105335      case 202: /* expr ::= expr LT|GT|GE|LE expr */ yytestcase(yyruleno==202);
105336      case 203: /* expr ::= expr EQ|NE expr */ yytestcase(yyruleno==203);
105337      case 204: /* expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr */ yytestcase(yyruleno==204);
105338      case 205: /* expr ::= expr PLUS|MINUS expr */ yytestcase(yyruleno==205);
105339      case 206: /* expr ::= expr STAR|SLASH|REM expr */ yytestcase(yyruleno==206);
105340      case 207: /* expr ::= expr CONCAT expr */ yytestcase(yyruleno==207);
105341{spanBinaryExpr(&yygotominor.yy118,pParse,yymsp[-1].major,&yymsp[-2].minor.yy118,&yymsp[0].minor.yy118);}
105342        break;
105343      case 208: /* likeop ::= LIKE_KW */
105344      case 210: /* likeop ::= MATCH */ yytestcase(yyruleno==210);
105345{yygotominor.yy342.eOperator = yymsp[0].minor.yy0; yygotominor.yy342.not = 0;}
105346        break;
105347      case 209: /* likeop ::= NOT LIKE_KW */
105348      case 211: /* likeop ::= NOT MATCH */ yytestcase(yyruleno==211);
105349{yygotominor.yy342.eOperator = yymsp[0].minor.yy0; yygotominor.yy342.not = 1;}
105350        break;
105351      case 212: /* expr ::= expr likeop expr */
105352{
105353  ExprList *pList;
105354  pList = sqlite3ExprListAppend(pParse,0, yymsp[0].minor.yy118.pExpr);
105355  pList = sqlite3ExprListAppend(pParse,pList, yymsp[-2].minor.yy118.pExpr);
105356  yygotominor.yy118.pExpr = sqlite3ExprFunction(pParse, pList, &yymsp[-1].minor.yy342.eOperator);
105357  if( yymsp[-1].minor.yy342.not ) yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy118.pExpr, 0, 0);
105358  yygotominor.yy118.zStart = yymsp[-2].minor.yy118.zStart;
105359  yygotominor.yy118.zEnd = yymsp[0].minor.yy118.zEnd;
105360  if( yygotominor.yy118.pExpr ) yygotominor.yy118.pExpr->flags |= EP_InfixFunc;
105361}
105362        break;
105363      case 213: /* expr ::= expr likeop expr ESCAPE expr */
105364{
105365  ExprList *pList;
105366  pList = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy118.pExpr);
105367  pList = sqlite3ExprListAppend(pParse,pList, yymsp[-4].minor.yy118.pExpr);
105368  pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy118.pExpr);
105369  yygotominor.yy118.pExpr = sqlite3ExprFunction(pParse, pList, &yymsp[-3].minor.yy342.eOperator);
105370  if( yymsp[-3].minor.yy342.not ) yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy118.pExpr, 0, 0);
105371  yygotominor.yy118.zStart = yymsp[-4].minor.yy118.zStart;
105372  yygotominor.yy118.zEnd = yymsp[0].minor.yy118.zEnd;
105373  if( yygotominor.yy118.pExpr ) yygotominor.yy118.pExpr->flags |= EP_InfixFunc;
105374}
105375        break;
105376      case 214: /* expr ::= expr ISNULL|NOTNULL */
105377{spanUnaryPostfix(&yygotominor.yy118,pParse,yymsp[0].major,&yymsp[-1].minor.yy118,&yymsp[0].minor.yy0);}
105378        break;
105379      case 215: /* expr ::= expr NOT NULL */
105380{spanUnaryPostfix(&yygotominor.yy118,pParse,TK_NOTNULL,&yymsp[-2].minor.yy118,&yymsp[0].minor.yy0);}
105381        break;
105382      case 216: /* expr ::= expr IS expr */
105383{
105384  spanBinaryExpr(&yygotominor.yy118,pParse,TK_IS,&yymsp[-2].minor.yy118,&yymsp[0].minor.yy118);
105385  binaryToUnaryIfNull(pParse, yymsp[0].minor.yy118.pExpr, yygotominor.yy118.pExpr, TK_ISNULL);
105386}
105387        break;
105388      case 217: /* expr ::= expr IS NOT expr */
105389{
105390  spanBinaryExpr(&yygotominor.yy118,pParse,TK_ISNOT,&yymsp[-3].minor.yy118,&yymsp[0].minor.yy118);
105391  binaryToUnaryIfNull(pParse, yymsp[0].minor.yy118.pExpr, yygotominor.yy118.pExpr, TK_NOTNULL);
105392}
105393        break;
105394      case 218: /* expr ::= NOT expr */
105395      case 219: /* expr ::= BITNOT expr */ yytestcase(yyruleno==219);
105396{spanUnaryPrefix(&yygotominor.yy118,pParse,yymsp[-1].major,&yymsp[0].minor.yy118,&yymsp[-1].minor.yy0);}
105397        break;
105398      case 220: /* expr ::= MINUS expr */
105399{spanUnaryPrefix(&yygotominor.yy118,pParse,TK_UMINUS,&yymsp[0].minor.yy118,&yymsp[-1].minor.yy0);}
105400        break;
105401      case 221: /* expr ::= PLUS expr */
105402{spanUnaryPrefix(&yygotominor.yy118,pParse,TK_UPLUS,&yymsp[0].minor.yy118,&yymsp[-1].minor.yy0);}
105403        break;
105404      case 224: /* expr ::= expr between_op expr AND expr */
105405{
105406  ExprList *pList = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy118.pExpr);
105407  pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy118.pExpr);
105408  yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_BETWEEN, yymsp[-4].minor.yy118.pExpr, 0, 0);
105409  if( yygotominor.yy118.pExpr ){
105410    yygotominor.yy118.pExpr->x.pList = pList;
105411  }else{
105412    sqlite3ExprListDelete(pParse->db, pList);
105413  }
105414  if( yymsp[-3].minor.yy4 ) yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy118.pExpr, 0, 0);
105415  yygotominor.yy118.zStart = yymsp[-4].minor.yy118.zStart;
105416  yygotominor.yy118.zEnd = yymsp[0].minor.yy118.zEnd;
105417}
105418        break;
105419      case 227: /* expr ::= expr in_op LP exprlist RP */
105420{
105421    if( yymsp[-1].minor.yy322==0 ){
105422      /* Expressions of the form
105423      **
105424      **      expr1 IN ()
105425      **      expr1 NOT IN ()
105426      **
105427      ** simplify to constants 0 (false) and 1 (true), respectively,
105428      ** regardless of the value of expr1.
105429      */
105430      yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_INTEGER, 0, 0, &sqlite3IntTokens[yymsp[-3].minor.yy4]);
105431      sqlite3ExprDelete(pParse->db, yymsp[-4].minor.yy118.pExpr);
105432    }else{
105433      yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy118.pExpr, 0, 0);
105434      if( yygotominor.yy118.pExpr ){
105435        yygotominor.yy118.pExpr->x.pList = yymsp[-1].minor.yy322;
105436        sqlite3ExprSetHeight(pParse, yygotominor.yy118.pExpr);
105437      }else{
105438        sqlite3ExprListDelete(pParse->db, yymsp[-1].minor.yy322);
105439      }
105440      if( yymsp[-3].minor.yy4 ) yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy118.pExpr, 0, 0);
105441    }
105442    yygotominor.yy118.zStart = yymsp[-4].minor.yy118.zStart;
105443    yygotominor.yy118.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
105444  }
105445        break;
105446      case 228: /* expr ::= LP select RP */
105447{
105448    yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_SELECT, 0, 0, 0);
105449    if( yygotominor.yy118.pExpr ){
105450      yygotominor.yy118.pExpr->x.pSelect = yymsp[-1].minor.yy387;
105451      ExprSetProperty(yygotominor.yy118.pExpr, EP_xIsSelect);
105452      sqlite3ExprSetHeight(pParse, yygotominor.yy118.pExpr);
105453    }else{
105454      sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy387);
105455    }
105456    yygotominor.yy118.zStart = yymsp[-2].minor.yy0.z;
105457    yygotominor.yy118.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
105458  }
105459        break;
105460      case 229: /* expr ::= expr in_op LP select RP */
105461{
105462    yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy118.pExpr, 0, 0);
105463    if( yygotominor.yy118.pExpr ){
105464      yygotominor.yy118.pExpr->x.pSelect = yymsp[-1].minor.yy387;
105465      ExprSetProperty(yygotominor.yy118.pExpr, EP_xIsSelect);
105466      sqlite3ExprSetHeight(pParse, yygotominor.yy118.pExpr);
105467    }else{
105468      sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy387);
105469    }
105470    if( yymsp[-3].minor.yy4 ) yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy118.pExpr, 0, 0);
105471    yygotominor.yy118.zStart = yymsp[-4].minor.yy118.zStart;
105472    yygotominor.yy118.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
105473  }
105474        break;
105475      case 230: /* expr ::= expr in_op nm dbnm */
105476{
105477    SrcList *pSrc = sqlite3SrcListAppend(pParse->db, 0,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0);
105478    yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-3].minor.yy118.pExpr, 0, 0);
105479    if( yygotominor.yy118.pExpr ){
105480      yygotominor.yy118.pExpr->x.pSelect = sqlite3SelectNew(pParse, 0,pSrc,0,0,0,0,0,0,0);
105481      ExprSetProperty(yygotominor.yy118.pExpr, EP_xIsSelect);
105482      sqlite3ExprSetHeight(pParse, yygotominor.yy118.pExpr);
105483    }else{
105484      sqlite3SrcListDelete(pParse->db, pSrc);
105485    }
105486    if( yymsp[-2].minor.yy4 ) yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy118.pExpr, 0, 0);
105487    yygotominor.yy118.zStart = yymsp[-3].minor.yy118.zStart;
105488    yygotominor.yy118.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];
105489  }
105490        break;
105491      case 231: /* expr ::= EXISTS LP select RP */
105492{
105493    Expr *p = yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_EXISTS, 0, 0, 0);
105494    if( p ){
105495      p->x.pSelect = yymsp[-1].minor.yy387;
105496      ExprSetProperty(p, EP_xIsSelect);
105497      sqlite3ExprSetHeight(pParse, p);
105498    }else{
105499      sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy387);
105500    }
105501    yygotominor.yy118.zStart = yymsp[-3].minor.yy0.z;
105502    yygotominor.yy118.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
105503  }
105504        break;
105505      case 232: /* expr ::= CASE case_operand case_exprlist case_else END */
105506{
105507  yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_CASE, yymsp[-3].minor.yy314, yymsp[-1].minor.yy314, 0);
105508  if( yygotominor.yy118.pExpr ){
105509    yygotominor.yy118.pExpr->x.pList = yymsp[-2].minor.yy322;
105510    sqlite3ExprSetHeight(pParse, yygotominor.yy118.pExpr);
105511  }else{
105512    sqlite3ExprListDelete(pParse->db, yymsp[-2].minor.yy322);
105513  }
105514  yygotominor.yy118.zStart = yymsp[-4].minor.yy0.z;
105515  yygotominor.yy118.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
105516}
105517        break;
105518      case 233: /* case_exprlist ::= case_exprlist WHEN expr THEN expr */
105519{
105520  yygotominor.yy322 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy322, yymsp[-2].minor.yy118.pExpr);
105521  yygotominor.yy322 = sqlite3ExprListAppend(pParse,yygotominor.yy322, yymsp[0].minor.yy118.pExpr);
105522}
105523        break;
105524      case 234: /* case_exprlist ::= WHEN expr THEN expr */
105525{
105526  yygotominor.yy322 = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy118.pExpr);
105527  yygotominor.yy322 = sqlite3ExprListAppend(pParse,yygotominor.yy322, yymsp[0].minor.yy118.pExpr);
105528}
105529        break;
105530      case 243: /* cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP idxlist RP */
105531{
105532  sqlite3CreateIndex(pParse, &yymsp[-6].minor.yy0, &yymsp[-5].minor.yy0,
105533                     sqlite3SrcListAppend(pParse->db,0,&yymsp[-3].minor.yy0,0), yymsp[-1].minor.yy322, yymsp[-9].minor.yy4,
105534                      &yymsp[-10].minor.yy0, &yymsp[0].minor.yy0, SQLITE_SO_ASC, yymsp[-7].minor.yy4);
105535}
105536        break;
105537      case 244: /* uniqueflag ::= UNIQUE */
105538      case 298: /* raisetype ::= ABORT */ yytestcase(yyruleno==298);
105539{yygotominor.yy4 = OE_Abort;}
105540        break;
105541      case 245: /* uniqueflag ::= */
105542{yygotominor.yy4 = OE_None;}
105543        break;
105544      case 248: /* idxlist ::= idxlist COMMA nm collate sortorder */
105545{
105546  Expr *p = 0;
105547  if( yymsp[-1].minor.yy0.n>0 ){
105548    p = sqlite3Expr(pParse->db, TK_COLUMN, 0);
105549    sqlite3ExprSetCollByToken(pParse, p, &yymsp[-1].minor.yy0);
105550  }
105551  yygotominor.yy322 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy322, p);
105552  sqlite3ExprListSetName(pParse,yygotominor.yy322,&yymsp[-2].minor.yy0,1);
105553  sqlite3ExprListCheckLength(pParse, yygotominor.yy322, "index");
105554  if( yygotominor.yy322 ) yygotominor.yy322->a[yygotominor.yy322->nExpr-1].sortOrder = (u8)yymsp[0].minor.yy4;
105555}
105556        break;
105557      case 249: /* idxlist ::= nm collate sortorder */
105558{
105559  Expr *p = 0;
105560  if( yymsp[-1].minor.yy0.n>0 ){
105561    p = sqlite3PExpr(pParse, TK_COLUMN, 0, 0, 0);
105562    sqlite3ExprSetCollByToken(pParse, p, &yymsp[-1].minor.yy0);
105563  }
105564  yygotominor.yy322 = sqlite3ExprListAppend(pParse,0, p);
105565  sqlite3ExprListSetName(pParse, yygotominor.yy322, &yymsp[-2].minor.yy0, 1);
105566  sqlite3ExprListCheckLength(pParse, yygotominor.yy322, "index");
105567  if( yygotominor.yy322 ) yygotominor.yy322->a[yygotominor.yy322->nExpr-1].sortOrder = (u8)yymsp[0].minor.yy4;
105568}
105569        break;
105570      case 250: /* collate ::= */
105571{yygotominor.yy0.z = 0; yygotominor.yy0.n = 0;}
105572        break;
105573      case 252: /* cmd ::= DROP INDEX ifexists fullname */
105574{sqlite3DropIndex(pParse, yymsp[0].minor.yy259, yymsp[-1].minor.yy4);}
105575        break;
105576      case 253: /* cmd ::= VACUUM */
105577      case 254: /* cmd ::= VACUUM nm */ yytestcase(yyruleno==254);
105578{sqlite3Vacuum(pParse);}
105579        break;
105580      case 255: /* cmd ::= PRAGMA nm dbnm */
105581{sqlite3Pragma(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,0,0);}
105582        break;
105583      case 256: /* cmd ::= PRAGMA nm dbnm EQ nmnum */
105584{sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,0);}
105585        break;
105586      case 257: /* cmd ::= PRAGMA nm dbnm LP nmnum RP */
105587{sqlite3Pragma(pParse,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,0);}
105588        break;
105589      case 258: /* cmd ::= PRAGMA nm dbnm EQ minus_num */
105590{sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,1);}
105591        break;
105592      case 259: /* cmd ::= PRAGMA nm dbnm LP minus_num RP */
105593{sqlite3Pragma(pParse,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,1);}
105594        break;
105595      case 270: /* cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END */
105596{
105597  Token all;
105598  all.z = yymsp[-3].minor.yy0.z;
105599  all.n = (int)(yymsp[0].minor.yy0.z - yymsp[-3].minor.yy0.z) + yymsp[0].minor.yy0.n;
105600  sqlite3FinishTrigger(pParse, yymsp[-1].minor.yy203, &all);
105601}
105602        break;
105603      case 271: /* trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause */
105604{
105605  sqlite3BeginTrigger(pParse, &yymsp[-7].minor.yy0, &yymsp[-6].minor.yy0, yymsp[-5].minor.yy4, yymsp[-4].minor.yy90.a, yymsp[-4].minor.yy90.b, yymsp[-2].minor.yy259, yymsp[0].minor.yy314, yymsp[-10].minor.yy4, yymsp[-8].minor.yy4);
105606  yygotominor.yy0 = (yymsp[-6].minor.yy0.n==0?yymsp[-7].minor.yy0:yymsp[-6].minor.yy0);
105607}
105608        break;
105609      case 272: /* trigger_time ::= BEFORE */
105610      case 275: /* trigger_time ::= */ yytestcase(yyruleno==275);
105611{ yygotominor.yy4 = TK_BEFORE; }
105612        break;
105613      case 273: /* trigger_time ::= AFTER */
105614{ yygotominor.yy4 = TK_AFTER;  }
105615        break;
105616      case 274: /* trigger_time ::= INSTEAD OF */
105617{ yygotominor.yy4 = TK_INSTEAD;}
105618        break;
105619      case 276: /* trigger_event ::= DELETE|INSERT */
105620      case 277: /* trigger_event ::= UPDATE */ yytestcase(yyruleno==277);
105621{yygotominor.yy90.a = yymsp[0].major; yygotominor.yy90.b = 0;}
105622        break;
105623      case 278: /* trigger_event ::= UPDATE OF inscollist */
105624{yygotominor.yy90.a = TK_UPDATE; yygotominor.yy90.b = yymsp[0].minor.yy384;}
105625        break;
105626      case 281: /* when_clause ::= */
105627      case 303: /* key_opt ::= */ yytestcase(yyruleno==303);
105628{ yygotominor.yy314 = 0; }
105629        break;
105630      case 282: /* when_clause ::= WHEN expr */
105631      case 304: /* key_opt ::= KEY expr */ yytestcase(yyruleno==304);
105632{ yygotominor.yy314 = yymsp[0].minor.yy118.pExpr; }
105633        break;
105634      case 283: /* trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI */
105635{
105636  assert( yymsp[-2].minor.yy203!=0 );
105637  yymsp[-2].minor.yy203->pLast->pNext = yymsp[-1].minor.yy203;
105638  yymsp[-2].minor.yy203->pLast = yymsp[-1].minor.yy203;
105639  yygotominor.yy203 = yymsp[-2].minor.yy203;
105640}
105641        break;
105642      case 284: /* trigger_cmd_list ::= trigger_cmd SEMI */
105643{
105644  assert( yymsp[-1].minor.yy203!=0 );
105645  yymsp[-1].minor.yy203->pLast = yymsp[-1].minor.yy203;
105646  yygotominor.yy203 = yymsp[-1].minor.yy203;
105647}
105648        break;
105649      case 286: /* trnm ::= nm DOT nm */
105650{
105651  yygotominor.yy0 = yymsp[0].minor.yy0;
105652  sqlite3ErrorMsg(pParse,
105653        "qualified table names are not allowed on INSERT, UPDATE, and DELETE "
105654        "statements within triggers");
105655}
105656        break;
105657      case 288: /* tridxby ::= INDEXED BY nm */
105658{
105659  sqlite3ErrorMsg(pParse,
105660        "the INDEXED BY clause is not allowed on UPDATE or DELETE statements "
105661        "within triggers");
105662}
105663        break;
105664      case 289: /* tridxby ::= NOT INDEXED */
105665{
105666  sqlite3ErrorMsg(pParse,
105667        "the NOT INDEXED clause is not allowed on UPDATE or DELETE statements "
105668        "within triggers");
105669}
105670        break;
105671      case 290: /* trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist where_opt */
105672{ yygotominor.yy203 = sqlite3TriggerUpdateStep(pParse->db, &yymsp[-4].minor.yy0, yymsp[-1].minor.yy322, yymsp[0].minor.yy314, yymsp[-5].minor.yy210); }
105673        break;
105674      case 291: /* trigger_cmd ::= insert_cmd INTO trnm inscollist_opt VALUES LP itemlist RP */
105675{yygotominor.yy203 = sqlite3TriggerInsertStep(pParse->db, &yymsp[-5].minor.yy0, yymsp[-4].minor.yy384, yymsp[-1].minor.yy322, 0, yymsp[-7].minor.yy210);}
105676        break;
105677      case 292: /* trigger_cmd ::= insert_cmd INTO trnm inscollist_opt select */
105678{yygotominor.yy203 = sqlite3TriggerInsertStep(pParse->db, &yymsp[-2].minor.yy0, yymsp[-1].minor.yy384, 0, yymsp[0].minor.yy387, yymsp[-4].minor.yy210);}
105679        break;
105680      case 293: /* trigger_cmd ::= DELETE FROM trnm tridxby where_opt */
105681{yygotominor.yy203 = sqlite3TriggerDeleteStep(pParse->db, &yymsp[-2].minor.yy0, yymsp[0].minor.yy314);}
105682        break;
105683      case 294: /* trigger_cmd ::= select */
105684{yygotominor.yy203 = sqlite3TriggerSelectStep(pParse->db, yymsp[0].minor.yy387); }
105685        break;
105686      case 295: /* expr ::= RAISE LP IGNORE RP */
105687{
105688  yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_RAISE, 0, 0, 0);
105689  if( yygotominor.yy118.pExpr ){
105690    yygotominor.yy118.pExpr->affinity = OE_Ignore;
105691  }
105692  yygotominor.yy118.zStart = yymsp[-3].minor.yy0.z;
105693  yygotominor.yy118.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
105694}
105695        break;
105696      case 296: /* expr ::= RAISE LP raisetype COMMA nm RP */
105697{
105698  yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_RAISE, 0, 0, &yymsp[-1].minor.yy0);
105699  if( yygotominor.yy118.pExpr ) {
105700    yygotominor.yy118.pExpr->affinity = (char)yymsp[-3].minor.yy4;
105701  }
105702  yygotominor.yy118.zStart = yymsp[-5].minor.yy0.z;
105703  yygotominor.yy118.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
105704}
105705        break;
105706      case 297: /* raisetype ::= ROLLBACK */
105707{yygotominor.yy4 = OE_Rollback;}
105708        break;
105709      case 299: /* raisetype ::= FAIL */
105710{yygotominor.yy4 = OE_Fail;}
105711        break;
105712      case 300: /* cmd ::= DROP TRIGGER ifexists fullname */
105713{
105714  sqlite3DropTrigger(pParse,yymsp[0].minor.yy259,yymsp[-1].minor.yy4);
105715}
105716        break;
105717      case 301: /* cmd ::= ATTACH database_kw_opt expr AS expr key_opt */
105718{
105719  sqlite3Attach(pParse, yymsp[-3].minor.yy118.pExpr, yymsp[-1].minor.yy118.pExpr, yymsp[0].minor.yy314);
105720}
105721        break;
105722      case 302: /* cmd ::= DETACH database_kw_opt expr */
105723{
105724  sqlite3Detach(pParse, yymsp[0].minor.yy118.pExpr);
105725}
105726        break;
105727      case 307: /* cmd ::= REINDEX */
105728{sqlite3Reindex(pParse, 0, 0);}
105729        break;
105730      case 308: /* cmd ::= REINDEX nm dbnm */
105731{sqlite3Reindex(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);}
105732        break;
105733      case 309: /* cmd ::= ANALYZE */
105734{sqlite3Analyze(pParse, 0, 0);}
105735        break;
105736      case 310: /* cmd ::= ANALYZE nm dbnm */
105737{sqlite3Analyze(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);}
105738        break;
105739      case 311: /* cmd ::= ALTER TABLE fullname RENAME TO nm */
105740{
105741  sqlite3AlterRenameTable(pParse,yymsp[-3].minor.yy259,&yymsp[0].minor.yy0);
105742}
105743        break;
105744      case 312: /* cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt column */
105745{
105746  sqlite3AlterFinishAddColumn(pParse, &yymsp[0].minor.yy0);
105747}
105748        break;
105749      case 313: /* add_column_fullname ::= fullname */
105750{
105751  pParse->db->lookaside.bEnabled = 0;
105752  sqlite3AlterBeginAddColumn(pParse, yymsp[0].minor.yy259);
105753}
105754        break;
105755      case 316: /* cmd ::= create_vtab */
105756{sqlite3VtabFinishParse(pParse,0);}
105757        break;
105758      case 317: /* cmd ::= create_vtab LP vtabarglist RP */
105759{sqlite3VtabFinishParse(pParse,&yymsp[0].minor.yy0);}
105760        break;
105761      case 318: /* create_vtab ::= createkw VIRTUAL TABLE nm dbnm USING nm */
105762{
105763    sqlite3VtabBeginParse(pParse, &yymsp[-3].minor.yy0, &yymsp[-2].minor.yy0, &yymsp[0].minor.yy0);
105764}
105765        break;
105766      case 321: /* vtabarg ::= */
105767{sqlite3VtabArgInit(pParse);}
105768        break;
105769      case 323: /* vtabargtoken ::= ANY */
105770      case 324: /* vtabargtoken ::= lp anylist RP */ yytestcase(yyruleno==324);
105771      case 325: /* lp ::= LP */ yytestcase(yyruleno==325);
105772{sqlite3VtabArgExtend(pParse,&yymsp[0].minor.yy0);}
105773        break;
105774      default:
105775      /* (0) input ::= cmdlist */ yytestcase(yyruleno==0);
105776      /* (1) cmdlist ::= cmdlist ecmd */ yytestcase(yyruleno==1);
105777      /* (2) cmdlist ::= ecmd */ yytestcase(yyruleno==2);
105778      /* (3) ecmd ::= SEMI */ yytestcase(yyruleno==3);
105779      /* (4) ecmd ::= explain cmdx SEMI */ yytestcase(yyruleno==4);
105780      /* (10) trans_opt ::= */ yytestcase(yyruleno==10);
105781      /* (11) trans_opt ::= TRANSACTION */ yytestcase(yyruleno==11);
105782      /* (12) trans_opt ::= TRANSACTION nm */ yytestcase(yyruleno==12);
105783      /* (20) savepoint_opt ::= SAVEPOINT */ yytestcase(yyruleno==20);
105784      /* (21) savepoint_opt ::= */ yytestcase(yyruleno==21);
105785      /* (25) cmd ::= create_table create_table_args */ yytestcase(yyruleno==25);
105786      /* (34) columnlist ::= columnlist COMMA column */ yytestcase(yyruleno==34);
105787      /* (35) columnlist ::= column */ yytestcase(yyruleno==35);
105788      /* (44) type ::= */ yytestcase(yyruleno==44);
105789      /* (51) signed ::= plus_num */ yytestcase(yyruleno==51);
105790      /* (52) signed ::= minus_num */ yytestcase(yyruleno==52);
105791      /* (53) carglist ::= carglist carg */ yytestcase(yyruleno==53);
105792      /* (54) carglist ::= */ yytestcase(yyruleno==54);
105793      /* (55) carg ::= CONSTRAINT nm ccons */ yytestcase(yyruleno==55);
105794      /* (56) carg ::= ccons */ yytestcase(yyruleno==56);
105795      /* (62) ccons ::= NULL onconf */ yytestcase(yyruleno==62);
105796      /* (90) conslist ::= conslist COMMA tcons */ yytestcase(yyruleno==90);
105797      /* (91) conslist ::= conslist tcons */ yytestcase(yyruleno==91);
105798      /* (92) conslist ::= tcons */ yytestcase(yyruleno==92);
105799      /* (93) tcons ::= CONSTRAINT nm */ yytestcase(yyruleno==93);
105800      /* (268) plus_opt ::= PLUS */ yytestcase(yyruleno==268);
105801      /* (269) plus_opt ::= */ yytestcase(yyruleno==269);
105802      /* (279) foreach_clause ::= */ yytestcase(yyruleno==279);
105803      /* (280) foreach_clause ::= FOR EACH ROW */ yytestcase(yyruleno==280);
105804      /* (287) tridxby ::= */ yytestcase(yyruleno==287);
105805      /* (305) database_kw_opt ::= DATABASE */ yytestcase(yyruleno==305);
105806      /* (306) database_kw_opt ::= */ yytestcase(yyruleno==306);
105807      /* (314) kwcolumn_opt ::= */ yytestcase(yyruleno==314);
105808      /* (315) kwcolumn_opt ::= COLUMNKW */ yytestcase(yyruleno==315);
105809      /* (319) vtabarglist ::= vtabarg */ yytestcase(yyruleno==319);
105810      /* (320) vtabarglist ::= vtabarglist COMMA vtabarg */ yytestcase(yyruleno==320);
105811      /* (322) vtabarg ::= vtabarg vtabargtoken */ yytestcase(yyruleno==322);
105812      /* (326) anylist ::= */ yytestcase(yyruleno==326);
105813      /* (327) anylist ::= anylist LP anylist RP */ yytestcase(yyruleno==327);
105814      /* (328) anylist ::= anylist ANY */ yytestcase(yyruleno==328);
105815        break;
105816  };
105817  yygoto = yyRuleInfo[yyruleno].lhs;
105818  yysize = yyRuleInfo[yyruleno].nrhs;
105819  yypParser->yyidx -= yysize;
105820  yyact = yy_find_reduce_action(yymsp[-yysize].stateno,(YYCODETYPE)yygoto);
105821  if( yyact < YYNSTATE ){
105822#ifdef NDEBUG
105823    /* If we are not debugging and the reduce action popped at least
105824    ** one element off the stack, then we can push the new element back
105825    ** onto the stack here, and skip the stack overflow test in yy_shift().
105826    ** That gives a significant speed improvement. */
105827    if( yysize ){
105828      yypParser->yyidx++;
105829      yymsp -= yysize-1;
105830      yymsp->stateno = (YYACTIONTYPE)yyact;
105831      yymsp->major = (YYCODETYPE)yygoto;
105832      yymsp->minor = yygotominor;
105833    }else
105834#endif
105835    {
105836      yy_shift(yypParser,yyact,yygoto,&yygotominor);
105837    }
105838  }else{
105839    assert( yyact == YYNSTATE + YYNRULE + 1 );
105840    yy_accept(yypParser);
105841  }
105842}
105843
105844/*
105845** The following code executes when the parse fails
105846*/
105847#ifndef YYNOERRORRECOVERY
105848static void yy_parse_failed(
105849  yyParser *yypParser           /* The parser */
105850){
105851  sqlite3ParserARG_FETCH;
105852#ifndef NDEBUG
105853  if( yyTraceFILE ){
105854    fprintf(yyTraceFILE,"%sFail!\n",yyTracePrompt);
105855  }
105856#endif
105857  while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
105858  /* Here code is inserted which will be executed whenever the
105859  ** parser fails */
105860  sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
105861}
105862#endif /* YYNOERRORRECOVERY */
105863
105864/*
105865** The following code executes when a syntax error first occurs.
105866*/
105867static void yy_syntax_error(
105868  yyParser *yypParser,           /* The parser */
105869  int yymajor,                   /* The major type of the error token */
105870  YYMINORTYPE yyminor            /* The minor type of the error token */
105871){
105872  sqlite3ParserARG_FETCH;
105873#define TOKEN (yyminor.yy0)
105874
105875  UNUSED_PARAMETER(yymajor);  /* Silence some compiler warnings */
105876  assert( TOKEN.z[0] );  /* The tokenizer always gives us a token */
105877  sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &TOKEN);
105878  pParse->parseError = 1;
105879  sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
105880}
105881
105882/*
105883** The following is executed when the parser accepts
105884*/
105885static void yy_accept(
105886  yyParser *yypParser           /* The parser */
105887){
105888  sqlite3ParserARG_FETCH;
105889#ifndef NDEBUG
105890  if( yyTraceFILE ){
105891    fprintf(yyTraceFILE,"%sAccept!\n",yyTracePrompt);
105892  }
105893#endif
105894  while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
105895  /* Here code is inserted which will be executed whenever the
105896  ** parser accepts */
105897  sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
105898}
105899
105900/* The main parser program.
105901** The first argument is a pointer to a structure obtained from
105902** "sqlite3ParserAlloc" which describes the current state of the parser.
105903** The second argument is the major token number.  The third is
105904** the minor token.  The fourth optional argument is whatever the
105905** user wants (and specified in the grammar) and is available for
105906** use by the action routines.
105907**
105908** Inputs:
105909** <ul>
105910** <li> A pointer to the parser (an opaque structure.)
105911** <li> The major token number.
105912** <li> The minor token number.
105913** <li> An option argument of a grammar-specified type.
105914** </ul>
105915**
105916** Outputs:
105917** None.
105918*/
105919SQLITE_PRIVATE void sqlite3Parser(
105920  void *yyp,                   /* The parser */
105921  int yymajor,                 /* The major token code number */
105922  sqlite3ParserTOKENTYPE yyminor       /* The value for the token */
105923  sqlite3ParserARG_PDECL               /* Optional %extra_argument parameter */
105924){
105925  YYMINORTYPE yyminorunion;
105926  int yyact;            /* The parser action. */
105927  int yyendofinput;     /* True if we are at the end of input */
105928#ifdef YYERRORSYMBOL
105929  int yyerrorhit = 0;   /* True if yymajor has invoked an error */
105930#endif
105931  yyParser *yypParser;  /* The parser */
105932
105933  /* (re)initialize the parser, if necessary */
105934  yypParser = (yyParser*)yyp;
105935  if( yypParser->yyidx<0 ){
105936#if YYSTACKDEPTH<=0
105937    if( yypParser->yystksz <=0 ){
105938      /*memset(&yyminorunion, 0, sizeof(yyminorunion));*/
105939      yyminorunion = yyzerominor;
105940      yyStackOverflow(yypParser, &yyminorunion);
105941      return;
105942    }
105943#endif
105944    yypParser->yyidx = 0;
105945    yypParser->yyerrcnt = -1;
105946    yypParser->yystack[0].stateno = 0;
105947    yypParser->yystack[0].major = 0;
105948  }
105949  yyminorunion.yy0 = yyminor;
105950  yyendofinput = (yymajor==0);
105951  sqlite3ParserARG_STORE;
105952
105953#ifndef NDEBUG
105954  if( yyTraceFILE ){
105955    fprintf(yyTraceFILE,"%sInput %s\n",yyTracePrompt,yyTokenName[yymajor]);
105956  }
105957#endif
105958
105959  do{
105960    yyact = yy_find_shift_action(yypParser,(YYCODETYPE)yymajor);
105961    if( yyact<YYNSTATE ){
105962      assert( !yyendofinput );  /* Impossible to shift the $ token */
105963      yy_shift(yypParser,yyact,yymajor,&yyminorunion);
105964      yypParser->yyerrcnt--;
105965      yymajor = YYNOCODE;
105966    }else if( yyact < YYNSTATE + YYNRULE ){
105967      yy_reduce(yypParser,yyact-YYNSTATE);
105968    }else{
105969      assert( yyact == YY_ERROR_ACTION );
105970#ifdef YYERRORSYMBOL
105971      int yymx;
105972#endif
105973#ifndef NDEBUG
105974      if( yyTraceFILE ){
105975        fprintf(yyTraceFILE,"%sSyntax Error!\n",yyTracePrompt);
105976      }
105977#endif
105978#ifdef YYERRORSYMBOL
105979      /* A syntax error has occurred.
105980      ** The response to an error depends upon whether or not the
105981      ** grammar defines an error token "ERROR".
105982      **
105983      ** This is what we do if the grammar does define ERROR:
105984      **
105985      **  * Call the %syntax_error function.
105986      **
105987      **  * Begin popping the stack until we enter a state where
105988      **    it is legal to shift the error symbol, then shift
105989      **    the error symbol.
105990      **
105991      **  * Set the error count to three.
105992      **
105993      **  * Begin accepting and shifting new tokens.  No new error
105994      **    processing will occur until three tokens have been
105995      **    shifted successfully.
105996      **
105997      */
105998      if( yypParser->yyerrcnt<0 ){
105999        yy_syntax_error(yypParser,yymajor,yyminorunion);
106000      }
106001      yymx = yypParser->yystack[yypParser->yyidx].major;
106002      if( yymx==YYERRORSYMBOL || yyerrorhit ){
106003#ifndef NDEBUG
106004        if( yyTraceFILE ){
106005          fprintf(yyTraceFILE,"%sDiscard input token %s\n",
106006             yyTracePrompt,yyTokenName[yymajor]);
106007        }
106008#endif
106009        yy_destructor(yypParser, (YYCODETYPE)yymajor,&yyminorunion);
106010        yymajor = YYNOCODE;
106011      }else{
106012         while(
106013          yypParser->yyidx >= 0 &&
106014          yymx != YYERRORSYMBOL &&
106015          (yyact = yy_find_reduce_action(
106016                        yypParser->yystack[yypParser->yyidx].stateno,
106017                        YYERRORSYMBOL)) >= YYNSTATE
106018        ){
106019          yy_pop_parser_stack(yypParser);
106020        }
106021        if( yypParser->yyidx < 0 || yymajor==0 ){
106022          yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
106023          yy_parse_failed(yypParser);
106024          yymajor = YYNOCODE;
106025        }else if( yymx!=YYERRORSYMBOL ){
106026          YYMINORTYPE u2;
106027          u2.YYERRSYMDT = 0;
106028          yy_shift(yypParser,yyact,YYERRORSYMBOL,&u2);
106029        }
106030      }
106031      yypParser->yyerrcnt = 3;
106032      yyerrorhit = 1;
106033#elif defined(YYNOERRORRECOVERY)
106034      /* If the YYNOERRORRECOVERY macro is defined, then do not attempt to
106035      ** do any kind of error recovery.  Instead, simply invoke the syntax
106036      ** error routine and continue going as if nothing had happened.
106037      **
106038      ** Applications can set this macro (for example inside %include) if
106039      ** they intend to abandon the parse upon the first syntax error seen.
106040      */
106041      yy_syntax_error(yypParser,yymajor,yyminorunion);
106042      yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
106043      yymajor = YYNOCODE;
106044
106045#else  /* YYERRORSYMBOL is not defined */
106046      /* This is what we do if the grammar does not define ERROR:
106047      **
106048      **  * Report an error message, and throw away the input token.
106049      **
106050      **  * If the input token is $, then fail the parse.
106051      **
106052      ** As before, subsequent error messages are suppressed until
106053      ** three input tokens have been successfully shifted.
106054      */
106055      if( yypParser->yyerrcnt<=0 ){
106056        yy_syntax_error(yypParser,yymajor,yyminorunion);
106057      }
106058      yypParser->yyerrcnt = 3;
106059      yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
106060      if( yyendofinput ){
106061        yy_parse_failed(yypParser);
106062      }
106063      yymajor = YYNOCODE;
106064#endif
106065    }
106066  }while( yymajor!=YYNOCODE && yypParser->yyidx>=0 );
106067  return;
106068}
106069
106070/************** End of parse.c ***********************************************/
106071/************** Begin file tokenize.c ****************************************/
106072/*
106073** 2001 September 15
106074**
106075** The author disclaims copyright to this source code.  In place of
106076** a legal notice, here is a blessing:
106077**
106078**    May you do good and not evil.
106079**    May you find forgiveness for yourself and forgive others.
106080**    May you share freely, never taking more than you give.
106081**
106082*************************************************************************
106083** An tokenizer for SQL
106084**
106085** This file contains C code that splits an SQL input string up into
106086** individual tokens and sends those tokens one-by-one over to the
106087** parser for analysis.
106088*/
106089
106090/*
106091** The charMap() macro maps alphabetic characters into their
106092** lower-case ASCII equivalent.  On ASCII machines, this is just
106093** an upper-to-lower case map.  On EBCDIC machines we also need
106094** to adjust the encoding.  Only alphabetic characters and underscores
106095** need to be translated.
106096*/
106097#ifdef SQLITE_ASCII
106098# define charMap(X) sqlite3UpperToLower[(unsigned char)X]
106099#endif
106100#ifdef SQLITE_EBCDIC
106101# define charMap(X) ebcdicToAscii[(unsigned char)X]
106102const unsigned char ebcdicToAscii[] = {
106103/* 0   1   2   3   4   5   6   7   8   9   A   B   C   D   E   F */
106104   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 0x */
106105   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 1x */
106106   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 2x */
106107   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 3x */
106108   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 4x */
106109   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 5x */
106110   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, 95,  0,  0,  /* 6x */
106111   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 7x */
106112   0, 97, 98, 99,100,101,102,103,104,105,  0,  0,  0,  0,  0,  0,  /* 8x */
106113   0,106,107,108,109,110,111,112,113,114,  0,  0,  0,  0,  0,  0,  /* 9x */
106114   0,  0,115,116,117,118,119,120,121,122,  0,  0,  0,  0,  0,  0,  /* Ax */
106115   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* Bx */
106116   0, 97, 98, 99,100,101,102,103,104,105,  0,  0,  0,  0,  0,  0,  /* Cx */
106117   0,106,107,108,109,110,111,112,113,114,  0,  0,  0,  0,  0,  0,  /* Dx */
106118   0,  0,115,116,117,118,119,120,121,122,  0,  0,  0,  0,  0,  0,  /* Ex */
106119   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* Fx */
106120};
106121#endif
106122
106123/*
106124** The sqlite3KeywordCode function looks up an identifier to determine if
106125** it is a keyword.  If it is a keyword, the token code of that keyword is
106126** returned.  If the input is not a keyword, TK_ID is returned.
106127**
106128** The implementation of this routine was generated by a program,
106129** mkkeywordhash.h, located in the tool subdirectory of the distribution.
106130** The output of the mkkeywordhash.c program is written into a file
106131** named keywordhash.h and then included into this source file by
106132** the #include below.
106133*/
106134/************** Include keywordhash.h in the middle of tokenize.c ************/
106135/************** Begin file keywordhash.h *************************************/
106136/***** This file contains automatically generated code ******
106137**
106138** The code in this file has been automatically generated by
106139**
106140**   sqlite/tool/mkkeywordhash.c
106141**
106142** The code in this file implements a function that determines whether
106143** or not a given identifier is really an SQL keyword.  The same thing
106144** might be implemented more directly using a hand-written hash table.
106145** But by using this automatically generated code, the size of the code
106146** is substantially reduced.  This is important for embedded applications
106147** on platforms with limited memory.
106148*/
106149/* Hash score: 175 */
106150static int keywordCode(const char *z, int n){
106151  /* zText[] encodes 811 bytes of keywords in 541 bytes */
106152  /*   REINDEXEDESCAPEACHECKEYBEFOREIGNOREGEXPLAINSTEADDATABASELECT       */
106153  /*   ABLEFTHENDEFERRABLELSEXCEPTRANSACTIONATURALTERAISEXCLUSIVE         */
106154  /*   XISTSAVEPOINTERSECTRIGGEREFERENCESCONSTRAINTOFFSETEMPORARY         */
106155  /*   UNIQUERYATTACHAVINGROUPDATEBEGINNERELEASEBETWEENOTNULLIKE          */
106156  /*   CASCADELETECASECOLLATECREATECURRENT_DATEDETACHIMMEDIATEJOIN        */
106157  /*   SERTMATCHPLANALYZEPRAGMABORTVALUESVIRTUALIMITWHENWHERENAME         */
106158  /*   AFTEREPLACEANDEFAULTAUTOINCREMENTCASTCOLUMNCOMMITCONFLICTCROSS     */
106159  /*   CURRENT_TIMESTAMPRIMARYDEFERREDISTINCTDROPFAILFROMFULLGLOBYIF      */
106160  /*   ISNULLORDERESTRICTOUTERIGHTROLLBACKROWUNIONUSINGVACUUMVIEW         */
106161  /*   INITIALLY                                                          */
106162  static const char zText[540] = {
106163    'R','E','I','N','D','E','X','E','D','E','S','C','A','P','E','A','C','H',
106164    'E','C','K','E','Y','B','E','F','O','R','E','I','G','N','O','R','E','G',
106165    'E','X','P','L','A','I','N','S','T','E','A','D','D','A','T','A','B','A',
106166    'S','E','L','E','C','T','A','B','L','E','F','T','H','E','N','D','E','F',
106167    'E','R','R','A','B','L','E','L','S','E','X','C','E','P','T','R','A','N',
106168    'S','A','C','T','I','O','N','A','T','U','R','A','L','T','E','R','A','I',
106169    'S','E','X','C','L','U','S','I','V','E','X','I','S','T','S','A','V','E',
106170    'P','O','I','N','T','E','R','S','E','C','T','R','I','G','G','E','R','E',
106171    'F','E','R','E','N','C','E','S','C','O','N','S','T','R','A','I','N','T',
106172    'O','F','F','S','E','T','E','M','P','O','R','A','R','Y','U','N','I','Q',
106173    'U','E','R','Y','A','T','T','A','C','H','A','V','I','N','G','R','O','U',
106174    'P','D','A','T','E','B','E','G','I','N','N','E','R','E','L','E','A','S',
106175    'E','B','E','T','W','E','E','N','O','T','N','U','L','L','I','K','E','C',
106176    'A','S','C','A','D','E','L','E','T','E','C','A','S','E','C','O','L','L',
106177    'A','T','E','C','R','E','A','T','E','C','U','R','R','E','N','T','_','D',
106178    'A','T','E','D','E','T','A','C','H','I','M','M','E','D','I','A','T','E',
106179    'J','O','I','N','S','E','R','T','M','A','T','C','H','P','L','A','N','A',
106180    'L','Y','Z','E','P','R','A','G','M','A','B','O','R','T','V','A','L','U',
106181    'E','S','V','I','R','T','U','A','L','I','M','I','T','W','H','E','N','W',
106182    'H','E','R','E','N','A','M','E','A','F','T','E','R','E','P','L','A','C',
106183    'E','A','N','D','E','F','A','U','L','T','A','U','T','O','I','N','C','R',
106184    'E','M','E','N','T','C','A','S','T','C','O','L','U','M','N','C','O','M',
106185    'M','I','T','C','O','N','F','L','I','C','T','C','R','O','S','S','C','U',
106186    'R','R','E','N','T','_','T','I','M','E','S','T','A','M','P','R','I','M',
106187    'A','R','Y','D','E','F','E','R','R','E','D','I','S','T','I','N','C','T',
106188    'D','R','O','P','F','A','I','L','F','R','O','M','F','U','L','L','G','L',
106189    'O','B','Y','I','F','I','S','N','U','L','L','O','R','D','E','R','E','S',
106190    'T','R','I','C','T','O','U','T','E','R','I','G','H','T','R','O','L','L',
106191    'B','A','C','K','R','O','W','U','N','I','O','N','U','S','I','N','G','V',
106192    'A','C','U','U','M','V','I','E','W','I','N','I','T','I','A','L','L','Y',
106193  };
106194  static const unsigned char aHash[127] = {
106195      72, 101, 114,  70,   0,  45,   0,   0,  78,   0,  73,   0,   0,
106196      42,  12,  74,  15,   0, 113,  81,  50, 108,   0,  19,   0,   0,
106197     118,   0, 116, 111,   0,  22,  89,   0,   9,   0,   0,  66,  67,
106198       0,  65,   6,   0,  48,  86,  98,   0, 115,  97,   0,   0,  44,
106199       0,  99,  24,   0,  17,   0, 119,  49,  23,   0,   5, 106,  25,
106200      92,   0,   0, 121, 102,  56, 120,  53,  28,  51,   0,  87,   0,
106201      96,  26,   0,  95,   0,   0,   0,  91,  88,  93,  84, 105,  14,
106202      39, 104,   0,  77,   0,  18,  85, 107,  32,   0, 117,  76, 109,
106203      58,  46,  80,   0,   0,  90,  40,   0, 112,   0,  36,   0,   0,
106204      29,   0,  82,  59,  60,   0,  20,  57,   0,  52,
106205  };
106206  static const unsigned char aNext[121] = {
106207       0,   0,   0,   0,   4,   0,   0,   0,   0,   0,   0,   0,   0,
106208       0,   2,   0,   0,   0,   0,   0,   0,  13,   0,   0,   0,   0,
106209       0,   7,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,
106210       0,   0,   0,   0,  33,   0,  21,   0,   0,   0,  43,   3,  47,
106211       0,   0,   0,   0,  30,   0,  54,   0,  38,   0,   0,   0,   1,
106212      62,   0,   0,  63,   0,  41,   0,   0,   0,   0,   0,   0,   0,
106213      61,   0,   0,   0,   0,  31,  55,  16,  34,  10,   0,   0,   0,
106214       0,   0,   0,   0,  11,  68,  75,   0,   8,   0, 100,  94,   0,
106215     103,   0,  83,   0,  71,   0,   0, 110,  27,  37,  69,  79,   0,
106216      35,  64,   0,   0,
106217  };
106218  static const unsigned char aLen[121] = {
106219       7,   7,   5,   4,   6,   4,   5,   3,   6,   7,   3,   6,   6,
106220       7,   7,   3,   8,   2,   6,   5,   4,   4,   3,  10,   4,   6,
106221      11,   6,   2,   7,   5,   5,   9,   6,   9,   9,   7,  10,  10,
106222       4,   6,   2,   3,   9,   4,   2,   6,   5,   6,   6,   5,   6,
106223       5,   5,   7,   7,   7,   3,   2,   4,   4,   7,   3,   6,   4,
106224       7,   6,  12,   6,   9,   4,   6,   5,   4,   7,   6,   5,   6,
106225       7,   5,   4,   5,   6,   5,   7,   3,   7,  13,   2,   2,   4,
106226       6,   6,   8,   5,  17,  12,   7,   8,   8,   2,   4,   4,   4,
106227       4,   4,   2,   2,   6,   5,   8,   5,   5,   8,   3,   5,   5,
106228       6,   4,   9,   3,
106229  };
106230  static const unsigned short int aOffset[121] = {
106231       0,   2,   2,   8,   9,  14,  16,  20,  23,  25,  25,  29,  33,
106232      36,  41,  46,  48,  53,  54,  59,  62,  65,  67,  69,  78,  81,
106233      86,  91,  95,  96, 101, 105, 109, 117, 122, 128, 136, 142, 152,
106234     159, 162, 162, 165, 167, 167, 171, 176, 179, 184, 189, 194, 197,
106235     203, 206, 210, 217, 223, 223, 223, 226, 229, 233, 234, 238, 244,
106236     248, 255, 261, 273, 279, 288, 290, 296, 301, 303, 310, 315, 320,
106237     326, 332, 337, 341, 344, 350, 354, 361, 363, 370, 372, 374, 383,
106238     387, 393, 399, 407, 412, 412, 428, 435, 442, 443, 450, 454, 458,
106239     462, 466, 469, 471, 473, 479, 483, 491, 495, 500, 508, 511, 516,
106240     521, 527, 531, 536,
106241  };
106242  static const unsigned char aCode[121] = {
106243    TK_REINDEX,    TK_INDEXED,    TK_INDEX,      TK_DESC,       TK_ESCAPE,
106244    TK_EACH,       TK_CHECK,      TK_KEY,        TK_BEFORE,     TK_FOREIGN,
106245    TK_FOR,        TK_IGNORE,     TK_LIKE_KW,    TK_EXPLAIN,    TK_INSTEAD,
106246    TK_ADD,        TK_DATABASE,   TK_AS,         TK_SELECT,     TK_TABLE,
106247    TK_JOIN_KW,    TK_THEN,       TK_END,        TK_DEFERRABLE, TK_ELSE,
106248    TK_EXCEPT,     TK_TRANSACTION,TK_ACTION,     TK_ON,         TK_JOIN_KW,
106249    TK_ALTER,      TK_RAISE,      TK_EXCLUSIVE,  TK_EXISTS,     TK_SAVEPOINT,
106250    TK_INTERSECT,  TK_TRIGGER,    TK_REFERENCES, TK_CONSTRAINT, TK_INTO,
106251    TK_OFFSET,     TK_OF,         TK_SET,        TK_TEMP,       TK_TEMP,
106252    TK_OR,         TK_UNIQUE,     TK_QUERY,      TK_ATTACH,     TK_HAVING,
106253    TK_GROUP,      TK_UPDATE,     TK_BEGIN,      TK_JOIN_KW,    TK_RELEASE,
106254    TK_BETWEEN,    TK_NOTNULL,    TK_NOT,        TK_NO,         TK_NULL,
106255    TK_LIKE_KW,    TK_CASCADE,    TK_ASC,        TK_DELETE,     TK_CASE,
106256    TK_COLLATE,    TK_CREATE,     TK_CTIME_KW,   TK_DETACH,     TK_IMMEDIATE,
106257    TK_JOIN,       TK_INSERT,     TK_MATCH,      TK_PLAN,       TK_ANALYZE,
106258    TK_PRAGMA,     TK_ABORT,      TK_VALUES,     TK_VIRTUAL,    TK_LIMIT,
106259    TK_WHEN,       TK_WHERE,      TK_RENAME,     TK_AFTER,      TK_REPLACE,
106260    TK_AND,        TK_DEFAULT,    TK_AUTOINCR,   TK_TO,         TK_IN,
106261    TK_CAST,       TK_COLUMNKW,   TK_COMMIT,     TK_CONFLICT,   TK_JOIN_KW,
106262    TK_CTIME_KW,   TK_CTIME_KW,   TK_PRIMARY,    TK_DEFERRED,   TK_DISTINCT,
106263    TK_IS,         TK_DROP,       TK_FAIL,       TK_FROM,       TK_JOIN_KW,
106264    TK_LIKE_KW,    TK_BY,         TK_IF,         TK_ISNULL,     TK_ORDER,
106265    TK_RESTRICT,   TK_JOIN_KW,    TK_JOIN_KW,    TK_ROLLBACK,   TK_ROW,
106266    TK_UNION,      TK_USING,      TK_VACUUM,     TK_VIEW,       TK_INITIALLY,
106267    TK_ALL,
106268  };
106269  int h, i;
106270  if( n<2 ) return TK_ID;
106271  h = ((charMap(z[0])*4) ^
106272      (charMap(z[n-1])*3) ^
106273      n) % 127;
106274  for(i=((int)aHash[h])-1; i>=0; i=((int)aNext[i])-1){
106275    if( aLen[i]==n && sqlite3StrNICmp(&zText[aOffset[i]],z,n)==0 ){
106276      testcase( i==0 ); /* REINDEX */
106277      testcase( i==1 ); /* INDEXED */
106278      testcase( i==2 ); /* INDEX */
106279      testcase( i==3 ); /* DESC */
106280      testcase( i==4 ); /* ESCAPE */
106281      testcase( i==5 ); /* EACH */
106282      testcase( i==6 ); /* CHECK */
106283      testcase( i==7 ); /* KEY */
106284      testcase( i==8 ); /* BEFORE */
106285      testcase( i==9 ); /* FOREIGN */
106286      testcase( i==10 ); /* FOR */
106287      testcase( i==11 ); /* IGNORE */
106288      testcase( i==12 ); /* REGEXP */
106289      testcase( i==13 ); /* EXPLAIN */
106290      testcase( i==14 ); /* INSTEAD */
106291      testcase( i==15 ); /* ADD */
106292      testcase( i==16 ); /* DATABASE */
106293      testcase( i==17 ); /* AS */
106294      testcase( i==18 ); /* SELECT */
106295      testcase( i==19 ); /* TABLE */
106296      testcase( i==20 ); /* LEFT */
106297      testcase( i==21 ); /* THEN */
106298      testcase( i==22 ); /* END */
106299      testcase( i==23 ); /* DEFERRABLE */
106300      testcase( i==24 ); /* ELSE */
106301      testcase( i==25 ); /* EXCEPT */
106302      testcase( i==26 ); /* TRANSACTION */
106303      testcase( i==27 ); /* ACTION */
106304      testcase( i==28 ); /* ON */
106305      testcase( i==29 ); /* NATURAL */
106306      testcase( i==30 ); /* ALTER */
106307      testcase( i==31 ); /* RAISE */
106308      testcase( i==32 ); /* EXCLUSIVE */
106309      testcase( i==33 ); /* EXISTS */
106310      testcase( i==34 ); /* SAVEPOINT */
106311      testcase( i==35 ); /* INTERSECT */
106312      testcase( i==36 ); /* TRIGGER */
106313      testcase( i==37 ); /* REFERENCES */
106314      testcase( i==38 ); /* CONSTRAINT */
106315      testcase( i==39 ); /* INTO */
106316      testcase( i==40 ); /* OFFSET */
106317      testcase( i==41 ); /* OF */
106318      testcase( i==42 ); /* SET */
106319      testcase( i==43 ); /* TEMPORARY */
106320      testcase( i==44 ); /* TEMP */
106321      testcase( i==45 ); /* OR */
106322      testcase( i==46 ); /* UNIQUE */
106323      testcase( i==47 ); /* QUERY */
106324      testcase( i==48 ); /* ATTACH */
106325      testcase( i==49 ); /* HAVING */
106326      testcase( i==50 ); /* GROUP */
106327      testcase( i==51 ); /* UPDATE */
106328      testcase( i==52 ); /* BEGIN */
106329      testcase( i==53 ); /* INNER */
106330      testcase( i==54 ); /* RELEASE */
106331      testcase( i==55 ); /* BETWEEN */
106332      testcase( i==56 ); /* NOTNULL */
106333      testcase( i==57 ); /* NOT */
106334      testcase( i==58 ); /* NO */
106335      testcase( i==59 ); /* NULL */
106336      testcase( i==60 ); /* LIKE */
106337      testcase( i==61 ); /* CASCADE */
106338      testcase( i==62 ); /* ASC */
106339      testcase( i==63 ); /* DELETE */
106340      testcase( i==64 ); /* CASE */
106341      testcase( i==65 ); /* COLLATE */
106342      testcase( i==66 ); /* CREATE */
106343      testcase( i==67 ); /* CURRENT_DATE */
106344      testcase( i==68 ); /* DETACH */
106345      testcase( i==69 ); /* IMMEDIATE */
106346      testcase( i==70 ); /* JOIN */
106347      testcase( i==71 ); /* INSERT */
106348      testcase( i==72 ); /* MATCH */
106349      testcase( i==73 ); /* PLAN */
106350      testcase( i==74 ); /* ANALYZE */
106351      testcase( i==75 ); /* PRAGMA */
106352      testcase( i==76 ); /* ABORT */
106353      testcase( i==77 ); /* VALUES */
106354      testcase( i==78 ); /* VIRTUAL */
106355      testcase( i==79 ); /* LIMIT */
106356      testcase( i==80 ); /* WHEN */
106357      testcase( i==81 ); /* WHERE */
106358      testcase( i==82 ); /* RENAME */
106359      testcase( i==83 ); /* AFTER */
106360      testcase( i==84 ); /* REPLACE */
106361      testcase( i==85 ); /* AND */
106362      testcase( i==86 ); /* DEFAULT */
106363      testcase( i==87 ); /* AUTOINCREMENT */
106364      testcase( i==88 ); /* TO */
106365      testcase( i==89 ); /* IN */
106366      testcase( i==90 ); /* CAST */
106367      testcase( i==91 ); /* COLUMN */
106368      testcase( i==92 ); /* COMMIT */
106369      testcase( i==93 ); /* CONFLICT */
106370      testcase( i==94 ); /* CROSS */
106371      testcase( i==95 ); /* CURRENT_TIMESTAMP */
106372      testcase( i==96 ); /* CURRENT_TIME */
106373      testcase( i==97 ); /* PRIMARY */
106374      testcase( i==98 ); /* DEFERRED */
106375      testcase( i==99 ); /* DISTINCT */
106376      testcase( i==100 ); /* IS */
106377      testcase( i==101 ); /* DROP */
106378      testcase( i==102 ); /* FAIL */
106379      testcase( i==103 ); /* FROM */
106380      testcase( i==104 ); /* FULL */
106381      testcase( i==105 ); /* GLOB */
106382      testcase( i==106 ); /* BY */
106383      testcase( i==107 ); /* IF */
106384      testcase( i==108 ); /* ISNULL */
106385      testcase( i==109 ); /* ORDER */
106386      testcase( i==110 ); /* RESTRICT */
106387      testcase( i==111 ); /* OUTER */
106388      testcase( i==112 ); /* RIGHT */
106389      testcase( i==113 ); /* ROLLBACK */
106390      testcase( i==114 ); /* ROW */
106391      testcase( i==115 ); /* UNION */
106392      testcase( i==116 ); /* USING */
106393      testcase( i==117 ); /* VACUUM */
106394      testcase( i==118 ); /* VIEW */
106395      testcase( i==119 ); /* INITIALLY */
106396      testcase( i==120 ); /* ALL */
106397      return aCode[i];
106398    }
106399  }
106400  return TK_ID;
106401}
106402SQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char *z, int n){
106403  return keywordCode((char*)z, n);
106404}
106405#define SQLITE_N_KEYWORD 121
106406
106407/************** End of keywordhash.h *****************************************/
106408/************** Continuing where we left off in tokenize.c *******************/
106409
106410
106411/*
106412** If X is a character that can be used in an identifier then
106413** IdChar(X) will be true.  Otherwise it is false.
106414**
106415** For ASCII, any character with the high-order bit set is
106416** allowed in an identifier.  For 7-bit characters,
106417** sqlite3IsIdChar[X] must be 1.
106418**
106419** For EBCDIC, the rules are more complex but have the same
106420** end result.
106421**
106422** Ticket #1066.  the SQL standard does not allow '$' in the
106423** middle of identfiers.  But many SQL implementations do.
106424** SQLite will allow '$' in identifiers for compatibility.
106425** But the feature is undocumented.
106426*/
106427#ifdef SQLITE_ASCII
106428#define IdChar(C)  ((sqlite3CtypeMap[(unsigned char)C]&0x46)!=0)
106429#endif
106430#ifdef SQLITE_EBCDIC
106431SQLITE_PRIVATE const char sqlite3IsEbcdicIdChar[] = {
106432/* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
106433    0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,  /* 4x */
106434    0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0,  /* 5x */
106435    0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0,  /* 6x */
106436    0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0,  /* 7x */
106437    0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 0,  /* 8x */
106438    0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 0, 1, 0,  /* 9x */
106439    1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0,  /* Ax */
106440    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* Bx */
106441    0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1,  /* Cx */
106442    0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1,  /* Dx */
106443    0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1,  /* Ex */
106444    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0,  /* Fx */
106445};
106446#define IdChar(C)  (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40]))
106447#endif
106448
106449
106450/*
106451** Return the length of the token that begins at z[0].
106452** Store the token type in *tokenType before returning.
106453*/
106454SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *z, int *tokenType){
106455  int i, c;
106456  switch( *z ){
106457    case ' ': case '\t': case '\n': case '\f': case '\r': {
106458      testcase( z[0]==' ' );
106459      testcase( z[0]=='\t' );
106460      testcase( z[0]=='\n' );
106461      testcase( z[0]=='\f' );
106462      testcase( z[0]=='\r' );
106463      for(i=1; sqlite3Isspace(z[i]); i++){}
106464      *tokenType = TK_SPACE;
106465      return i;
106466    }
106467    case '-': {
106468      if( z[1]=='-' ){
106469        /* IMP: R-15891-05542 -- syntax diagram for comments */
106470        for(i=2; (c=z[i])!=0 && c!='\n'; i++){}
106471        *tokenType = TK_SPACE;   /* IMP: R-22934-25134 */
106472        return i;
106473      }
106474      *tokenType = TK_MINUS;
106475      return 1;
106476    }
106477    case '(': {
106478      *tokenType = TK_LP;
106479      return 1;
106480    }
106481    case ')': {
106482      *tokenType = TK_RP;
106483      return 1;
106484    }
106485    case ';': {
106486      *tokenType = TK_SEMI;
106487      return 1;
106488    }
106489    case '+': {
106490      *tokenType = TK_PLUS;
106491      return 1;
106492    }
106493    case '*': {
106494      *tokenType = TK_STAR;
106495      return 1;
106496    }
106497    case '/': {
106498      if( z[1]!='*' || z[2]==0 ){
106499        *tokenType = TK_SLASH;
106500        return 1;
106501      }
106502      /* IMP: R-15891-05542 -- syntax diagram for comments */
106503      for(i=3, c=z[2]; (c!='*' || z[i]!='/') && (c=z[i])!=0; i++){}
106504      if( c ) i++;
106505      *tokenType = TK_SPACE;   /* IMP: R-22934-25134 */
106506      return i;
106507    }
106508    case '%': {
106509      *tokenType = TK_REM;
106510      return 1;
106511    }
106512    case '=': {
106513      *tokenType = TK_EQ;
106514      return 1 + (z[1]=='=');
106515    }
106516    case '<': {
106517      if( (c=z[1])=='=' ){
106518        *tokenType = TK_LE;
106519        return 2;
106520      }else if( c=='>' ){
106521        *tokenType = TK_NE;
106522        return 2;
106523      }else if( c=='<' ){
106524        *tokenType = TK_LSHIFT;
106525        return 2;
106526      }else{
106527        *tokenType = TK_LT;
106528        return 1;
106529      }
106530    }
106531    case '>': {
106532      if( (c=z[1])=='=' ){
106533        *tokenType = TK_GE;
106534        return 2;
106535      }else if( c=='>' ){
106536        *tokenType = TK_RSHIFT;
106537        return 2;
106538      }else{
106539        *tokenType = TK_GT;
106540        return 1;
106541      }
106542    }
106543    case '!': {
106544      if( z[1]!='=' ){
106545        *tokenType = TK_ILLEGAL;
106546        return 2;
106547      }else{
106548        *tokenType = TK_NE;
106549        return 2;
106550      }
106551    }
106552    case '|': {
106553      if( z[1]!='|' ){
106554        *tokenType = TK_BITOR;
106555        return 1;
106556      }else{
106557        *tokenType = TK_CONCAT;
106558        return 2;
106559      }
106560    }
106561    case ',': {
106562      *tokenType = TK_COMMA;
106563      return 1;
106564    }
106565    case '&': {
106566      *tokenType = TK_BITAND;
106567      return 1;
106568    }
106569    case '~': {
106570      *tokenType = TK_BITNOT;
106571      return 1;
106572    }
106573    case '`':
106574    case '\'':
106575    case '"': {
106576      int delim = z[0];
106577      testcase( delim=='`' );
106578      testcase( delim=='\'' );
106579      testcase( delim=='"' );
106580      for(i=1; (c=z[i])!=0; i++){
106581        if( c==delim ){
106582          if( z[i+1]==delim ){
106583            i++;
106584          }else{
106585            break;
106586          }
106587        }
106588      }
106589      if( c=='\'' ){
106590        *tokenType = TK_STRING;
106591        return i+1;
106592      }else if( c!=0 ){
106593        *tokenType = TK_ID;
106594        return i+1;
106595      }else{
106596        *tokenType = TK_ILLEGAL;
106597        return i;
106598      }
106599    }
106600    case '.': {
106601#ifndef SQLITE_OMIT_FLOATING_POINT
106602      if( !sqlite3Isdigit(z[1]) )
106603#endif
106604      {
106605        *tokenType = TK_DOT;
106606        return 1;
106607      }
106608      /* If the next character is a digit, this is a floating point
106609      ** number that begins with ".".  Fall thru into the next case */
106610    }
106611    case '0': case '1': case '2': case '3': case '4':
106612    case '5': case '6': case '7': case '8': case '9': {
106613      testcase( z[0]=='0' );  testcase( z[0]=='1' );  testcase( z[0]=='2' );
106614      testcase( z[0]=='3' );  testcase( z[0]=='4' );  testcase( z[0]=='5' );
106615      testcase( z[0]=='6' );  testcase( z[0]=='7' );  testcase( z[0]=='8' );
106616      testcase( z[0]=='9' );
106617      *tokenType = TK_INTEGER;
106618      for(i=0; sqlite3Isdigit(z[i]); i++){}
106619#ifndef SQLITE_OMIT_FLOATING_POINT
106620      if( z[i]=='.' ){
106621        i++;
106622        while( sqlite3Isdigit(z[i]) ){ i++; }
106623        *tokenType = TK_FLOAT;
106624      }
106625      if( (z[i]=='e' || z[i]=='E') &&
106626           ( sqlite3Isdigit(z[i+1])
106627            || ((z[i+1]=='+' || z[i+1]=='-') && sqlite3Isdigit(z[i+2]))
106628           )
106629      ){
106630        i += 2;
106631        while( sqlite3Isdigit(z[i]) ){ i++; }
106632        *tokenType = TK_FLOAT;
106633      }
106634#endif
106635      while( IdChar(z[i]) ){
106636        *tokenType = TK_ILLEGAL;
106637        i++;
106638      }
106639      return i;
106640    }
106641    case '[': {
106642      for(i=1, c=z[0]; c!=']' && (c=z[i])!=0; i++){}
106643      *tokenType = c==']' ? TK_ID : TK_ILLEGAL;
106644      return i;
106645    }
106646    case '?': {
106647      *tokenType = TK_VARIABLE;
106648      for(i=1; sqlite3Isdigit(z[i]); i++){}
106649      return i;
106650    }
106651    case '#': {
106652      for(i=1; sqlite3Isdigit(z[i]); i++){}
106653      if( i>1 ){
106654        /* Parameters of the form #NNN (where NNN is a number) are used
106655        ** internally by sqlite3NestedParse.  */
106656        *tokenType = TK_REGISTER;
106657        return i;
106658      }
106659      /* Fall through into the next case if the '#' is not followed by
106660      ** a digit. Try to match #AAAA where AAAA is a parameter name. */
106661    }
106662#ifndef SQLITE_OMIT_TCL_VARIABLE
106663    case '$':
106664#endif
106665    case '@':  /* For compatibility with MS SQL Server */
106666    case ':': {
106667      int n = 0;
106668      testcase( z[0]=='$' );  testcase( z[0]=='@' );  testcase( z[0]==':' );
106669      *tokenType = TK_VARIABLE;
106670      for(i=1; (c=z[i])!=0; i++){
106671        if( IdChar(c) ){
106672          n++;
106673#ifndef SQLITE_OMIT_TCL_VARIABLE
106674        }else if( c=='(' && n>0 ){
106675          do{
106676            i++;
106677          }while( (c=z[i])!=0 && !sqlite3Isspace(c) && c!=')' );
106678          if( c==')' ){
106679            i++;
106680          }else{
106681            *tokenType = TK_ILLEGAL;
106682          }
106683          break;
106684        }else if( c==':' && z[i+1]==':' ){
106685          i++;
106686#endif
106687        }else{
106688          break;
106689        }
106690      }
106691      if( n==0 ) *tokenType = TK_ILLEGAL;
106692      return i;
106693    }
106694#ifndef SQLITE_OMIT_BLOB_LITERAL
106695    case 'x': case 'X': {
106696      testcase( z[0]=='x' ); testcase( z[0]=='X' );
106697      if( z[1]=='\'' ){
106698        *tokenType = TK_BLOB;
106699        for(i=2; (c=z[i])!=0 && c!='\''; i++){
106700          if( !sqlite3Isxdigit(c) ){
106701            *tokenType = TK_ILLEGAL;
106702          }
106703        }
106704        if( i%2 || !c ) *tokenType = TK_ILLEGAL;
106705        if( c ) i++;
106706        return i;
106707      }
106708      /* Otherwise fall through to the next case */
106709    }
106710#endif
106711    default: {
106712      if( !IdChar(*z) ){
106713        break;
106714      }
106715      for(i=1; IdChar(z[i]); i++){}
106716      *tokenType = keywordCode((char*)z, i);
106717      return i;
106718    }
106719  }
106720  *tokenType = TK_ILLEGAL;
106721  return 1;
106722}
106723
106724/*
106725** Run the parser on the given SQL string.  The parser structure is
106726** passed in.  An SQLITE_ status code is returned.  If an error occurs
106727** then an and attempt is made to write an error message into
106728** memory obtained from sqlite3_malloc() and to make *pzErrMsg point to that
106729** error message.
106730*/
106731SQLITE_PRIVATE int sqlite3RunParser(Parse *pParse, const char *zSql, char **pzErrMsg){
106732  int nErr = 0;                   /* Number of errors encountered */
106733  int i;                          /* Loop counter */
106734  void *pEngine;                  /* The LEMON-generated LALR(1) parser */
106735  int tokenType;                  /* type of the next token */
106736  int lastTokenParsed = -1;       /* type of the previous token */
106737  u8 enableLookaside;             /* Saved value of db->lookaside.bEnabled */
106738  sqlite3 *db = pParse->db;       /* The database connection */
106739  int mxSqlLen;                   /* Max length of an SQL string */
106740
106741
106742  mxSqlLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH];
106743  if( db->activeVdbeCnt==0 ){
106744    db->u1.isInterrupted = 0;
106745  }
106746  pParse->rc = SQLITE_OK;
106747  pParse->zTail = zSql;
106748  i = 0;
106749  assert( pzErrMsg!=0 );
106750  pEngine = sqlite3ParserAlloc((void*(*)(size_t))sqlite3Malloc);
106751  if( pEngine==0 ){
106752    db->mallocFailed = 1;
106753    return SQLITE_NOMEM;
106754  }
106755  assert( pParse->pNewTable==0 );
106756  assert( pParse->pNewTrigger==0 );
106757  assert( pParse->nVar==0 );
106758  assert( pParse->nVarExpr==0 );
106759  assert( pParse->nVarExprAlloc==0 );
106760  assert( pParse->apVarExpr==0 );
106761  enableLookaside = db->lookaside.bEnabled;
106762  if( db->lookaside.pStart ) db->lookaside.bEnabled = 1;
106763  while( !db->mallocFailed && zSql[i]!=0 ){
106764    assert( i>=0 );
106765    pParse->sLastToken.z = &zSql[i];
106766    pParse->sLastToken.n = sqlite3GetToken((unsigned char*)&zSql[i],&tokenType);
106767    i += pParse->sLastToken.n;
106768    if( i>mxSqlLen ){
106769      pParse->rc = SQLITE_TOOBIG;
106770      break;
106771    }
106772    switch( tokenType ){
106773      case TK_SPACE: {
106774        if( db->u1.isInterrupted ){
106775          sqlite3ErrorMsg(pParse, "interrupt");
106776          pParse->rc = SQLITE_INTERRUPT;
106777          goto abort_parse;
106778        }
106779        break;
106780      }
106781      case TK_ILLEGAL: {
106782        sqlite3DbFree(db, *pzErrMsg);
106783        *pzErrMsg = sqlite3MPrintf(db, "unrecognized token: \"%T\"",
106784                        &pParse->sLastToken);
106785        nErr++;
106786        goto abort_parse;
106787      }
106788      case TK_SEMI: {
106789        pParse->zTail = &zSql[i];
106790        /* Fall thru into the default case */
106791      }
106792      default: {
106793        sqlite3Parser(pEngine, tokenType, pParse->sLastToken, pParse);
106794        lastTokenParsed = tokenType;
106795        if( pParse->rc!=SQLITE_OK ){
106796          goto abort_parse;
106797        }
106798        break;
106799      }
106800    }
106801  }
106802abort_parse:
106803  if( zSql[i]==0 && nErr==0 && pParse->rc==SQLITE_OK ){
106804    if( lastTokenParsed!=TK_SEMI ){
106805      sqlite3Parser(pEngine, TK_SEMI, pParse->sLastToken, pParse);
106806      pParse->zTail = &zSql[i];
106807    }
106808    sqlite3Parser(pEngine, 0, pParse->sLastToken, pParse);
106809  }
106810#ifdef YYTRACKMAXSTACKDEPTH
106811  sqlite3StatusSet(SQLITE_STATUS_PARSER_STACK,
106812      sqlite3ParserStackPeak(pEngine)
106813  );
106814#endif /* YYDEBUG */
106815  sqlite3ParserFree(pEngine, sqlite3_free);
106816  db->lookaside.bEnabled = enableLookaside;
106817  if( db->mallocFailed ){
106818    pParse->rc = SQLITE_NOMEM;
106819  }
106820  if( pParse->rc!=SQLITE_OK && pParse->rc!=SQLITE_DONE && pParse->zErrMsg==0 ){
106821    sqlite3SetString(&pParse->zErrMsg, db, "%s", sqlite3ErrStr(pParse->rc));
106822  }
106823  assert( pzErrMsg!=0 );
106824  if( pParse->zErrMsg ){
106825    *pzErrMsg = pParse->zErrMsg;
106826    sqlite3_log(pParse->rc, "%s", *pzErrMsg);
106827    pParse->zErrMsg = 0;
106828    nErr++;
106829  }
106830  if( pParse->pVdbe && pParse->nErr>0 && pParse->nested==0 ){
106831    sqlite3VdbeDelete(pParse->pVdbe);
106832    pParse->pVdbe = 0;
106833  }
106834#ifndef SQLITE_OMIT_SHARED_CACHE
106835  if( pParse->nested==0 ){
106836    sqlite3DbFree(db, pParse->aTableLock);
106837    pParse->aTableLock = 0;
106838    pParse->nTableLock = 0;
106839  }
106840#endif
106841#ifndef SQLITE_OMIT_VIRTUALTABLE
106842  sqlite3_free(pParse->apVtabLock);
106843#endif
106844
106845  if( !IN_DECLARE_VTAB ){
106846    /* If the pParse->declareVtab flag is set, do not delete any table
106847    ** structure built up in pParse->pNewTable. The calling code (see vtab.c)
106848    ** will take responsibility for freeing the Table structure.
106849    */
106850    sqlite3DeleteTable(db, pParse->pNewTable);
106851  }
106852
106853  sqlite3DeleteTrigger(db, pParse->pNewTrigger);
106854  sqlite3DbFree(db, pParse->apVarExpr);
106855  sqlite3DbFree(db, pParse->aAlias);
106856  while( pParse->pAinc ){
106857    AutoincInfo *p = pParse->pAinc;
106858    pParse->pAinc = p->pNext;
106859    sqlite3DbFree(db, p);
106860  }
106861  while( pParse->pZombieTab ){
106862    Table *p = pParse->pZombieTab;
106863    pParse->pZombieTab = p->pNextZombie;
106864    sqlite3DeleteTable(db, p);
106865  }
106866  if( nErr>0 && pParse->rc==SQLITE_OK ){
106867    pParse->rc = SQLITE_ERROR;
106868  }
106869  return nErr;
106870}
106871
106872/************** End of tokenize.c ********************************************/
106873/************** Begin file complete.c ****************************************/
106874/*
106875** 2001 September 15
106876**
106877** The author disclaims copyright to this source code.  In place of
106878** a legal notice, here is a blessing:
106879**
106880**    May you do good and not evil.
106881**    May you find forgiveness for yourself and forgive others.
106882**    May you share freely, never taking more than you give.
106883**
106884*************************************************************************
106885** An tokenizer for SQL
106886**
106887** This file contains C code that implements the sqlite3_complete() API.
106888** This code used to be part of the tokenizer.c source file.  But by
106889** separating it out, the code will be automatically omitted from
106890** static links that do not use it.
106891*/
106892#ifndef SQLITE_OMIT_COMPLETE
106893
106894/*
106895** This is defined in tokenize.c.  We just have to import the definition.
106896*/
106897#ifndef SQLITE_AMALGAMATION
106898#ifdef SQLITE_ASCII
106899#define IdChar(C)  ((sqlite3CtypeMap[(unsigned char)C]&0x46)!=0)
106900#endif
106901#ifdef SQLITE_EBCDIC
106902SQLITE_PRIVATE const char sqlite3IsEbcdicIdChar[];
106903#define IdChar(C)  (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40]))
106904#endif
106905#endif /* SQLITE_AMALGAMATION */
106906
106907
106908/*
106909** Token types used by the sqlite3_complete() routine.  See the header
106910** comments on that procedure for additional information.
106911*/
106912#define tkSEMI    0
106913#define tkWS      1
106914#define tkOTHER   2
106915#ifndef SQLITE_OMIT_TRIGGER
106916#define tkEXPLAIN 3
106917#define tkCREATE  4
106918#define tkTEMP    5
106919#define tkTRIGGER 6
106920#define tkEND     7
106921#endif
106922
106923/*
106924** Return TRUE if the given SQL string ends in a semicolon.
106925**
106926** Special handling is require for CREATE TRIGGER statements.
106927** Whenever the CREATE TRIGGER keywords are seen, the statement
106928** must end with ";END;".
106929**
106930** This implementation uses a state machine with 8 states:
106931**
106932**   (0) INVALID   We have not yet seen a non-whitespace character.
106933**
106934**   (1) START     At the beginning or end of an SQL statement.  This routine
106935**                 returns 1 if it ends in the START state and 0 if it ends
106936**                 in any other state.
106937**
106938**   (2) NORMAL    We are in the middle of statement which ends with a single
106939**                 semicolon.
106940**
106941**   (3) EXPLAIN   The keyword EXPLAIN has been seen at the beginning of
106942**                 a statement.
106943**
106944**   (4) CREATE    The keyword CREATE has been seen at the beginning of a
106945**                 statement, possibly preceeded by EXPLAIN and/or followed by
106946**                 TEMP or TEMPORARY
106947**
106948**   (5) TRIGGER   We are in the middle of a trigger definition that must be
106949**                 ended by a semicolon, the keyword END, and another semicolon.
106950**
106951**   (6) SEMI      We've seen the first semicolon in the ";END;" that occurs at
106952**                 the end of a trigger definition.
106953**
106954**   (7) END       We've seen the ";END" of the ";END;" that occurs at the end
106955**                 of a trigger difinition.
106956**
106957** Transitions between states above are determined by tokens extracted
106958** from the input.  The following tokens are significant:
106959**
106960**   (0) tkSEMI      A semicolon.
106961**   (1) tkWS        Whitespace.
106962**   (2) tkOTHER     Any other SQL token.
106963**   (3) tkEXPLAIN   The "explain" keyword.
106964**   (4) tkCREATE    The "create" keyword.
106965**   (5) tkTEMP      The "temp" or "temporary" keyword.
106966**   (6) tkTRIGGER   The "trigger" keyword.
106967**   (7) tkEND       The "end" keyword.
106968**
106969** Whitespace never causes a state transition and is always ignored.
106970** This means that a SQL string of all whitespace is invalid.
106971**
106972** If we compile with SQLITE_OMIT_TRIGGER, all of the computation needed
106973** to recognize the end of a trigger can be omitted.  All we have to do
106974** is look for a semicolon that is not part of an string or comment.
106975*/
106976SQLITE_API int sqlite3_complete(const char *zSql){
106977  u8 state = 0;   /* Current state, using numbers defined in header comment */
106978  u8 token;       /* Value of the next token */
106979
106980#ifndef SQLITE_OMIT_TRIGGER
106981  /* A complex statement machine used to detect the end of a CREATE TRIGGER
106982  ** statement.  This is the normal case.
106983  */
106984  static const u8 trans[8][8] = {
106985                     /* Token:                                                */
106986     /* State:       **  SEMI  WS  OTHER  EXPLAIN  CREATE  TEMP  TRIGGER  END */
106987     /* 0 INVALID: */ {    1,  0,     2,       3,      4,    2,       2,   2, },
106988     /* 1   START: */ {    1,  1,     2,       3,      4,    2,       2,   2, },
106989     /* 2  NORMAL: */ {    1,  2,     2,       2,      2,    2,       2,   2, },
106990     /* 3 EXPLAIN: */ {    1,  3,     3,       2,      4,    2,       2,   2, },
106991     /* 4  CREATE: */ {    1,  4,     2,       2,      2,    4,       5,   2, },
106992     /* 5 TRIGGER: */ {    6,  5,     5,       5,      5,    5,       5,   5, },
106993     /* 6    SEMI: */ {    6,  6,     5,       5,      5,    5,       5,   7, },
106994     /* 7     END: */ {    1,  7,     5,       5,      5,    5,       5,   5, },
106995  };
106996#else
106997  /* If triggers are not supported by this compile then the statement machine
106998  ** used to detect the end of a statement is much simplier
106999  */
107000  static const u8 trans[3][3] = {
107001                     /* Token:           */
107002     /* State:       **  SEMI  WS  OTHER */
107003     /* 0 INVALID: */ {    1,  0,     2, },
107004     /* 1   START: */ {    1,  1,     2, },
107005     /* 2  NORMAL: */ {    1,  2,     2, },
107006  };
107007#endif /* SQLITE_OMIT_TRIGGER */
107008
107009  while( *zSql ){
107010    switch( *zSql ){
107011      case ';': {  /* A semicolon */
107012        token = tkSEMI;
107013        break;
107014      }
107015      case ' ':
107016      case '\r':
107017      case '\t':
107018      case '\n':
107019      case '\f': {  /* White space is ignored */
107020        token = tkWS;
107021        break;
107022      }
107023      case '/': {   /* C-style comments */
107024        if( zSql[1]!='*' ){
107025          token = tkOTHER;
107026          break;
107027        }
107028        zSql += 2;
107029        while( zSql[0] && (zSql[0]!='*' || zSql[1]!='/') ){ zSql++; }
107030        if( zSql[0]==0 ) return 0;
107031        zSql++;
107032        token = tkWS;
107033        break;
107034      }
107035      case '-': {   /* SQL-style comments from "--" to end of line */
107036        if( zSql[1]!='-' ){
107037          token = tkOTHER;
107038          break;
107039        }
107040        while( *zSql && *zSql!='\n' ){ zSql++; }
107041        if( *zSql==0 ) return state==1;
107042        token = tkWS;
107043        break;
107044      }
107045      case '[': {   /* Microsoft-style identifiers in [...] */
107046        zSql++;
107047        while( *zSql && *zSql!=']' ){ zSql++; }
107048        if( *zSql==0 ) return 0;
107049        token = tkOTHER;
107050        break;
107051      }
107052      case '`':     /* Grave-accent quoted symbols used by MySQL */
107053      case '"':     /* single- and double-quoted strings */
107054      case '\'': {
107055        int c = *zSql;
107056        zSql++;
107057        while( *zSql && *zSql!=c ){ zSql++; }
107058        if( *zSql==0 ) return 0;
107059        token = tkOTHER;
107060        break;
107061      }
107062      default: {
107063#ifdef SQLITE_EBCDIC
107064        unsigned char c;
107065#endif
107066        if( IdChar((u8)*zSql) ){
107067          /* Keywords and unquoted identifiers */
107068          int nId;
107069          for(nId=1; IdChar(zSql[nId]); nId++){}
107070#ifdef SQLITE_OMIT_TRIGGER
107071          token = tkOTHER;
107072#else
107073          switch( *zSql ){
107074            case 'c': case 'C': {
107075              if( nId==6 && sqlite3StrNICmp(zSql, "create", 6)==0 ){
107076                token = tkCREATE;
107077              }else{
107078                token = tkOTHER;
107079              }
107080              break;
107081            }
107082            case 't': case 'T': {
107083              if( nId==7 && sqlite3StrNICmp(zSql, "trigger", 7)==0 ){
107084                token = tkTRIGGER;
107085              }else if( nId==4 && sqlite3StrNICmp(zSql, "temp", 4)==0 ){
107086                token = tkTEMP;
107087              }else if( nId==9 && sqlite3StrNICmp(zSql, "temporary", 9)==0 ){
107088                token = tkTEMP;
107089              }else{
107090                token = tkOTHER;
107091              }
107092              break;
107093            }
107094            case 'e':  case 'E': {
107095              if( nId==3 && sqlite3StrNICmp(zSql, "end", 3)==0 ){
107096                token = tkEND;
107097              }else
107098#ifndef SQLITE_OMIT_EXPLAIN
107099              if( nId==7 && sqlite3StrNICmp(zSql, "explain", 7)==0 ){
107100                token = tkEXPLAIN;
107101              }else
107102#endif
107103              {
107104                token = tkOTHER;
107105              }
107106              break;
107107            }
107108            default: {
107109              token = tkOTHER;
107110              break;
107111            }
107112          }
107113#endif /* SQLITE_OMIT_TRIGGER */
107114          zSql += nId-1;
107115        }else{
107116          /* Operators and special symbols */
107117          token = tkOTHER;
107118        }
107119        break;
107120      }
107121    }
107122    state = trans[state][token];
107123    zSql++;
107124  }
107125  return state==1;
107126}
107127
107128#ifndef SQLITE_OMIT_UTF16
107129/*
107130** This routine is the same as the sqlite3_complete() routine described
107131** above, except that the parameter is required to be UTF-16 encoded, not
107132** UTF-8.
107133*/
107134SQLITE_API int sqlite3_complete16(const void *zSql){
107135  sqlite3_value *pVal;
107136  char const *zSql8;
107137  int rc = SQLITE_NOMEM;
107138
107139#ifndef SQLITE_OMIT_AUTOINIT
107140  rc = sqlite3_initialize();
107141  if( rc ) return rc;
107142#endif
107143  pVal = sqlite3ValueNew(0);
107144  sqlite3ValueSetStr(pVal, -1, zSql, SQLITE_UTF16NATIVE, SQLITE_STATIC);
107145  zSql8 = sqlite3ValueText(pVal, SQLITE_UTF8);
107146  if( zSql8 ){
107147    rc = sqlite3_complete(zSql8);
107148  }else{
107149    rc = SQLITE_NOMEM;
107150  }
107151  sqlite3ValueFree(pVal);
107152  return sqlite3ApiExit(0, rc);
107153}
107154#endif /* SQLITE_OMIT_UTF16 */
107155#endif /* SQLITE_OMIT_COMPLETE */
107156
107157/************** End of complete.c ********************************************/
107158/************** Begin file main.c ********************************************/
107159/*
107160** 2001 September 15
107161**
107162** The author disclaims copyright to this source code.  In place of
107163** a legal notice, here is a blessing:
107164**
107165**    May you do good and not evil.
107166**    May you find forgiveness for yourself and forgive others.
107167**    May you share freely, never taking more than you give.
107168**
107169*************************************************************************
107170** Main file for the SQLite library.  The routines in this file
107171** implement the programmer interface to the library.  Routines in
107172** other files are for internal use by SQLite and should not be
107173** accessed by users of the library.
107174*/
107175
107176#ifdef SQLITE_ENABLE_FTS3
107177/************** Include fts3.h in the middle of main.c ***********************/
107178/************** Begin file fts3.h ********************************************/
107179/*
107180** 2006 Oct 10
107181**
107182** The author disclaims copyright to this source code.  In place of
107183** a legal notice, here is a blessing:
107184**
107185**    May you do good and not evil.
107186**    May you find forgiveness for yourself and forgive others.
107187**    May you share freely, never taking more than you give.
107188**
107189******************************************************************************
107190**
107191** This header file is used by programs that want to link against the
107192** FTS3 library.  All it does is declare the sqlite3Fts3Init() interface.
107193*/
107194
107195#if 0
107196extern "C" {
107197#endif  /* __cplusplus */
107198
107199SQLITE_PRIVATE int sqlite3Fts3Init(sqlite3 *db);
107200
107201#if 0
107202}  /* extern "C" */
107203#endif  /* __cplusplus */
107204
107205/************** End of fts3.h ************************************************/
107206/************** Continuing where we left off in main.c ***********************/
107207#endif
107208#ifdef SQLITE_ENABLE_RTREE
107209/************** Include rtree.h in the middle of main.c **********************/
107210/************** Begin file rtree.h *******************************************/
107211/*
107212** 2008 May 26
107213**
107214** The author disclaims copyright to this source code.  In place of
107215** a legal notice, here is a blessing:
107216**
107217**    May you do good and not evil.
107218**    May you find forgiveness for yourself and forgive others.
107219**    May you share freely, never taking more than you give.
107220**
107221******************************************************************************
107222**
107223** This header file is used by programs that want to link against the
107224** RTREE library.  All it does is declare the sqlite3RtreeInit() interface.
107225*/
107226
107227#if 0
107228extern "C" {
107229#endif  /* __cplusplus */
107230
107231SQLITE_PRIVATE int sqlite3RtreeInit(sqlite3 *db);
107232
107233#if 0
107234}  /* extern "C" */
107235#endif  /* __cplusplus */
107236
107237/************** End of rtree.h ***********************************************/
107238/************** Continuing where we left off in main.c ***********************/
107239#endif
107240#ifdef SQLITE_ENABLE_ICU
107241/************** Include sqliteicu.h in the middle of main.c ******************/
107242/************** Begin file sqliteicu.h ***************************************/
107243/*
107244** 2008 May 26
107245**
107246** The author disclaims copyright to this source code.  In place of
107247** a legal notice, here is a blessing:
107248**
107249**    May you do good and not evil.
107250**    May you find forgiveness for yourself and forgive others.
107251**    May you share freely, never taking more than you give.
107252**
107253******************************************************************************
107254**
107255** This header file is used by programs that want to link against the
107256** ICU extension.  All it does is declare the sqlite3IcuInit() interface.
107257*/
107258
107259#if 0
107260extern "C" {
107261#endif  /* __cplusplus */
107262
107263SQLITE_PRIVATE int sqlite3IcuInit(sqlite3 *db);
107264
107265#if 0
107266}  /* extern "C" */
107267#endif  /* __cplusplus */
107268
107269
107270/************** End of sqliteicu.h *******************************************/
107271/************** Continuing where we left off in main.c ***********************/
107272#endif
107273
107274#ifndef SQLITE_AMALGAMATION
107275/* IMPLEMENTATION-OF: R-46656-45156 The sqlite3_version[] string constant
107276** contains the text of SQLITE_VERSION macro.
107277*/
107278SQLITE_API const char sqlite3_version[] = SQLITE_VERSION;
107279#endif
107280
107281/* IMPLEMENTATION-OF: R-53536-42575 The sqlite3_libversion() function returns
107282** a pointer to the to the sqlite3_version[] string constant.
107283*/
107284SQLITE_API const char *sqlite3_libversion(void){ return sqlite3_version; }
107285
107286/* IMPLEMENTATION-OF: R-63124-39300 The sqlite3_sourceid() function returns a
107287** pointer to a string constant whose value is the same as the
107288** SQLITE_SOURCE_ID C preprocessor macro.
107289*/
107290SQLITE_API const char *sqlite3_sourceid(void){ return SQLITE_SOURCE_ID; }
107291
107292/* IMPLEMENTATION-OF: R-35210-63508 The sqlite3_libversion_number() function
107293** returns an integer equal to SQLITE_VERSION_NUMBER.
107294*/
107295SQLITE_API int sqlite3_libversion_number(void){ return SQLITE_VERSION_NUMBER; }
107296
107297/* IMPLEMENTATION-OF: R-54823-41343 The sqlite3_threadsafe() function returns
107298** zero if and only if SQLite was compiled mutexing code omitted due to
107299** the SQLITE_THREADSAFE compile-time option being set to 0.
107300*/
107301SQLITE_API int sqlite3_threadsafe(void){ return SQLITE_THREADSAFE; }
107302
107303#if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
107304/*
107305** If the following function pointer is not NULL and if
107306** SQLITE_ENABLE_IOTRACE is enabled, then messages describing
107307** I/O active are written using this function.  These messages
107308** are intended for debugging activity only.
107309*/
107310SQLITE_PRIVATE void (*sqlite3IoTrace)(const char*, ...) = 0;
107311#endif
107312
107313/*
107314** If the following global variable points to a string which is the
107315** name of a directory, then that directory will be used to store
107316** temporary files.
107317**
107318** See also the "PRAGMA temp_store_directory" SQL command.
107319*/
107320SQLITE_API char *sqlite3_temp_directory = 0;
107321
107322/*
107323** Initialize SQLite.
107324**
107325** This routine must be called to initialize the memory allocation,
107326** VFS, and mutex subsystems prior to doing any serious work with
107327** SQLite.  But as long as you do not compile with SQLITE_OMIT_AUTOINIT
107328** this routine will be called automatically by key routines such as
107329** sqlite3_open().
107330**
107331** This routine is a no-op except on its very first call for the process,
107332** or for the first call after a call to sqlite3_shutdown.
107333**
107334** The first thread to call this routine runs the initialization to
107335** completion.  If subsequent threads call this routine before the first
107336** thread has finished the initialization process, then the subsequent
107337** threads must block until the first thread finishes with the initialization.
107338**
107339** The first thread might call this routine recursively.  Recursive
107340** calls to this routine should not block, of course.  Otherwise the
107341** initialization process would never complete.
107342**
107343** Let X be the first thread to enter this routine.  Let Y be some other
107344** thread.  Then while the initial invocation of this routine by X is
107345** incomplete, it is required that:
107346**
107347**    *  Calls to this routine from Y must block until the outer-most
107348**       call by X completes.
107349**
107350**    *  Recursive calls to this routine from thread X return immediately
107351**       without blocking.
107352*/
107353SQLITE_API int sqlite3_initialize(void){
107354  sqlite3_mutex *pMaster;                      /* The main static mutex */
107355  int rc;                                      /* Result code */
107356
107357#ifdef SQLITE_OMIT_WSD
107358  rc = sqlite3_wsd_init(4096, 24);
107359  if( rc!=SQLITE_OK ){
107360    return rc;
107361  }
107362#endif
107363
107364  /* If SQLite is already completely initialized, then this call
107365  ** to sqlite3_initialize() should be a no-op.  But the initialization
107366  ** must be complete.  So isInit must not be set until the very end
107367  ** of this routine.
107368  */
107369  if( sqlite3GlobalConfig.isInit ) return SQLITE_OK;
107370
107371  /* Make sure the mutex subsystem is initialized.  If unable to
107372  ** initialize the mutex subsystem, return early with the error.
107373  ** If the system is so sick that we are unable to allocate a mutex,
107374  ** there is not much SQLite is going to be able to do.
107375  **
107376  ** The mutex subsystem must take care of serializing its own
107377  ** initialization.
107378  */
107379  rc = sqlite3MutexInit();
107380  if( rc ) return rc;
107381
107382  /* Initialize the malloc() system and the recursive pInitMutex mutex.
107383  ** This operation is protected by the STATIC_MASTER mutex.  Note that
107384  ** MutexAlloc() is called for a static mutex prior to initializing the
107385  ** malloc subsystem - this implies that the allocation of a static
107386  ** mutex must not require support from the malloc subsystem.
107387  */
107388  pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
107389  sqlite3_mutex_enter(pMaster);
107390  sqlite3GlobalConfig.isMutexInit = 1;
107391  if( !sqlite3GlobalConfig.isMallocInit ){
107392    rc = sqlite3MallocInit();
107393  }
107394  if( rc==SQLITE_OK ){
107395    sqlite3GlobalConfig.isMallocInit = 1;
107396    if( !sqlite3GlobalConfig.pInitMutex ){
107397      sqlite3GlobalConfig.pInitMutex =
107398           sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);
107399      if( sqlite3GlobalConfig.bCoreMutex && !sqlite3GlobalConfig.pInitMutex ){
107400        rc = SQLITE_NOMEM;
107401      }
107402    }
107403  }
107404  if( rc==SQLITE_OK ){
107405    sqlite3GlobalConfig.nRefInitMutex++;
107406  }
107407  sqlite3_mutex_leave(pMaster);
107408
107409  /* If rc is not SQLITE_OK at this point, then either the malloc
107410  ** subsystem could not be initialized or the system failed to allocate
107411  ** the pInitMutex mutex. Return an error in either case.  */
107412  if( rc!=SQLITE_OK ){
107413    return rc;
107414  }
107415
107416  /* Do the rest of the initialization under the recursive mutex so
107417  ** that we will be able to handle recursive calls into
107418  ** sqlite3_initialize().  The recursive calls normally come through
107419  ** sqlite3_os_init() when it invokes sqlite3_vfs_register(), but other
107420  ** recursive calls might also be possible.
107421  **
107422  ** IMPLEMENTATION-OF: R-00140-37445 SQLite automatically serializes calls
107423  ** to the xInit method, so the xInit method need not be threadsafe.
107424  **
107425  ** The following mutex is what serializes access to the appdef pcache xInit
107426  ** methods.  The sqlite3_pcache_methods.xInit() all is embedded in the
107427  ** call to sqlite3PcacheInitialize().
107428  */
107429  sqlite3_mutex_enter(sqlite3GlobalConfig.pInitMutex);
107430  if( sqlite3GlobalConfig.isInit==0 && sqlite3GlobalConfig.inProgress==0 ){
107431    FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
107432    sqlite3GlobalConfig.inProgress = 1;
107433    memset(pHash, 0, sizeof(sqlite3GlobalFunctions));
107434    sqlite3RegisterGlobalFunctions();
107435    if( sqlite3GlobalConfig.isPCacheInit==0 ){
107436      rc = sqlite3PcacheInitialize();
107437    }
107438    if( rc==SQLITE_OK ){
107439      sqlite3GlobalConfig.isPCacheInit = 1;
107440      rc = sqlite3OsInit();
107441    }
107442    if( rc==SQLITE_OK ){
107443      sqlite3PCacheBufferSetup( sqlite3GlobalConfig.pPage,
107444          sqlite3GlobalConfig.szPage, sqlite3GlobalConfig.nPage);
107445      sqlite3GlobalConfig.isInit = 1;
107446    }
107447    sqlite3GlobalConfig.inProgress = 0;
107448  }
107449  sqlite3_mutex_leave(sqlite3GlobalConfig.pInitMutex);
107450
107451  /* Go back under the static mutex and clean up the recursive
107452  ** mutex to prevent a resource leak.
107453  */
107454  sqlite3_mutex_enter(pMaster);
107455  sqlite3GlobalConfig.nRefInitMutex--;
107456  if( sqlite3GlobalConfig.nRefInitMutex<=0 ){
107457    assert( sqlite3GlobalConfig.nRefInitMutex==0 );
107458    sqlite3_mutex_free(sqlite3GlobalConfig.pInitMutex);
107459    sqlite3GlobalConfig.pInitMutex = 0;
107460  }
107461  sqlite3_mutex_leave(pMaster);
107462
107463  /* The following is just a sanity check to make sure SQLite has
107464  ** been compiled correctly.  It is important to run this code, but
107465  ** we don't want to run it too often and soak up CPU cycles for no
107466  ** reason.  So we run it once during initialization.
107467  */
107468#ifndef NDEBUG
107469#ifndef SQLITE_OMIT_FLOATING_POINT
107470  /* This section of code's only "output" is via assert() statements. */
107471  if ( rc==SQLITE_OK ){
107472    u64 x = (((u64)1)<<63)-1;
107473    double y;
107474    assert(sizeof(x)==8);
107475    assert(sizeof(x)==sizeof(y));
107476    memcpy(&y, &x, 8);
107477    assert( sqlite3IsNaN(y) );
107478  }
107479#endif
107480#endif
107481
107482  return rc;
107483}
107484
107485/*
107486** Undo the effects of sqlite3_initialize().  Must not be called while
107487** there are outstanding database connections or memory allocations or
107488** while any part of SQLite is otherwise in use in any thread.  This
107489** routine is not threadsafe.  But it is safe to invoke this routine
107490** on when SQLite is already shut down.  If SQLite is already shut down
107491** when this routine is invoked, then this routine is a harmless no-op.
107492*/
107493SQLITE_API int sqlite3_shutdown(void){
107494  if( sqlite3GlobalConfig.isInit ){
107495    sqlite3_os_end();
107496    sqlite3_reset_auto_extension();
107497    sqlite3GlobalConfig.isInit = 0;
107498  }
107499  if( sqlite3GlobalConfig.isPCacheInit ){
107500    sqlite3PcacheShutdown();
107501    sqlite3GlobalConfig.isPCacheInit = 0;
107502  }
107503  if( sqlite3GlobalConfig.isMallocInit ){
107504    sqlite3MallocEnd();
107505    sqlite3GlobalConfig.isMallocInit = 0;
107506  }
107507  if( sqlite3GlobalConfig.isMutexInit ){
107508    sqlite3MutexEnd();
107509    sqlite3GlobalConfig.isMutexInit = 0;
107510  }
107511
107512  return SQLITE_OK;
107513}
107514
107515/*
107516** This API allows applications to modify the global configuration of
107517** the SQLite library at run-time.
107518**
107519** This routine should only be called when there are no outstanding
107520** database connections or memory allocations.  This routine is not
107521** threadsafe.  Failure to heed these warnings can lead to unpredictable
107522** behavior.
107523*/
107524SQLITE_API int sqlite3_config(int op, ...){
107525  va_list ap;
107526  int rc = SQLITE_OK;
107527
107528  /* sqlite3_config() shall return SQLITE_MISUSE if it is invoked while
107529  ** the SQLite library is in use. */
107530  if( sqlite3GlobalConfig.isInit ) return SQLITE_MISUSE_BKPT;
107531
107532  va_start(ap, op);
107533  switch( op ){
107534
107535    /* Mutex configuration options are only available in a threadsafe
107536    ** compile.
107537    */
107538#if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0
107539    case SQLITE_CONFIG_SINGLETHREAD: {
107540      /* Disable all mutexing */
107541      sqlite3GlobalConfig.bCoreMutex = 0;
107542      sqlite3GlobalConfig.bFullMutex = 0;
107543      break;
107544    }
107545    case SQLITE_CONFIG_MULTITHREAD: {
107546      /* Disable mutexing of database connections */
107547      /* Enable mutexing of core data structures */
107548      sqlite3GlobalConfig.bCoreMutex = 1;
107549      sqlite3GlobalConfig.bFullMutex = 0;
107550      break;
107551    }
107552    case SQLITE_CONFIG_SERIALIZED: {
107553      /* Enable all mutexing */
107554      sqlite3GlobalConfig.bCoreMutex = 1;
107555      sqlite3GlobalConfig.bFullMutex = 1;
107556      break;
107557    }
107558    case SQLITE_CONFIG_MUTEX: {
107559      /* Specify an alternative mutex implementation */
107560      sqlite3GlobalConfig.mutex = *va_arg(ap, sqlite3_mutex_methods*);
107561      break;
107562    }
107563    case SQLITE_CONFIG_GETMUTEX: {
107564      /* Retrieve the current mutex implementation */
107565      *va_arg(ap, sqlite3_mutex_methods*) = sqlite3GlobalConfig.mutex;
107566      break;
107567    }
107568#endif
107569
107570
107571    case SQLITE_CONFIG_MALLOC: {
107572      /* Specify an alternative malloc implementation */
107573      sqlite3GlobalConfig.m = *va_arg(ap, sqlite3_mem_methods*);
107574      break;
107575    }
107576    case SQLITE_CONFIG_GETMALLOC: {
107577      /* Retrieve the current malloc() implementation */
107578      if( sqlite3GlobalConfig.m.xMalloc==0 ) sqlite3MemSetDefault();
107579      *va_arg(ap, sqlite3_mem_methods*) = sqlite3GlobalConfig.m;
107580      break;
107581    }
107582    case SQLITE_CONFIG_MEMSTATUS: {
107583      /* Enable or disable the malloc status collection */
107584      sqlite3GlobalConfig.bMemstat = va_arg(ap, int);
107585      break;
107586    }
107587    case SQLITE_CONFIG_SCRATCH: {
107588      /* Designate a buffer for scratch memory space */
107589      sqlite3GlobalConfig.pScratch = va_arg(ap, void*);
107590      sqlite3GlobalConfig.szScratch = va_arg(ap, int);
107591      sqlite3GlobalConfig.nScratch = va_arg(ap, int);
107592      break;
107593    }
107594    case SQLITE_CONFIG_PAGECACHE: {
107595      /* Designate a buffer for page cache memory space */
107596      sqlite3GlobalConfig.pPage = va_arg(ap, void*);
107597      sqlite3GlobalConfig.szPage = va_arg(ap, int);
107598      sqlite3GlobalConfig.nPage = va_arg(ap, int);
107599      break;
107600    }
107601
107602    case SQLITE_CONFIG_PCACHE: {
107603      /* Specify an alternative page cache implementation */
107604      sqlite3GlobalConfig.pcache = *va_arg(ap, sqlite3_pcache_methods*);
107605      break;
107606    }
107607
107608    case SQLITE_CONFIG_GETPCACHE: {
107609      if( sqlite3GlobalConfig.pcache.xInit==0 ){
107610        sqlite3PCacheSetDefault();
107611      }
107612      *va_arg(ap, sqlite3_pcache_methods*) = sqlite3GlobalConfig.pcache;
107613      break;
107614    }
107615
107616#if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
107617    case SQLITE_CONFIG_HEAP: {
107618      /* Designate a buffer for heap memory space */
107619      sqlite3GlobalConfig.pHeap = va_arg(ap, void*);
107620      sqlite3GlobalConfig.nHeap = va_arg(ap, int);
107621      sqlite3GlobalConfig.mnReq = va_arg(ap, int);
107622
107623      if( sqlite3GlobalConfig.mnReq<1 ){
107624        sqlite3GlobalConfig.mnReq = 1;
107625      }else if( sqlite3GlobalConfig.mnReq>(1<<12) ){
107626        /* cap min request size at 2^12 */
107627        sqlite3GlobalConfig.mnReq = (1<<12);
107628      }
107629
107630      if( sqlite3GlobalConfig.pHeap==0 ){
107631        /* If the heap pointer is NULL, then restore the malloc implementation
107632        ** back to NULL pointers too.  This will cause the malloc to go
107633        ** back to its default implementation when sqlite3_initialize() is
107634        ** run.
107635        */
107636        memset(&sqlite3GlobalConfig.m, 0, sizeof(sqlite3GlobalConfig.m));
107637      }else{
107638        /* The heap pointer is not NULL, then install one of the
107639        ** mem5.c/mem3.c methods. If neither ENABLE_MEMSYS3 nor
107640        ** ENABLE_MEMSYS5 is defined, return an error.
107641        */
107642#ifdef SQLITE_ENABLE_MEMSYS3
107643        sqlite3GlobalConfig.m = *sqlite3MemGetMemsys3();
107644#endif
107645#ifdef SQLITE_ENABLE_MEMSYS5
107646        sqlite3GlobalConfig.m = *sqlite3MemGetMemsys5();
107647#endif
107648      }
107649      break;
107650    }
107651#endif
107652
107653    case SQLITE_CONFIG_LOOKASIDE: {
107654      sqlite3GlobalConfig.szLookaside = va_arg(ap, int);
107655      sqlite3GlobalConfig.nLookaside = va_arg(ap, int);
107656      break;
107657    }
107658
107659    /* Record a pointer to the logger funcction and its first argument.
107660    ** The default is NULL.  Logging is disabled if the function pointer is
107661    ** NULL.
107662    */
107663    case SQLITE_CONFIG_LOG: {
107664      /* MSVC is picky about pulling func ptrs from va lists.
107665      ** http://support.microsoft.com/kb/47961
107666      ** sqlite3GlobalConfig.xLog = va_arg(ap, void(*)(void*,int,const char*));
107667      */
107668      typedef void(*LOGFUNC_t)(void*,int,const char*);
107669      sqlite3GlobalConfig.xLog = va_arg(ap, LOGFUNC_t);
107670      sqlite3GlobalConfig.pLogArg = va_arg(ap, void*);
107671      break;
107672    }
107673
107674    default: {
107675      rc = SQLITE_ERROR;
107676      break;
107677    }
107678  }
107679  va_end(ap);
107680  return rc;
107681}
107682
107683/*
107684** Set up the lookaside buffers for a database connection.
107685** Return SQLITE_OK on success.
107686** If lookaside is already active, return SQLITE_BUSY.
107687**
107688** The sz parameter is the number of bytes in each lookaside slot.
107689** The cnt parameter is the number of slots.  If pStart is NULL the
107690** space for the lookaside memory is obtained from sqlite3_malloc().
107691** If pStart is not NULL then it is sz*cnt bytes of memory to use for
107692** the lookaside memory.
107693*/
107694static int setupLookaside(sqlite3 *db, void *pBuf, int sz, int cnt){
107695  void *pStart;
107696  if( db->lookaside.nOut ){
107697    return SQLITE_BUSY;
107698  }
107699  /* Free any existing lookaside buffer for this handle before
107700  ** allocating a new one so we don't have to have space for
107701  ** both at the same time.
107702  */
107703  if( db->lookaside.bMalloced ){
107704    sqlite3_free(db->lookaside.pStart);
107705  }
107706  /* The size of a lookaside slot needs to be larger than a pointer
107707  ** to be useful.
107708  */
107709  if( sz<=(int)sizeof(LookasideSlot*) ) sz = 0;
107710  if( cnt<0 ) cnt = 0;
107711  if( sz==0 || cnt==0 ){
107712    sz = 0;
107713    pStart = 0;
107714  }else if( pBuf==0 ){
107715    sz = ROUNDDOWN8(sz); /* IMP: R-33038-09382 */
107716    sqlite3BeginBenignMalloc();
107717    pStart = sqlite3Malloc( sz*cnt );  /* IMP: R-61949-35727 */
107718    sqlite3EndBenignMalloc();
107719  }else{
107720    sz = ROUNDDOWN8(sz); /* IMP: R-33038-09382 */
107721    pStart = pBuf;
107722  }
107723  db->lookaside.pStart = pStart;
107724  db->lookaside.pFree = 0;
107725  db->lookaside.sz = (u16)sz;
107726  if( pStart ){
107727    int i;
107728    LookasideSlot *p;
107729    assert( sz > (int)sizeof(LookasideSlot*) );
107730    p = (LookasideSlot*)pStart;
107731    for(i=cnt-1; i>=0; i--){
107732      p->pNext = db->lookaside.pFree;
107733      db->lookaside.pFree = p;
107734      p = (LookasideSlot*)&((u8*)p)[sz];
107735    }
107736    db->lookaside.pEnd = p;
107737    db->lookaside.bEnabled = 1;
107738    db->lookaside.bMalloced = pBuf==0 ?1:0;
107739  }else{
107740    db->lookaside.pEnd = 0;
107741    db->lookaside.bEnabled = 0;
107742    db->lookaside.bMalloced = 0;
107743  }
107744  return SQLITE_OK;
107745}
107746
107747/*
107748** Return the mutex associated with a database connection.
107749*/
107750SQLITE_API sqlite3_mutex *sqlite3_db_mutex(sqlite3 *db){
107751  return db->mutex;
107752}
107753
107754/*
107755** Configuration settings for an individual database connection
107756*/
107757SQLITE_API int sqlite3_db_config(sqlite3 *db, int op, ...){
107758  va_list ap;
107759  int rc;
107760  va_start(ap, op);
107761  switch( op ){
107762    case SQLITE_DBCONFIG_LOOKASIDE: {
107763      void *pBuf = va_arg(ap, void*); /* IMP: R-26835-10964 */
107764      int sz = va_arg(ap, int);       /* IMP: R-47871-25994 */
107765      int cnt = va_arg(ap, int);      /* IMP: R-04460-53386 */
107766      rc = setupLookaside(db, pBuf, sz, cnt);
107767      break;
107768    }
107769    default: {
107770      static const struct {
107771        int op;      /* The opcode */
107772        u32 mask;    /* Mask of the bit in sqlite3.flags to set/clear */
107773      } aFlagOp[] = {
107774        { SQLITE_DBCONFIG_ENABLE_FKEY,    SQLITE_ForeignKeys    },
107775        { SQLITE_DBCONFIG_ENABLE_TRIGGER, SQLITE_EnableTrigger  },
107776      };
107777      unsigned int i;
107778      rc = SQLITE_ERROR; /* IMP: R-42790-23372 */
107779      for(i=0; i<ArraySize(aFlagOp); i++){
107780        if( aFlagOp[i].op==op ){
107781          int onoff = va_arg(ap, int);
107782          int *pRes = va_arg(ap, int*);
107783          int oldFlags = db->flags;
107784          if( onoff>0 ){
107785            db->flags |= aFlagOp[i].mask;
107786          }else if( onoff==0 ){
107787            db->flags &= ~aFlagOp[i].mask;
107788          }
107789          if( oldFlags!=db->flags ){
107790            sqlite3ExpirePreparedStatements(db);
107791          }
107792          if( pRes ){
107793            *pRes = (db->flags & aFlagOp[i].mask)!=0;
107794          }
107795          rc = SQLITE_OK;
107796          break;
107797        }
107798      }
107799      break;
107800    }
107801  }
107802  va_end(ap);
107803  return rc;
107804}
107805
107806
107807/*
107808** Return true if the buffer z[0..n-1] contains all spaces.
107809*/
107810static int allSpaces(const char *z, int n){
107811  while( n>0 && z[n-1]==' ' ){ n--; }
107812  return n==0;
107813}
107814
107815/*
107816** This is the default collating function named "BINARY" which is always
107817** available.
107818**
107819** If the padFlag argument is not NULL then space padding at the end
107820** of strings is ignored.  This implements the RTRIM collation.
107821*/
107822static int binCollFunc(
107823  void *padFlag,
107824  int nKey1, const void *pKey1,
107825  int nKey2, const void *pKey2
107826){
107827  int rc, n;
107828  n = nKey1<nKey2 ? nKey1 : nKey2;
107829  rc = memcmp(pKey1, pKey2, n);
107830  if( rc==0 ){
107831    if( padFlag
107832     && allSpaces(((char*)pKey1)+n, nKey1-n)
107833     && allSpaces(((char*)pKey2)+n, nKey2-n)
107834    ){
107835      /* Leave rc unchanged at 0 */
107836    }else{
107837      rc = nKey1 - nKey2;
107838    }
107839  }
107840  return rc;
107841}
107842
107843/*
107844** Another built-in collating sequence: NOCASE.
107845**
107846** This collating sequence is intended to be used for "case independant
107847** comparison". SQLite's knowledge of upper and lower case equivalents
107848** extends only to the 26 characters used in the English language.
107849**
107850** At the moment there is only a UTF-8 implementation.
107851*/
107852static int nocaseCollatingFunc(
107853  void *NotUsed,
107854  int nKey1, const void *pKey1,
107855  int nKey2, const void *pKey2
107856){
107857  int r = sqlite3StrNICmp(
107858      (const char *)pKey1, (const char *)pKey2, (nKey1<nKey2)?nKey1:nKey2);
107859  UNUSED_PARAMETER(NotUsed);
107860  if( 0==r ){
107861    r = nKey1-nKey2;
107862  }
107863  return r;
107864}
107865
107866/*
107867** Return the ROWID of the most recent insert
107868*/
107869SQLITE_API sqlite_int64 sqlite3_last_insert_rowid(sqlite3 *db){
107870  return db->lastRowid;
107871}
107872
107873/*
107874** Return the number of changes in the most recent call to sqlite3_exec().
107875*/
107876SQLITE_API int sqlite3_changes(sqlite3 *db){
107877  return db->nChange;
107878}
107879
107880/*
107881** Return the number of changes since the database handle was opened.
107882*/
107883SQLITE_API int sqlite3_total_changes(sqlite3 *db){
107884  return db->nTotalChange;
107885}
107886
107887/*
107888** Close all open savepoints. This function only manipulates fields of the
107889** database handle object, it does not close any savepoints that may be open
107890** at the b-tree/pager level.
107891*/
107892SQLITE_PRIVATE void sqlite3CloseSavepoints(sqlite3 *db){
107893  while( db->pSavepoint ){
107894    Savepoint *pTmp = db->pSavepoint;
107895    db->pSavepoint = pTmp->pNext;
107896    sqlite3DbFree(db, pTmp);
107897  }
107898  db->nSavepoint = 0;
107899  db->nStatement = 0;
107900  db->isTransactionSavepoint = 0;
107901}
107902
107903/*
107904** Invoke the destructor function associated with FuncDef p, if any. Except,
107905** if this is not the last copy of the function, do not invoke it. Multiple
107906** copies of a single function are created when create_function() is called
107907** with SQLITE_ANY as the encoding.
107908*/
107909static void functionDestroy(sqlite3 *db, FuncDef *p){
107910  FuncDestructor *pDestructor = p->pDestructor;
107911  if( pDestructor ){
107912    pDestructor->nRef--;
107913    if( pDestructor->nRef==0 ){
107914      pDestructor->xDestroy(pDestructor->pUserData);
107915      sqlite3DbFree(db, pDestructor);
107916    }
107917  }
107918}
107919
107920/*
107921** Close an existing SQLite database
107922*/
107923SQLITE_API int sqlite3_close(sqlite3 *db){
107924  HashElem *i;                    /* Hash table iterator */
107925  int j;
107926
107927  if( !db ){
107928    return SQLITE_OK;
107929  }
107930  if( !sqlite3SafetyCheckSickOrOk(db) ){
107931    return SQLITE_MISUSE_BKPT;
107932  }
107933  sqlite3_mutex_enter(db->mutex);
107934
107935  /* Force xDestroy calls on all virtual tables */
107936  sqlite3ResetInternalSchema(db, -1);
107937
107938  /* If a transaction is open, the ResetInternalSchema() call above
107939  ** will not have called the xDisconnect() method on any virtual
107940  ** tables in the db->aVTrans[] array. The following sqlite3VtabRollback()
107941  ** call will do so. We need to do this before the check for active
107942  ** SQL statements below, as the v-table implementation may be storing
107943  ** some prepared statements internally.
107944  */
107945  sqlite3VtabRollback(db);
107946
107947  /* If there are any outstanding VMs, return SQLITE_BUSY. */
107948  if( db->pVdbe ){
107949    sqlite3Error(db, SQLITE_BUSY,
107950        "unable to close due to unfinalised statements");
107951    sqlite3_mutex_leave(db->mutex);
107952    return SQLITE_BUSY;
107953  }
107954  assert( sqlite3SafetyCheckSickOrOk(db) );
107955
107956  for(j=0; j<db->nDb; j++){
107957    Btree *pBt = db->aDb[j].pBt;
107958    if( pBt && sqlite3BtreeIsInBackup(pBt) ){
107959      sqlite3Error(db, SQLITE_BUSY,
107960          "unable to close due to unfinished backup operation");
107961      sqlite3_mutex_leave(db->mutex);
107962      return SQLITE_BUSY;
107963    }
107964  }
107965
107966  /* Free any outstanding Savepoint structures. */
107967  sqlite3CloseSavepoints(db);
107968
107969  for(j=0; j<db->nDb; j++){
107970    struct Db *pDb = &db->aDb[j];
107971    if( pDb->pBt ){
107972      sqlite3BtreeClose(pDb->pBt);
107973      pDb->pBt = 0;
107974      if( j!=1 ){
107975        pDb->pSchema = 0;
107976      }
107977    }
107978  }
107979  sqlite3ResetInternalSchema(db, -1);
107980
107981  /* Tell the code in notify.c that the connection no longer holds any
107982  ** locks and does not require any further unlock-notify callbacks.
107983  */
107984  sqlite3ConnectionClosed(db);
107985
107986  assert( db->nDb<=2 );
107987  assert( db->aDb==db->aDbStatic );
107988  for(j=0; j<ArraySize(db->aFunc.a); j++){
107989    FuncDef *pNext, *pHash, *p;
107990    for(p=db->aFunc.a[j]; p; p=pHash){
107991      pHash = p->pHash;
107992      while( p ){
107993        functionDestroy(db, p);
107994        pNext = p->pNext;
107995        sqlite3DbFree(db, p);
107996        p = pNext;
107997      }
107998    }
107999  }
108000  for(i=sqliteHashFirst(&db->aCollSeq); i; i=sqliteHashNext(i)){
108001    CollSeq *pColl = (CollSeq *)sqliteHashData(i);
108002    /* Invoke any destructors registered for collation sequence user data. */
108003    for(j=0; j<3; j++){
108004      if( pColl[j].xDel ){
108005        pColl[j].xDel(pColl[j].pUser);
108006      }
108007    }
108008    sqlite3DbFree(db, pColl);
108009  }
108010  sqlite3HashClear(&db->aCollSeq);
108011#ifndef SQLITE_OMIT_VIRTUALTABLE
108012  for(i=sqliteHashFirst(&db->aModule); i; i=sqliteHashNext(i)){
108013    Module *pMod = (Module *)sqliteHashData(i);
108014    if( pMod->xDestroy ){
108015      pMod->xDestroy(pMod->pAux);
108016    }
108017    sqlite3DbFree(db, pMod);
108018  }
108019  sqlite3HashClear(&db->aModule);
108020#endif
108021
108022  sqlite3Error(db, SQLITE_OK, 0); /* Deallocates any cached error strings. */
108023  if( db->pErr ){
108024    sqlite3ValueFree(db->pErr);
108025  }
108026  sqlite3CloseExtensions(db);
108027
108028  db->magic = SQLITE_MAGIC_ERROR;
108029
108030  /* The temp-database schema is allocated differently from the other schema
108031  ** objects (using sqliteMalloc() directly, instead of sqlite3BtreeSchema()).
108032  ** So it needs to be freed here. Todo: Why not roll the temp schema into
108033  ** the same sqliteMalloc() as the one that allocates the database
108034  ** structure?
108035  */
108036  sqlite3DbFree(db, db->aDb[1].pSchema);
108037  sqlite3_mutex_leave(db->mutex);
108038  db->magic = SQLITE_MAGIC_CLOSED;
108039  sqlite3_mutex_free(db->mutex);
108040  assert( db->lookaside.nOut==0 );  /* Fails on a lookaside memory leak */
108041  if( db->lookaside.bMalloced ){
108042    sqlite3_free(db->lookaside.pStart);
108043  }
108044  sqlite3_free(db);
108045  return SQLITE_OK;
108046}
108047
108048/*
108049** Rollback all database files.
108050*/
108051SQLITE_PRIVATE void sqlite3RollbackAll(sqlite3 *db){
108052  int i;
108053  int inTrans = 0;
108054  assert( sqlite3_mutex_held(db->mutex) );
108055  sqlite3BeginBenignMalloc();
108056  for(i=0; i<db->nDb; i++){
108057    if( db->aDb[i].pBt ){
108058      if( sqlite3BtreeIsInTrans(db->aDb[i].pBt) ){
108059        inTrans = 1;
108060      }
108061      sqlite3BtreeRollback(db->aDb[i].pBt);
108062      db->aDb[i].inTrans = 0;
108063    }
108064  }
108065  sqlite3VtabRollback(db);
108066  sqlite3EndBenignMalloc();
108067
108068  if( db->flags&SQLITE_InternChanges ){
108069    sqlite3ExpirePreparedStatements(db);
108070    sqlite3ResetInternalSchema(db, -1);
108071  }
108072
108073  /* Any deferred constraint violations have now been resolved. */
108074  db->nDeferredCons = 0;
108075
108076  /* If one has been configured, invoke the rollback-hook callback */
108077  if( db->xRollbackCallback && (inTrans || !db->autoCommit) ){
108078    db->xRollbackCallback(db->pRollbackArg);
108079  }
108080}
108081
108082/*
108083** Return a static string that describes the kind of error specified in the
108084** argument.
108085*/
108086SQLITE_PRIVATE const char *sqlite3ErrStr(int rc){
108087  static const char* const aMsg[] = {
108088    /* SQLITE_OK          */ "not an error",
108089    /* SQLITE_ERROR       */ "SQL logic error or missing database",
108090    /* SQLITE_INTERNAL    */ 0,
108091    /* SQLITE_PERM        */ "access permission denied",
108092    /* SQLITE_ABORT       */ "callback requested query abort",
108093    /* SQLITE_BUSY        */ "database is locked",
108094    /* SQLITE_LOCKED      */ "database table is locked",
108095    /* SQLITE_NOMEM       */ "out of memory",
108096    /* SQLITE_READONLY    */ "attempt to write a readonly database",
108097    /* SQLITE_INTERRUPT   */ "interrupted",
108098    /* SQLITE_IOERR       */ "disk I/O error",
108099    /* SQLITE_CORRUPT     */ "database disk image is malformed",
108100    /* SQLITE_NOTFOUND    */ "unknown operation",
108101    /* SQLITE_FULL        */ "database or disk is full",
108102    /* SQLITE_CANTOPEN    */ "unable to open database file",
108103    /* SQLITE_PROTOCOL    */ "locking protocol",
108104    /* SQLITE_EMPTY       */ "table contains no data",
108105    /* SQLITE_SCHEMA      */ "database schema has changed",
108106    /* SQLITE_TOOBIG      */ "string or blob too big",
108107    /* SQLITE_CONSTRAINT  */ "constraint failed",
108108    /* SQLITE_MISMATCH    */ "datatype mismatch",
108109    /* SQLITE_MISUSE      */ "library routine called out of sequence",
108110    /* SQLITE_NOLFS       */ "large file support is disabled",
108111    /* SQLITE_AUTH        */ "authorization denied",
108112    /* SQLITE_FORMAT      */ "auxiliary database format error",
108113    /* SQLITE_RANGE       */ "bind or column index out of range",
108114    /* SQLITE_NOTADB      */ "file is encrypted or is not a database",
108115  };
108116  rc &= 0xff;
108117  if( ALWAYS(rc>=0) && rc<(int)(sizeof(aMsg)/sizeof(aMsg[0])) && aMsg[rc]!=0 ){
108118    return aMsg[rc];
108119  }else{
108120    return "unknown error";
108121  }
108122}
108123
108124/*
108125** This routine implements a busy callback that sleeps and tries
108126** again until a timeout value is reached.  The timeout value is
108127** an integer number of milliseconds passed in as the first
108128** argument.
108129*/
108130static int sqliteDefaultBusyCallback(
108131 void *ptr,               /* Database connection */
108132 int count                /* Number of times table has been busy */
108133){
108134#if SQLITE_OS_WIN || (defined(HAVE_USLEEP) && HAVE_USLEEP)
108135  static const u8 delays[] =
108136     { 1, 2, 5, 10, 15, 20, 25, 25,  25,  50,  50, 100 };
108137  static const u8 totals[] =
108138     { 0, 1, 3,  8, 18, 33, 53, 78, 103, 128, 178, 228 };
108139# define NDELAY ArraySize(delays)
108140  sqlite3 *db = (sqlite3 *)ptr;
108141  int timeout = db->busyTimeout;
108142  int delay, prior;
108143
108144  assert( count>=0 );
108145  if( count < NDELAY ){
108146    delay = delays[count];
108147    prior = totals[count];
108148  }else{
108149    delay = delays[NDELAY-1];
108150    prior = totals[NDELAY-1] + delay*(count-(NDELAY-1));
108151  }
108152  if( prior + delay > timeout ){
108153    delay = timeout - prior;
108154    if( delay<=0 ) return 0;
108155  }
108156  sqlite3OsSleep(db->pVfs, delay*1000);
108157  return 1;
108158#else
108159  sqlite3 *db = (sqlite3 *)ptr;
108160  int timeout = ((sqlite3 *)ptr)->busyTimeout;
108161  if( (count+1)*1000 > timeout ){
108162    return 0;
108163  }
108164  sqlite3OsSleep(db->pVfs, 1000000);
108165  return 1;
108166#endif
108167}
108168
108169/*
108170** Invoke the given busy handler.
108171**
108172** This routine is called when an operation failed with a lock.
108173** If this routine returns non-zero, the lock is retried.  If it
108174** returns 0, the operation aborts with an SQLITE_BUSY error.
108175*/
108176SQLITE_PRIVATE int sqlite3InvokeBusyHandler(BusyHandler *p){
108177  int rc;
108178  if( NEVER(p==0) || p->xFunc==0 || p->nBusy<0 ) return 0;
108179  rc = p->xFunc(p->pArg, p->nBusy);
108180  if( rc==0 ){
108181    p->nBusy = -1;
108182  }else{
108183    p->nBusy++;
108184  }
108185  return rc;
108186}
108187
108188/*
108189** This routine sets the busy callback for an Sqlite database to the
108190** given callback function with the given argument.
108191*/
108192SQLITE_API int sqlite3_busy_handler(
108193  sqlite3 *db,
108194  int (*xBusy)(void*,int),
108195  void *pArg
108196){
108197  sqlite3_mutex_enter(db->mutex);
108198  db->busyHandler.xFunc = xBusy;
108199  db->busyHandler.pArg = pArg;
108200  db->busyHandler.nBusy = 0;
108201  sqlite3_mutex_leave(db->mutex);
108202  return SQLITE_OK;
108203}
108204
108205#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
108206/*
108207** This routine sets the progress callback for an Sqlite database to the
108208** given callback function with the given argument. The progress callback will
108209** be invoked every nOps opcodes.
108210*/
108211SQLITE_API void sqlite3_progress_handler(
108212  sqlite3 *db,
108213  int nOps,
108214  int (*xProgress)(void*),
108215  void *pArg
108216){
108217  sqlite3_mutex_enter(db->mutex);
108218  if( nOps>0 ){
108219    db->xProgress = xProgress;
108220    db->nProgressOps = nOps;
108221    db->pProgressArg = pArg;
108222  }else{
108223    db->xProgress = 0;
108224    db->nProgressOps = 0;
108225    db->pProgressArg = 0;
108226  }
108227  sqlite3_mutex_leave(db->mutex);
108228}
108229#endif
108230
108231
108232/*
108233** This routine installs a default busy handler that waits for the
108234** specified number of milliseconds before returning 0.
108235*/
108236SQLITE_API int sqlite3_busy_timeout(sqlite3 *db, int ms){
108237  if( ms>0 ){
108238    db->busyTimeout = ms;
108239    sqlite3_busy_handler(db, sqliteDefaultBusyCallback, (void*)db);
108240  }else{
108241    sqlite3_busy_handler(db, 0, 0);
108242  }
108243  return SQLITE_OK;
108244}
108245
108246/*
108247** Cause any pending operation to stop at its earliest opportunity.
108248*/
108249SQLITE_API void sqlite3_interrupt(sqlite3 *db){
108250  db->u1.isInterrupted = 1;
108251}
108252
108253
108254/*
108255** This function is exactly the same as sqlite3_create_function(), except
108256** that it is designed to be called by internal code. The difference is
108257** that if a malloc() fails in sqlite3_create_function(), an error code
108258** is returned and the mallocFailed flag cleared.
108259*/
108260SQLITE_PRIVATE int sqlite3CreateFunc(
108261  sqlite3 *db,
108262  const char *zFunctionName,
108263  int nArg,
108264  int enc,
108265  void *pUserData,
108266  void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
108267  void (*xStep)(sqlite3_context*,int,sqlite3_value **),
108268  void (*xFinal)(sqlite3_context*),
108269  FuncDestructor *pDestructor
108270){
108271  FuncDef *p;
108272  int nName;
108273
108274  assert( sqlite3_mutex_held(db->mutex) );
108275  if( zFunctionName==0 ||
108276      (xFunc && (xFinal || xStep)) ||
108277      (!xFunc && (xFinal && !xStep)) ||
108278      (!xFunc && (!xFinal && xStep)) ||
108279      (nArg<-1 || nArg>SQLITE_MAX_FUNCTION_ARG) ||
108280      (255<(nName = sqlite3Strlen30( zFunctionName))) ){
108281    return SQLITE_MISUSE_BKPT;
108282  }
108283
108284#ifndef SQLITE_OMIT_UTF16
108285  /* If SQLITE_UTF16 is specified as the encoding type, transform this
108286  ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
108287  ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
108288  **
108289  ** If SQLITE_ANY is specified, add three versions of the function
108290  ** to the hash table.
108291  */
108292  if( enc==SQLITE_UTF16 ){
108293    enc = SQLITE_UTF16NATIVE;
108294  }else if( enc==SQLITE_ANY ){
108295    int rc;
108296    rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF8,
108297         pUserData, xFunc, xStep, xFinal, pDestructor);
108298    if( rc==SQLITE_OK ){
108299      rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF16LE,
108300          pUserData, xFunc, xStep, xFinal, pDestructor);
108301    }
108302    if( rc!=SQLITE_OK ){
108303      return rc;
108304    }
108305    enc = SQLITE_UTF16BE;
108306  }
108307#else
108308  enc = SQLITE_UTF8;
108309#endif
108310
108311  /* Check if an existing function is being overridden or deleted. If so,
108312  ** and there are active VMs, then return SQLITE_BUSY. If a function
108313  ** is being overridden/deleted but there are no active VMs, allow the
108314  ** operation to continue but invalidate all precompiled statements.
108315  */
108316  p = sqlite3FindFunction(db, zFunctionName, nName, nArg, (u8)enc, 0);
108317  if( p && p->iPrefEnc==enc && p->nArg==nArg ){
108318    if( db->activeVdbeCnt ){
108319      sqlite3Error(db, SQLITE_BUSY,
108320        "unable to delete/modify user-function due to active statements");
108321      assert( !db->mallocFailed );
108322      return SQLITE_BUSY;
108323    }else{
108324      sqlite3ExpirePreparedStatements(db);
108325    }
108326  }
108327
108328  p = sqlite3FindFunction(db, zFunctionName, nName, nArg, (u8)enc, 1);
108329  assert(p || db->mallocFailed);
108330  if( !p ){
108331    return SQLITE_NOMEM;
108332  }
108333
108334  /* If an older version of the function with a configured destructor is
108335  ** being replaced invoke the destructor function here. */
108336  functionDestroy(db, p);
108337
108338  if( pDestructor ){
108339    pDestructor->nRef++;
108340  }
108341  p->pDestructor = pDestructor;
108342  p->flags = 0;
108343  p->xFunc = xFunc;
108344  p->xStep = xStep;
108345  p->xFinalize = xFinal;
108346  p->pUserData = pUserData;
108347  p->nArg = (u16)nArg;
108348  return SQLITE_OK;
108349}
108350
108351/*
108352** Create new user functions.
108353*/
108354SQLITE_API int sqlite3_create_function(
108355  sqlite3 *db,
108356  const char *zFunc,
108357  int nArg,
108358  int enc,
108359  void *p,
108360  void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
108361  void (*xStep)(sqlite3_context*,int,sqlite3_value **),
108362  void (*xFinal)(sqlite3_context*)
108363){
108364  return sqlite3_create_function_v2(db, zFunc, nArg, enc, p, xFunc, xStep,
108365                                    xFinal, 0);
108366}
108367
108368SQLITE_API int sqlite3_create_function_v2(
108369  sqlite3 *db,
108370  const char *zFunc,
108371  int nArg,
108372  int enc,
108373  void *p,
108374  void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
108375  void (*xStep)(sqlite3_context*,int,sqlite3_value **),
108376  void (*xFinal)(sqlite3_context*),
108377  void (*xDestroy)(void *)
108378){
108379  int rc = SQLITE_ERROR;
108380  FuncDestructor *pArg = 0;
108381  sqlite3_mutex_enter(db->mutex);
108382  if( xDestroy ){
108383    pArg = (FuncDestructor *)sqlite3DbMallocZero(db, sizeof(FuncDestructor));
108384    if( !pArg ){
108385      xDestroy(p);
108386      goto out;
108387    }
108388    pArg->xDestroy = xDestroy;
108389    pArg->pUserData = p;
108390  }
108391  rc = sqlite3CreateFunc(db, zFunc, nArg, enc, p, xFunc, xStep, xFinal, pArg);
108392  if( pArg && pArg->nRef==0 ){
108393    assert( rc!=SQLITE_OK );
108394    xDestroy(p);
108395    sqlite3DbFree(db, pArg);
108396  }
108397
108398 out:
108399  rc = sqlite3ApiExit(db, rc);
108400  sqlite3_mutex_leave(db->mutex);
108401  return rc;
108402}
108403
108404#ifndef SQLITE_OMIT_UTF16
108405SQLITE_API int sqlite3_create_function16(
108406  sqlite3 *db,
108407  const void *zFunctionName,
108408  int nArg,
108409  int eTextRep,
108410  void *p,
108411  void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
108412  void (*xStep)(sqlite3_context*,int,sqlite3_value**),
108413  void (*xFinal)(sqlite3_context*)
108414){
108415  int rc;
108416  char *zFunc8;
108417  sqlite3_mutex_enter(db->mutex);
108418  assert( !db->mallocFailed );
108419  zFunc8 = sqlite3Utf16to8(db, zFunctionName, -1, SQLITE_UTF16NATIVE);
108420  rc = sqlite3CreateFunc(db, zFunc8, nArg, eTextRep, p, xFunc, xStep, xFinal,0);
108421  sqlite3DbFree(db, zFunc8);
108422  rc = sqlite3ApiExit(db, rc);
108423  sqlite3_mutex_leave(db->mutex);
108424  return rc;
108425}
108426#endif
108427
108428
108429/*
108430** Declare that a function has been overloaded by a virtual table.
108431**
108432** If the function already exists as a regular global function, then
108433** this routine is a no-op.  If the function does not exist, then create
108434** a new one that always throws a run-time error.
108435**
108436** When virtual tables intend to provide an overloaded function, they
108437** should call this routine to make sure the global function exists.
108438** A global function must exist in order for name resolution to work
108439** properly.
108440*/
108441SQLITE_API int sqlite3_overload_function(
108442  sqlite3 *db,
108443  const char *zName,
108444  int nArg
108445){
108446  int nName = sqlite3Strlen30(zName);
108447  int rc;
108448  sqlite3_mutex_enter(db->mutex);
108449  if( sqlite3FindFunction(db, zName, nName, nArg, SQLITE_UTF8, 0)==0 ){
108450    sqlite3CreateFunc(db, zName, nArg, SQLITE_UTF8,
108451                      0, sqlite3InvalidFunction, 0, 0, 0);
108452  }
108453  rc = sqlite3ApiExit(db, SQLITE_OK);
108454  sqlite3_mutex_leave(db->mutex);
108455  return rc;
108456}
108457
108458#ifndef SQLITE_OMIT_TRACE
108459/*
108460** Register a trace function.  The pArg from the previously registered trace
108461** is returned.
108462**
108463** A NULL trace function means that no tracing is executes.  A non-NULL
108464** trace is a pointer to a function that is invoked at the start of each
108465** SQL statement.
108466*/
108467SQLITE_API void *sqlite3_trace(sqlite3 *db, void (*xTrace)(void*,const char*), void *pArg){
108468  void *pOld;
108469  sqlite3_mutex_enter(db->mutex);
108470  pOld = db->pTraceArg;
108471  db->xTrace = xTrace;
108472  db->pTraceArg = pArg;
108473  sqlite3_mutex_leave(db->mutex);
108474  return pOld;
108475}
108476/*
108477** Register a profile function.  The pArg from the previously registered
108478** profile function is returned.
108479**
108480** A NULL profile function means that no profiling is executes.  A non-NULL
108481** profile is a pointer to a function that is invoked at the conclusion of
108482** each SQL statement that is run.
108483*/
108484SQLITE_API void *sqlite3_profile(
108485  sqlite3 *db,
108486  void (*xProfile)(void*,const char*,sqlite_uint64),
108487  void *pArg
108488){
108489  void *pOld;
108490  sqlite3_mutex_enter(db->mutex);
108491  pOld = db->pProfileArg;
108492  db->xProfile = xProfile;
108493  db->pProfileArg = pArg;
108494  sqlite3_mutex_leave(db->mutex);
108495  return pOld;
108496}
108497#endif /* SQLITE_OMIT_TRACE */
108498
108499/*** EXPERIMENTAL ***
108500**
108501** Register a function to be invoked when a transaction comments.
108502** If the invoked function returns non-zero, then the commit becomes a
108503** rollback.
108504*/
108505SQLITE_API void *sqlite3_commit_hook(
108506  sqlite3 *db,              /* Attach the hook to this database */
108507  int (*xCallback)(void*),  /* Function to invoke on each commit */
108508  void *pArg                /* Argument to the function */
108509){
108510  void *pOld;
108511  sqlite3_mutex_enter(db->mutex);
108512  pOld = db->pCommitArg;
108513  db->xCommitCallback = xCallback;
108514  db->pCommitArg = pArg;
108515  sqlite3_mutex_leave(db->mutex);
108516  return pOld;
108517}
108518
108519/*
108520** Register a callback to be invoked each time a row is updated,
108521** inserted or deleted using this database connection.
108522*/
108523SQLITE_API void *sqlite3_update_hook(
108524  sqlite3 *db,              /* Attach the hook to this database */
108525  void (*xCallback)(void*,int,char const *,char const *,sqlite_int64),
108526  void *pArg                /* Argument to the function */
108527){
108528  void *pRet;
108529  sqlite3_mutex_enter(db->mutex);
108530  pRet = db->pUpdateArg;
108531  db->xUpdateCallback = xCallback;
108532  db->pUpdateArg = pArg;
108533  sqlite3_mutex_leave(db->mutex);
108534  return pRet;
108535}
108536
108537/*
108538** Register a callback to be invoked each time a transaction is rolled
108539** back by this database connection.
108540*/
108541SQLITE_API void *sqlite3_rollback_hook(
108542  sqlite3 *db,              /* Attach the hook to this database */
108543  void (*xCallback)(void*), /* Callback function */
108544  void *pArg                /* Argument to the function */
108545){
108546  void *pRet;
108547  sqlite3_mutex_enter(db->mutex);
108548  pRet = db->pRollbackArg;
108549  db->xRollbackCallback = xCallback;
108550  db->pRollbackArg = pArg;
108551  sqlite3_mutex_leave(db->mutex);
108552  return pRet;
108553}
108554
108555#ifndef SQLITE_OMIT_WAL
108556/*
108557** The sqlite3_wal_hook() callback registered by sqlite3_wal_autocheckpoint().
108558** Invoke sqlite3_wal_checkpoint if the number of frames in the log file
108559** is greater than sqlite3.pWalArg cast to an integer (the value configured by
108560** wal_autocheckpoint()).
108561*/
108562SQLITE_PRIVATE int sqlite3WalDefaultHook(
108563  void *pClientData,     /* Argument */
108564  sqlite3 *db,           /* Connection */
108565  const char *zDb,       /* Database */
108566  int nFrame             /* Size of WAL */
108567){
108568  if( nFrame>=SQLITE_PTR_TO_INT(pClientData) ){
108569    sqlite3BeginBenignMalloc();
108570    sqlite3_wal_checkpoint(db, zDb);
108571    sqlite3EndBenignMalloc();
108572  }
108573  return SQLITE_OK;
108574}
108575#endif /* SQLITE_OMIT_WAL */
108576
108577/*
108578** Configure an sqlite3_wal_hook() callback to automatically checkpoint
108579** a database after committing a transaction if there are nFrame or
108580** more frames in the log file. Passing zero or a negative value as the
108581** nFrame parameter disables automatic checkpoints entirely.
108582**
108583** The callback registered by this function replaces any existing callback
108584** registered using sqlite3_wal_hook(). Likewise, registering a callback
108585** using sqlite3_wal_hook() disables the automatic checkpoint mechanism
108586** configured by this function.
108587*/
108588SQLITE_API int sqlite3_wal_autocheckpoint(sqlite3 *db, int nFrame){
108589#ifdef SQLITE_OMIT_WAL
108590  UNUSED_PARAMETER(db);
108591  UNUSED_PARAMETER(nFrame);
108592#else
108593  if( nFrame>0 ){
108594    sqlite3_wal_hook(db, sqlite3WalDefaultHook, SQLITE_INT_TO_PTR(nFrame));
108595  }else{
108596    sqlite3_wal_hook(db, 0, 0);
108597  }
108598#endif
108599  return SQLITE_OK;
108600}
108601
108602/*
108603** Register a callback to be invoked each time a transaction is written
108604** into the write-ahead-log by this database connection.
108605*/
108606SQLITE_API void *sqlite3_wal_hook(
108607  sqlite3 *db,                    /* Attach the hook to this db handle */
108608  int(*xCallback)(void *, sqlite3*, const char*, int),
108609  void *pArg                      /* First argument passed to xCallback() */
108610){
108611#ifndef SQLITE_OMIT_WAL
108612  void *pRet;
108613  sqlite3_mutex_enter(db->mutex);
108614  pRet = db->pWalArg;
108615  db->xWalCallback = xCallback;
108616  db->pWalArg = pArg;
108617  sqlite3_mutex_leave(db->mutex);
108618  return pRet;
108619#else
108620  return 0;
108621#endif
108622}
108623
108624/*
108625** Checkpoint database zDb.
108626*/
108627SQLITE_API int sqlite3_wal_checkpoint_v2(
108628  sqlite3 *db,                    /* Database handle */
108629  const char *zDb,                /* Name of attached database (or NULL) */
108630  int eMode,                      /* SQLITE_CHECKPOINT_* value */
108631  int *pnLog,                     /* OUT: Size of WAL log in frames */
108632  int *pnCkpt                     /* OUT: Total number of frames checkpointed */
108633){
108634#ifdef SQLITE_OMIT_WAL
108635  return SQLITE_OK;
108636#else
108637  int rc;                         /* Return code */
108638  int iDb = SQLITE_MAX_ATTACHED;  /* sqlite3.aDb[] index of db to checkpoint */
108639
108640  /* Initialize the output variables to -1 in case an error occurs. */
108641  if( pnLog ) *pnLog = -1;
108642  if( pnCkpt ) *pnCkpt = -1;
108643
108644  assert( SQLITE_CHECKPOINT_FULL>SQLITE_CHECKPOINT_PASSIVE );
108645  assert( SQLITE_CHECKPOINT_FULL<SQLITE_CHECKPOINT_RESTART );
108646  assert( SQLITE_CHECKPOINT_PASSIVE+2==SQLITE_CHECKPOINT_RESTART );
108647  if( eMode<SQLITE_CHECKPOINT_PASSIVE || eMode>SQLITE_CHECKPOINT_RESTART ){
108648    return SQLITE_MISUSE;
108649  }
108650
108651  sqlite3_mutex_enter(db->mutex);
108652  if( zDb && zDb[0] ){
108653    iDb = sqlite3FindDbName(db, zDb);
108654  }
108655  if( iDb<0 ){
108656    rc = SQLITE_ERROR;
108657    sqlite3Error(db, SQLITE_ERROR, "unknown database: %s", zDb);
108658  }else{
108659    rc = sqlite3Checkpoint(db, iDb, eMode, pnLog, pnCkpt);
108660    sqlite3Error(db, rc, 0);
108661  }
108662  rc = sqlite3ApiExit(db, rc);
108663  sqlite3_mutex_leave(db->mutex);
108664  return rc;
108665#endif
108666}
108667
108668
108669/*
108670** Checkpoint database zDb. If zDb is NULL, or if the buffer zDb points
108671** to contains a zero-length string, all attached databases are
108672** checkpointed.
108673*/
108674SQLITE_API int sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb){
108675  return sqlite3_wal_checkpoint_v2(db, zDb, SQLITE_CHECKPOINT_PASSIVE, 0, 0);
108676}
108677
108678#ifndef SQLITE_OMIT_WAL
108679/*
108680** Run a checkpoint on database iDb. This is a no-op if database iDb is
108681** not currently open in WAL mode.
108682**
108683** If a transaction is open on the database being checkpointed, this
108684** function returns SQLITE_LOCKED and a checkpoint is not attempted. If
108685** an error occurs while running the checkpoint, an SQLite error code is
108686** returned (i.e. SQLITE_IOERR). Otherwise, SQLITE_OK.
108687**
108688** The mutex on database handle db should be held by the caller. The mutex
108689** associated with the specific b-tree being checkpointed is taken by
108690** this function while the checkpoint is running.
108691**
108692** If iDb is passed SQLITE_MAX_ATTACHED, then all attached databases are
108693** checkpointed. If an error is encountered it is returned immediately -
108694** no attempt is made to checkpoint any remaining databases.
108695**
108696** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
108697*/
108698SQLITE_PRIVATE int sqlite3Checkpoint(sqlite3 *db, int iDb, int eMode, int *pnLog, int *pnCkpt){
108699  int rc = SQLITE_OK;             /* Return code */
108700  int i;                          /* Used to iterate through attached dbs */
108701  int bBusy = 0;                  /* True if SQLITE_BUSY has been encountered */
108702
108703  assert( sqlite3_mutex_held(db->mutex) );
108704  assert( !pnLog || *pnLog==-1 );
108705  assert( !pnCkpt || *pnCkpt==-1 );
108706
108707  for(i=0; i<db->nDb && rc==SQLITE_OK; i++){
108708    if( i==iDb || iDb==SQLITE_MAX_ATTACHED ){
108709      rc = sqlite3BtreeCheckpoint(db->aDb[i].pBt, eMode, pnLog, pnCkpt);
108710      pnLog = 0;
108711      pnCkpt = 0;
108712      if( rc==SQLITE_BUSY ){
108713        bBusy = 1;
108714        rc = SQLITE_OK;
108715      }
108716    }
108717  }
108718
108719  return (rc==SQLITE_OK && bBusy) ? SQLITE_BUSY : rc;
108720}
108721#endif /* SQLITE_OMIT_WAL */
108722
108723/*
108724** This function returns true if main-memory should be used instead of
108725** a temporary file for transient pager files and statement journals.
108726** The value returned depends on the value of db->temp_store (runtime
108727** parameter) and the compile time value of SQLITE_TEMP_STORE. The
108728** following table describes the relationship between these two values
108729** and this functions return value.
108730**
108731**   SQLITE_TEMP_STORE     db->temp_store     Location of temporary database
108732**   -----------------     --------------     ------------------------------
108733**   0                     any                file      (return 0)
108734**   1                     1                  file      (return 0)
108735**   1                     2                  memory    (return 1)
108736**   1                     0                  file      (return 0)
108737**   2                     1                  file      (return 0)
108738**   2                     2                  memory    (return 1)
108739**   2                     0                  memory    (return 1)
108740**   3                     any                memory    (return 1)
108741*/
108742SQLITE_PRIVATE int sqlite3TempInMemory(const sqlite3 *db){
108743#if SQLITE_TEMP_STORE==1
108744  return ( db->temp_store==2 );
108745#endif
108746#if SQLITE_TEMP_STORE==2
108747  return ( db->temp_store!=1 );
108748#endif
108749#if SQLITE_TEMP_STORE==3
108750  return 1;
108751#endif
108752#if SQLITE_TEMP_STORE<1 || SQLITE_TEMP_STORE>3
108753  return 0;
108754#endif
108755}
108756
108757/*
108758** Return UTF-8 encoded English language explanation of the most recent
108759** error.
108760*/
108761SQLITE_API const char *sqlite3_errmsg(sqlite3 *db){
108762  const char *z;
108763  if( !db ){
108764    return sqlite3ErrStr(SQLITE_NOMEM);
108765  }
108766  if( !sqlite3SafetyCheckSickOrOk(db) ){
108767    return sqlite3ErrStr(SQLITE_MISUSE_BKPT);
108768  }
108769  sqlite3_mutex_enter(db->mutex);
108770  if( db->mallocFailed ){
108771    z = sqlite3ErrStr(SQLITE_NOMEM);
108772  }else{
108773    z = (char*)sqlite3_value_text(db->pErr);
108774    assert( !db->mallocFailed );
108775    if( z==0 ){
108776      z = sqlite3ErrStr(db->errCode);
108777    }
108778  }
108779  sqlite3_mutex_leave(db->mutex);
108780  return z;
108781}
108782
108783#ifndef SQLITE_OMIT_UTF16
108784/*
108785** Return UTF-16 encoded English language explanation of the most recent
108786** error.
108787*/
108788SQLITE_API const void *sqlite3_errmsg16(sqlite3 *db){
108789  static const u16 outOfMem[] = {
108790    'o', 'u', 't', ' ', 'o', 'f', ' ', 'm', 'e', 'm', 'o', 'r', 'y', 0
108791  };
108792  static const u16 misuse[] = {
108793    'l', 'i', 'b', 'r', 'a', 'r', 'y', ' ',
108794    'r', 'o', 'u', 't', 'i', 'n', 'e', ' ',
108795    'c', 'a', 'l', 'l', 'e', 'd', ' ',
108796    'o', 'u', 't', ' ',
108797    'o', 'f', ' ',
108798    's', 'e', 'q', 'u', 'e', 'n', 'c', 'e', 0
108799  };
108800
108801  const void *z;
108802  if( !db ){
108803    return (void *)outOfMem;
108804  }
108805  if( !sqlite3SafetyCheckSickOrOk(db) ){
108806    return (void *)misuse;
108807  }
108808  sqlite3_mutex_enter(db->mutex);
108809  if( db->mallocFailed ){
108810    z = (void *)outOfMem;
108811  }else{
108812    z = sqlite3_value_text16(db->pErr);
108813    if( z==0 ){
108814      sqlite3ValueSetStr(db->pErr, -1, sqlite3ErrStr(db->errCode),
108815           SQLITE_UTF8, SQLITE_STATIC);
108816      z = sqlite3_value_text16(db->pErr);
108817    }
108818    /* A malloc() may have failed within the call to sqlite3_value_text16()
108819    ** above. If this is the case, then the db->mallocFailed flag needs to
108820    ** be cleared before returning. Do this directly, instead of via
108821    ** sqlite3ApiExit(), to avoid setting the database handle error message.
108822    */
108823    db->mallocFailed = 0;
108824  }
108825  sqlite3_mutex_leave(db->mutex);
108826  return z;
108827}
108828#endif /* SQLITE_OMIT_UTF16 */
108829
108830/*
108831** Return the most recent error code generated by an SQLite routine. If NULL is
108832** passed to this function, we assume a malloc() failed during sqlite3_open().
108833*/
108834SQLITE_API int sqlite3_errcode(sqlite3 *db){
108835  if( db && !sqlite3SafetyCheckSickOrOk(db) ){
108836    return SQLITE_MISUSE_BKPT;
108837  }
108838  if( !db || db->mallocFailed ){
108839    return SQLITE_NOMEM;
108840  }
108841  return db->errCode & db->errMask;
108842}
108843SQLITE_API int sqlite3_extended_errcode(sqlite3 *db){
108844  if( db && !sqlite3SafetyCheckSickOrOk(db) ){
108845    return SQLITE_MISUSE_BKPT;
108846  }
108847  if( !db || db->mallocFailed ){
108848    return SQLITE_NOMEM;
108849  }
108850  return db->errCode;
108851}
108852
108853/*
108854** Create a new collating function for database "db".  The name is zName
108855** and the encoding is enc.
108856*/
108857static int createCollation(
108858  sqlite3* db,
108859  const char *zName,
108860  u8 enc,
108861  u8 collType,
108862  void* pCtx,
108863  int(*xCompare)(void*,int,const void*,int,const void*),
108864  void(*xDel)(void*)
108865){
108866  CollSeq *pColl;
108867  int enc2;
108868  int nName = sqlite3Strlen30(zName);
108869
108870  assert( sqlite3_mutex_held(db->mutex) );
108871
108872  /* If SQLITE_UTF16 is specified as the encoding type, transform this
108873  ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
108874  ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
108875  */
108876  enc2 = enc;
108877  testcase( enc2==SQLITE_UTF16 );
108878  testcase( enc2==SQLITE_UTF16_ALIGNED );
108879  if( enc2==SQLITE_UTF16 || enc2==SQLITE_UTF16_ALIGNED ){
108880    enc2 = SQLITE_UTF16NATIVE;
108881  }
108882  if( enc2<SQLITE_UTF8 || enc2>SQLITE_UTF16BE ){
108883    return SQLITE_MISUSE_BKPT;
108884  }
108885
108886  /* Check if this call is removing or replacing an existing collation
108887  ** sequence. If so, and there are active VMs, return busy. If there
108888  ** are no active VMs, invalidate any pre-compiled statements.
108889  */
108890  pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 0);
108891  if( pColl && pColl->xCmp ){
108892    if( db->activeVdbeCnt ){
108893      sqlite3Error(db, SQLITE_BUSY,
108894        "unable to delete/modify collation sequence due to active statements");
108895      return SQLITE_BUSY;
108896    }
108897    sqlite3ExpirePreparedStatements(db);
108898
108899    /* If collation sequence pColl was created directly by a call to
108900    ** sqlite3_create_collation, and not generated by synthCollSeq(),
108901    ** then any copies made by synthCollSeq() need to be invalidated.
108902    ** Also, collation destructor - CollSeq.xDel() - function may need
108903    ** to be called.
108904    */
108905    if( (pColl->enc & ~SQLITE_UTF16_ALIGNED)==enc2 ){
108906      CollSeq *aColl = sqlite3HashFind(&db->aCollSeq, zName, nName);
108907      int j;
108908      for(j=0; j<3; j++){
108909        CollSeq *p = &aColl[j];
108910        if( p->enc==pColl->enc ){
108911          if( p->xDel ){
108912            p->xDel(p->pUser);
108913          }
108914          p->xCmp = 0;
108915        }
108916      }
108917    }
108918  }
108919
108920  pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 1);
108921  if( pColl==0 ) return SQLITE_NOMEM;
108922  pColl->xCmp = xCompare;
108923  pColl->pUser = pCtx;
108924  pColl->xDel = xDel;
108925  pColl->enc = (u8)(enc2 | (enc & SQLITE_UTF16_ALIGNED));
108926  pColl->type = collType;
108927  sqlite3Error(db, SQLITE_OK, 0);
108928  return SQLITE_OK;
108929}
108930
108931
108932/*
108933** This array defines hard upper bounds on limit values.  The
108934** initializer must be kept in sync with the SQLITE_LIMIT_*
108935** #defines in sqlite3.h.
108936*/
108937static const int aHardLimit[] = {
108938  SQLITE_MAX_LENGTH,
108939  SQLITE_MAX_SQL_LENGTH,
108940  SQLITE_MAX_COLUMN,
108941  SQLITE_MAX_EXPR_DEPTH,
108942  SQLITE_MAX_COMPOUND_SELECT,
108943  SQLITE_MAX_VDBE_OP,
108944  SQLITE_MAX_FUNCTION_ARG,
108945  SQLITE_MAX_ATTACHED,
108946  SQLITE_MAX_LIKE_PATTERN_LENGTH,
108947  SQLITE_MAX_VARIABLE_NUMBER,
108948  SQLITE_MAX_TRIGGER_DEPTH,
108949};
108950
108951/*
108952** Make sure the hard limits are set to reasonable values
108953*/
108954#if SQLITE_MAX_LENGTH<100
108955# error SQLITE_MAX_LENGTH must be at least 100
108956#endif
108957#if SQLITE_MAX_SQL_LENGTH<100
108958# error SQLITE_MAX_SQL_LENGTH must be at least 100
108959#endif
108960#if SQLITE_MAX_SQL_LENGTH>SQLITE_MAX_LENGTH
108961# error SQLITE_MAX_SQL_LENGTH must not be greater than SQLITE_MAX_LENGTH
108962#endif
108963#if SQLITE_MAX_COMPOUND_SELECT<2
108964# error SQLITE_MAX_COMPOUND_SELECT must be at least 2
108965#endif
108966#if SQLITE_MAX_VDBE_OP<40
108967# error SQLITE_MAX_VDBE_OP must be at least 40
108968#endif
108969#if SQLITE_MAX_FUNCTION_ARG<0 || SQLITE_MAX_FUNCTION_ARG>1000
108970# error SQLITE_MAX_FUNCTION_ARG must be between 0 and 1000
108971#endif
108972#if SQLITE_MAX_ATTACHED<0 || SQLITE_MAX_ATTACHED>62
108973# error SQLITE_MAX_ATTACHED must be between 0 and 62
108974#endif
108975#if SQLITE_MAX_LIKE_PATTERN_LENGTH<1
108976# error SQLITE_MAX_LIKE_PATTERN_LENGTH must be at least 1
108977#endif
108978#if SQLITE_MAX_COLUMN>32767
108979# error SQLITE_MAX_COLUMN must not exceed 32767
108980#endif
108981#if SQLITE_MAX_TRIGGER_DEPTH<1
108982# error SQLITE_MAX_TRIGGER_DEPTH must be at least 1
108983#endif
108984
108985
108986/*
108987** Change the value of a limit.  Report the old value.
108988** If an invalid limit index is supplied, report -1.
108989** Make no changes but still report the old value if the
108990** new limit is negative.
108991**
108992** A new lower limit does not shrink existing constructs.
108993** It merely prevents new constructs that exceed the limit
108994** from forming.
108995*/
108996SQLITE_API int sqlite3_limit(sqlite3 *db, int limitId, int newLimit){
108997  int oldLimit;
108998
108999
109000  /* EVIDENCE-OF: R-30189-54097 For each limit category SQLITE_LIMIT_NAME
109001  ** there is a hard upper bound set at compile-time by a C preprocessor
109002  ** macro called SQLITE_MAX_NAME. (The "_LIMIT_" in the name is changed to
109003  ** "_MAX_".)
109004  */
109005  assert( aHardLimit[SQLITE_LIMIT_LENGTH]==SQLITE_MAX_LENGTH );
109006  assert( aHardLimit[SQLITE_LIMIT_SQL_LENGTH]==SQLITE_MAX_SQL_LENGTH );
109007  assert( aHardLimit[SQLITE_LIMIT_COLUMN]==SQLITE_MAX_COLUMN );
109008  assert( aHardLimit[SQLITE_LIMIT_EXPR_DEPTH]==SQLITE_MAX_EXPR_DEPTH );
109009  assert( aHardLimit[SQLITE_LIMIT_COMPOUND_SELECT]==SQLITE_MAX_COMPOUND_SELECT);
109010  assert( aHardLimit[SQLITE_LIMIT_VDBE_OP]==SQLITE_MAX_VDBE_OP );
109011  assert( aHardLimit[SQLITE_LIMIT_FUNCTION_ARG]==SQLITE_MAX_FUNCTION_ARG );
109012  assert( aHardLimit[SQLITE_LIMIT_ATTACHED]==SQLITE_MAX_ATTACHED );
109013  assert( aHardLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]==
109014                                               SQLITE_MAX_LIKE_PATTERN_LENGTH );
109015  assert( aHardLimit[SQLITE_LIMIT_VARIABLE_NUMBER]==SQLITE_MAX_VARIABLE_NUMBER);
109016  assert( aHardLimit[SQLITE_LIMIT_TRIGGER_DEPTH]==SQLITE_MAX_TRIGGER_DEPTH );
109017  assert( SQLITE_LIMIT_TRIGGER_DEPTH==(SQLITE_N_LIMIT-1) );
109018
109019
109020  if( limitId<0 || limitId>=SQLITE_N_LIMIT ){
109021    return -1;
109022  }
109023  oldLimit = db->aLimit[limitId];
109024  if( newLimit>=0 ){                   /* IMP: R-52476-28732 */
109025    if( newLimit>aHardLimit[limitId] ){
109026      newLimit = aHardLimit[limitId];  /* IMP: R-51463-25634 */
109027    }
109028    db->aLimit[limitId] = newLimit;
109029  }
109030  return oldLimit;                     /* IMP: R-53341-35419 */
109031}
109032
109033/*
109034** This routine does the work of opening a database on behalf of
109035** sqlite3_open() and sqlite3_open16(). The database filename "zFilename"
109036** is UTF-8 encoded.
109037*/
109038static int openDatabase(
109039  const char *zFilename, /* Database filename UTF-8 encoded */
109040  sqlite3 **ppDb,        /* OUT: Returned database handle */
109041  unsigned flags,        /* Operational flags */
109042  const char *zVfs       /* Name of the VFS to use */
109043){
109044  sqlite3 *db;
109045  int rc;
109046  int isThreadsafe;
109047
109048  *ppDb = 0;
109049#ifndef SQLITE_OMIT_AUTOINIT
109050  rc = sqlite3_initialize();
109051  if( rc ) return rc;
109052#endif
109053
109054  /* Only allow sensible combinations of bits in the flags argument.
109055  ** Throw an error if any non-sense combination is used.  If we
109056  ** do not block illegal combinations here, it could trigger
109057  ** assert() statements in deeper layers.  Sensible combinations
109058  ** are:
109059  **
109060  **  1:  SQLITE_OPEN_READONLY
109061  **  2:  SQLITE_OPEN_READWRITE
109062  **  6:  SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE
109063  */
109064  assert( SQLITE_OPEN_READONLY  == 0x01 );
109065  assert( SQLITE_OPEN_READWRITE == 0x02 );
109066  assert( SQLITE_OPEN_CREATE    == 0x04 );
109067  testcase( (1<<(flags&7))==0x02 ); /* READONLY */
109068  testcase( (1<<(flags&7))==0x04 ); /* READWRITE */
109069  testcase( (1<<(flags&7))==0x40 ); /* READWRITE | CREATE */
109070  if( ((1<<(flags&7)) & 0x46)==0 ) return SQLITE_MISUSE;
109071
109072  if( sqlite3GlobalConfig.bCoreMutex==0 ){
109073    isThreadsafe = 0;
109074  }else if( flags & SQLITE_OPEN_NOMUTEX ){
109075    isThreadsafe = 0;
109076  }else if( flags & SQLITE_OPEN_FULLMUTEX ){
109077    isThreadsafe = 1;
109078  }else{
109079    isThreadsafe = sqlite3GlobalConfig.bFullMutex;
109080  }
109081  if( flags & SQLITE_OPEN_PRIVATECACHE ){
109082    flags &= ~SQLITE_OPEN_SHAREDCACHE;
109083  }else if( sqlite3GlobalConfig.sharedCacheEnabled ){
109084    flags |= SQLITE_OPEN_SHAREDCACHE;
109085  }
109086
109087  /* Remove harmful bits from the flags parameter
109088  **
109089  ** The SQLITE_OPEN_NOMUTEX and SQLITE_OPEN_FULLMUTEX flags were
109090  ** dealt with in the previous code block.  Besides these, the only
109091  ** valid input flags for sqlite3_open_v2() are SQLITE_OPEN_READONLY,
109092  ** SQLITE_OPEN_READWRITE, SQLITE_OPEN_CREATE, SQLITE_OPEN_SHAREDCACHE,
109093  ** SQLITE_OPEN_PRIVATECACHE, and some reserved bits.  Silently mask
109094  ** off all other flags.
109095  */
109096  flags &=  ~( SQLITE_OPEN_DELETEONCLOSE |
109097               SQLITE_OPEN_EXCLUSIVE |
109098               SQLITE_OPEN_MAIN_DB |
109099               SQLITE_OPEN_TEMP_DB |
109100               SQLITE_OPEN_TRANSIENT_DB |
109101               SQLITE_OPEN_MAIN_JOURNAL |
109102               SQLITE_OPEN_TEMP_JOURNAL |
109103               SQLITE_OPEN_SUBJOURNAL |
109104               SQLITE_OPEN_MASTER_JOURNAL |
109105               SQLITE_OPEN_NOMUTEX |
109106               SQLITE_OPEN_FULLMUTEX |
109107               SQLITE_OPEN_WAL
109108             );
109109
109110  /* Allocate the sqlite data structure */
109111  db = sqlite3MallocZero( sizeof(sqlite3) );
109112  if( db==0 ) goto opendb_out;
109113  if( isThreadsafe ){
109114    db->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);
109115    if( db->mutex==0 ){
109116      sqlite3_free(db);
109117      db = 0;
109118      goto opendb_out;
109119    }
109120  }
109121  sqlite3_mutex_enter(db->mutex);
109122  db->errMask = 0xff;
109123  db->nDb = 2;
109124  db->magic = SQLITE_MAGIC_BUSY;
109125  db->aDb = db->aDbStatic;
109126
109127  assert( sizeof(db->aLimit)==sizeof(aHardLimit) );
109128  memcpy(db->aLimit, aHardLimit, sizeof(db->aLimit));
109129  db->autoCommit = 1;
109130  db->nextAutovac = -1;
109131  db->nextPagesize = 0;
109132  db->flags |= SQLITE_ShortColNames | SQLITE_AutoIndex | SQLITE_EnableTrigger
109133#if SQLITE_DEFAULT_FILE_FORMAT<4
109134                 | SQLITE_LegacyFileFmt
109135#endif
109136#ifdef SQLITE_ENABLE_LOAD_EXTENSION
109137                 | SQLITE_LoadExtension
109138#endif
109139#if SQLITE_DEFAULT_RECURSIVE_TRIGGERS
109140                 | SQLITE_RecTriggers
109141#endif
109142#if defined(SQLITE_DEFAULT_FOREIGN_KEYS) && SQLITE_DEFAULT_FOREIGN_KEYS
109143                 | SQLITE_ForeignKeys
109144#endif
109145      ;
109146  sqlite3HashInit(&db->aCollSeq);
109147#ifndef SQLITE_OMIT_VIRTUALTABLE
109148  sqlite3HashInit(&db->aModule);
109149#endif
109150
109151  db->pVfs = sqlite3_vfs_find(zVfs);
109152  if( !db->pVfs ){
109153    rc = SQLITE_ERROR;
109154    sqlite3Error(db, rc, "no such vfs: %s", zVfs);
109155    goto opendb_out;
109156  }
109157
109158  /* Add the default collation sequence BINARY. BINARY works for both UTF-8
109159  ** and UTF-16, so add a version for each to avoid any unnecessary
109160  ** conversions. The only error that can occur here is a malloc() failure.
109161  */
109162  createCollation(db, "BINARY", SQLITE_UTF8, SQLITE_COLL_BINARY, 0,
109163                  binCollFunc, 0);
109164  createCollation(db, "BINARY", SQLITE_UTF16BE, SQLITE_COLL_BINARY, 0,
109165                  binCollFunc, 0);
109166  createCollation(db, "BINARY", SQLITE_UTF16LE, SQLITE_COLL_BINARY, 0,
109167                  binCollFunc, 0);
109168  createCollation(db, "RTRIM", SQLITE_UTF8, SQLITE_COLL_USER, (void*)1,
109169                  binCollFunc, 0);
109170  if( db->mallocFailed ){
109171    goto opendb_out;
109172  }
109173  db->pDfltColl = sqlite3FindCollSeq(db, SQLITE_UTF8, "BINARY", 0);
109174  assert( db->pDfltColl!=0 );
109175
109176  /* Also add a UTF-8 case-insensitive collation sequence. */
109177  createCollation(db, "NOCASE", SQLITE_UTF8, SQLITE_COLL_NOCASE, 0,
109178                  nocaseCollatingFunc, 0);
109179
109180  /* Open the backend database driver */
109181  db->openFlags = flags;
109182  rc = sqlite3BtreeOpen(zFilename, db, &db->aDb[0].pBt, 0,
109183                        flags | SQLITE_OPEN_MAIN_DB);
109184  if( rc!=SQLITE_OK ){
109185    if( rc==SQLITE_IOERR_NOMEM ){
109186      rc = SQLITE_NOMEM;
109187    }
109188    sqlite3Error(db, rc, 0);
109189    goto opendb_out;
109190  }
109191  db->aDb[0].pSchema = sqlite3SchemaGet(db, db->aDb[0].pBt);
109192  db->aDb[1].pSchema = sqlite3SchemaGet(db, 0);
109193
109194
109195  /* The default safety_level for the main database is 'full'; for the temp
109196  ** database it is 'NONE'. This matches the pager layer defaults.
109197  */
109198  db->aDb[0].zName = "main";
109199  db->aDb[0].safety_level = 3;
109200  db->aDb[1].zName = "temp";
109201  db->aDb[1].safety_level = 1;
109202
109203  db->magic = SQLITE_MAGIC_OPEN;
109204  if( db->mallocFailed ){
109205    goto opendb_out;
109206  }
109207
109208  /* Register all built-in functions, but do not attempt to read the
109209  ** database schema yet. This is delayed until the first time the database
109210  ** is accessed.
109211  */
109212  sqlite3Error(db, SQLITE_OK, 0);
109213  sqlite3RegisterBuiltinFunctions(db);
109214
109215  /* Load automatic extensions - extensions that have been registered
109216  ** using the sqlite3_automatic_extension() API.
109217  */
109218  sqlite3AutoLoadExtensions(db);
109219  rc = sqlite3_errcode(db);
109220  if( rc!=SQLITE_OK ){
109221    goto opendb_out;
109222  }
109223
109224#ifdef SQLITE_ENABLE_FTS1
109225  if( !db->mallocFailed ){
109226    extern int sqlite3Fts1Init(sqlite3*);
109227    rc = sqlite3Fts1Init(db);
109228  }
109229#endif
109230
109231#ifdef SQLITE_ENABLE_FTS2
109232  if( !db->mallocFailed && rc==SQLITE_OK ){
109233    extern int sqlite3Fts2Init(sqlite3*);
109234    rc = sqlite3Fts2Init(db);
109235  }
109236#endif
109237
109238#ifdef SQLITE_ENABLE_FTS3
109239  if( !db->mallocFailed && rc==SQLITE_OK ){
109240    rc = sqlite3Fts3Init(db);
109241  }
109242#endif
109243
109244#ifdef SQLITE_ENABLE_ICU
109245  if( !db->mallocFailed && rc==SQLITE_OK ){
109246    rc = sqlite3IcuInit(db);
109247  }
109248#endif
109249
109250#ifdef SQLITE_ENABLE_RTREE
109251  if( !db->mallocFailed && rc==SQLITE_OK){
109252    rc = sqlite3RtreeInit(db);
109253  }
109254#endif
109255
109256  sqlite3Error(db, rc, 0);
109257
109258  /* -DSQLITE_DEFAULT_LOCKING_MODE=1 makes EXCLUSIVE the default locking
109259  ** mode.  -DSQLITE_DEFAULT_LOCKING_MODE=0 make NORMAL the default locking
109260  ** mode.  Doing nothing at all also makes NORMAL the default.
109261  */
109262#ifdef SQLITE_DEFAULT_LOCKING_MODE
109263  db->dfltLockMode = SQLITE_DEFAULT_LOCKING_MODE;
109264  sqlite3PagerLockingMode(sqlite3BtreePager(db->aDb[0].pBt),
109265                          SQLITE_DEFAULT_LOCKING_MODE);
109266#endif
109267
109268  /* Enable the lookaside-malloc subsystem */
109269  setupLookaside(db, 0, sqlite3GlobalConfig.szLookaside,
109270                        sqlite3GlobalConfig.nLookaside);
109271
109272  sqlite3_wal_autocheckpoint(db, SQLITE_DEFAULT_WAL_AUTOCHECKPOINT);
109273
109274opendb_out:
109275  if( db ){
109276    assert( db->mutex!=0 || isThreadsafe==0 || sqlite3GlobalConfig.bFullMutex==0 );
109277    sqlite3_mutex_leave(db->mutex);
109278  }
109279  rc = sqlite3_errcode(db);
109280  if( rc==SQLITE_NOMEM ){
109281    sqlite3_close(db);
109282    db = 0;
109283  }else if( rc!=SQLITE_OK ){
109284    db->magic = SQLITE_MAGIC_SICK;
109285  }
109286  *ppDb = db;
109287  return sqlite3ApiExit(0, rc);
109288}
109289
109290/*
109291** Open a new database handle.
109292*/
109293SQLITE_API int sqlite3_open(
109294  const char *zFilename,
109295  sqlite3 **ppDb
109296){
109297  return openDatabase(zFilename, ppDb,
109298                      SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
109299}
109300SQLITE_API int sqlite3_open_v2(
109301  const char *filename,   /* Database filename (UTF-8) */
109302  sqlite3 **ppDb,         /* OUT: SQLite db handle */
109303  int flags,              /* Flags */
109304  const char *zVfs        /* Name of VFS module to use */
109305){
109306  return openDatabase(filename, ppDb, flags, zVfs);
109307}
109308
109309#ifndef SQLITE_OMIT_UTF16
109310/*
109311** Open a new database handle.
109312*/
109313SQLITE_API int sqlite3_open16(
109314  const void *zFilename,
109315  sqlite3 **ppDb
109316){
109317  char const *zFilename8;   /* zFilename encoded in UTF-8 instead of UTF-16 */
109318  sqlite3_value *pVal;
109319  int rc;
109320
109321  assert( zFilename );
109322  assert( ppDb );
109323  *ppDb = 0;
109324#ifndef SQLITE_OMIT_AUTOINIT
109325  rc = sqlite3_initialize();
109326  if( rc ) return rc;
109327#endif
109328  pVal = sqlite3ValueNew(0);
109329  sqlite3ValueSetStr(pVal, -1, zFilename, SQLITE_UTF16NATIVE, SQLITE_STATIC);
109330  zFilename8 = sqlite3ValueText(pVal, SQLITE_UTF8);
109331  if( zFilename8 ){
109332    rc = openDatabase(zFilename8, ppDb,
109333                      SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
109334    assert( *ppDb || rc==SQLITE_NOMEM );
109335    if( rc==SQLITE_OK && !DbHasProperty(*ppDb, 0, DB_SchemaLoaded) ){
109336      ENC(*ppDb) = SQLITE_UTF16NATIVE;
109337    }
109338  }else{
109339    rc = SQLITE_NOMEM;
109340  }
109341  sqlite3ValueFree(pVal);
109342
109343  return sqlite3ApiExit(0, rc);
109344}
109345#endif /* SQLITE_OMIT_UTF16 */
109346
109347/*
109348** Register a new collation sequence with the database handle db.
109349*/
109350SQLITE_API int sqlite3_create_collation(
109351  sqlite3* db,
109352  const char *zName,
109353  int enc,
109354  void* pCtx,
109355  int(*xCompare)(void*,int,const void*,int,const void*)
109356){
109357  int rc;
109358  sqlite3_mutex_enter(db->mutex);
109359  assert( !db->mallocFailed );
109360  rc = createCollation(db, zName, (u8)enc, SQLITE_COLL_USER, pCtx, xCompare, 0);
109361  rc = sqlite3ApiExit(db, rc);
109362  sqlite3_mutex_leave(db->mutex);
109363  return rc;
109364}
109365
109366/*
109367** Register a new collation sequence with the database handle db.
109368*/
109369SQLITE_API int sqlite3_create_collation_v2(
109370  sqlite3* db,
109371  const char *zName,
109372  int enc,
109373  void* pCtx,
109374  int(*xCompare)(void*,int,const void*,int,const void*),
109375  void(*xDel)(void*)
109376){
109377  int rc;
109378  sqlite3_mutex_enter(db->mutex);
109379  assert( !db->mallocFailed );
109380  rc = createCollation(db, zName, (u8)enc, SQLITE_COLL_USER, pCtx, xCompare, xDel);
109381  rc = sqlite3ApiExit(db, rc);
109382  sqlite3_mutex_leave(db->mutex);
109383  return rc;
109384}
109385
109386#ifndef SQLITE_OMIT_UTF16
109387/*
109388** Register a new collation sequence with the database handle db.
109389*/
109390SQLITE_API int sqlite3_create_collation16(
109391  sqlite3* db,
109392  const void *zName,
109393  int enc,
109394  void* pCtx,
109395  int(*xCompare)(void*,int,const void*,int,const void*)
109396){
109397  int rc = SQLITE_OK;
109398  char *zName8;
109399  sqlite3_mutex_enter(db->mutex);
109400  assert( !db->mallocFailed );
109401  zName8 = sqlite3Utf16to8(db, zName, -1, SQLITE_UTF16NATIVE);
109402  if( zName8 ){
109403    rc = createCollation(db, zName8, (u8)enc, SQLITE_COLL_USER, pCtx, xCompare, 0);
109404    sqlite3DbFree(db, zName8);
109405  }
109406  rc = sqlite3ApiExit(db, rc);
109407  sqlite3_mutex_leave(db->mutex);
109408  return rc;
109409}
109410#endif /* SQLITE_OMIT_UTF16 */
109411
109412/*
109413** Register a collation sequence factory callback with the database handle
109414** db. Replace any previously installed collation sequence factory.
109415*/
109416SQLITE_API int sqlite3_collation_needed(
109417  sqlite3 *db,
109418  void *pCollNeededArg,
109419  void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*)
109420){
109421  sqlite3_mutex_enter(db->mutex);
109422  db->xCollNeeded = xCollNeeded;
109423  db->xCollNeeded16 = 0;
109424  db->pCollNeededArg = pCollNeededArg;
109425  sqlite3_mutex_leave(db->mutex);
109426  return SQLITE_OK;
109427}
109428
109429#ifndef SQLITE_OMIT_UTF16
109430/*
109431** Register a collation sequence factory callback with the database handle
109432** db. Replace any previously installed collation sequence factory.
109433*/
109434SQLITE_API int sqlite3_collation_needed16(
109435  sqlite3 *db,
109436  void *pCollNeededArg,
109437  void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*)
109438){
109439  sqlite3_mutex_enter(db->mutex);
109440  db->xCollNeeded = 0;
109441  db->xCollNeeded16 = xCollNeeded16;
109442  db->pCollNeededArg = pCollNeededArg;
109443  sqlite3_mutex_leave(db->mutex);
109444  return SQLITE_OK;
109445}
109446#endif /* SQLITE_OMIT_UTF16 */
109447
109448#ifndef SQLITE_OMIT_DEPRECATED
109449/*
109450** This function is now an anachronism. It used to be used to recover from a
109451** malloc() failure, but SQLite now does this automatically.
109452*/
109453SQLITE_API int sqlite3_global_recover(void){
109454  return SQLITE_OK;
109455}
109456#endif
109457
109458/*
109459** Test to see whether or not the database connection is in autocommit
109460** mode.  Return TRUE if it is and FALSE if not.  Autocommit mode is on
109461** by default.  Autocommit is disabled by a BEGIN statement and reenabled
109462** by the next COMMIT or ROLLBACK.
109463**
109464******* THIS IS AN EXPERIMENTAL API AND IS SUBJECT TO CHANGE ******
109465*/
109466SQLITE_API int sqlite3_get_autocommit(sqlite3 *db){
109467  return db->autoCommit;
109468}
109469
109470/*
109471** The following routines are subtitutes for constants SQLITE_CORRUPT,
109472** SQLITE_MISUSE, SQLITE_CANTOPEN, SQLITE_IOERR and possibly other error
109473** constants.  They server two purposes:
109474**
109475**   1.  Serve as a convenient place to set a breakpoint in a debugger
109476**       to detect when version error conditions occurs.
109477**
109478**   2.  Invoke sqlite3_log() to provide the source code location where
109479**       a low-level error is first detected.
109480*/
109481SQLITE_PRIVATE int sqlite3CorruptError(int lineno){
109482  testcase( sqlite3GlobalConfig.xLog!=0 );
109483  sqlite3_log(SQLITE_CORRUPT,
109484              "database corruption at line %d of [%.10s]",
109485              lineno, 20+sqlite3_sourceid());
109486  return SQLITE_CORRUPT;
109487}
109488SQLITE_PRIVATE int sqlite3MisuseError(int lineno){
109489  testcase( sqlite3GlobalConfig.xLog!=0 );
109490  sqlite3_log(SQLITE_MISUSE,
109491              "misuse at line %d of [%.10s]",
109492              lineno, 20+sqlite3_sourceid());
109493  return SQLITE_MISUSE;
109494}
109495SQLITE_PRIVATE int sqlite3CantopenError(int lineno){
109496  testcase( sqlite3GlobalConfig.xLog!=0 );
109497  sqlite3_log(SQLITE_CANTOPEN,
109498              "cannot open file at line %d of [%.10s]",
109499              lineno, 20+sqlite3_sourceid());
109500  return SQLITE_CANTOPEN;
109501}
109502
109503
109504#ifndef SQLITE_OMIT_DEPRECATED
109505/*
109506** This is a convenience routine that makes sure that all thread-specific
109507** data for this thread has been deallocated.
109508**
109509** SQLite no longer uses thread-specific data so this routine is now a
109510** no-op.  It is retained for historical compatibility.
109511*/
109512SQLITE_API void sqlite3_thread_cleanup(void){
109513}
109514#endif
109515
109516/*
109517** Return meta information about a specific column of a database table.
109518** See comment in sqlite3.h (sqlite.h.in) for details.
109519*/
109520#ifdef SQLITE_ENABLE_COLUMN_METADATA
109521SQLITE_API int sqlite3_table_column_metadata(
109522  sqlite3 *db,                /* Connection handle */
109523  const char *zDbName,        /* Database name or NULL */
109524  const char *zTableName,     /* Table name */
109525  const char *zColumnName,    /* Column name */
109526  char const **pzDataType,    /* OUTPUT: Declared data type */
109527  char const **pzCollSeq,     /* OUTPUT: Collation sequence name */
109528  int *pNotNull,              /* OUTPUT: True if NOT NULL constraint exists */
109529  int *pPrimaryKey,           /* OUTPUT: True if column part of PK */
109530  int *pAutoinc               /* OUTPUT: True if column is auto-increment */
109531){
109532  int rc;
109533  char *zErrMsg = 0;
109534  Table *pTab = 0;
109535  Column *pCol = 0;
109536  int iCol;
109537
109538  char const *zDataType = 0;
109539  char const *zCollSeq = 0;
109540  int notnull = 0;
109541  int primarykey = 0;
109542  int autoinc = 0;
109543
109544  /* Ensure the database schema has been loaded */
109545  sqlite3_mutex_enter(db->mutex);
109546  sqlite3BtreeEnterAll(db);
109547  rc = sqlite3Init(db, &zErrMsg);
109548  if( SQLITE_OK!=rc ){
109549    goto error_out;
109550  }
109551
109552  /* Locate the table in question */
109553  pTab = sqlite3FindTable(db, zTableName, zDbName);
109554  if( !pTab || pTab->pSelect ){
109555    pTab = 0;
109556    goto error_out;
109557  }
109558
109559  /* Find the column for which info is requested */
109560  if( sqlite3IsRowid(zColumnName) ){
109561    iCol = pTab->iPKey;
109562    if( iCol>=0 ){
109563      pCol = &pTab->aCol[iCol];
109564    }
109565  }else{
109566    for(iCol=0; iCol<pTab->nCol; iCol++){
109567      pCol = &pTab->aCol[iCol];
109568      if( 0==sqlite3StrICmp(pCol->zName, zColumnName) ){
109569        break;
109570      }
109571    }
109572    if( iCol==pTab->nCol ){
109573      pTab = 0;
109574      goto error_out;
109575    }
109576  }
109577
109578  /* The following block stores the meta information that will be returned
109579  ** to the caller in local variables zDataType, zCollSeq, notnull, primarykey
109580  ** and autoinc. At this point there are two possibilities:
109581  **
109582  **     1. The specified column name was rowid", "oid" or "_rowid_"
109583  **        and there is no explicitly declared IPK column.
109584  **
109585  **     2. The table is not a view and the column name identified an
109586  **        explicitly declared column. Copy meta information from *pCol.
109587  */
109588  if( pCol ){
109589    zDataType = pCol->zType;
109590    zCollSeq = pCol->zColl;
109591    notnull = pCol->notNull!=0;
109592    primarykey  = pCol->isPrimKey!=0;
109593    autoinc = pTab->iPKey==iCol && (pTab->tabFlags & TF_Autoincrement)!=0;
109594  }else{
109595    zDataType = "INTEGER";
109596    primarykey = 1;
109597  }
109598  if( !zCollSeq ){
109599    zCollSeq = "BINARY";
109600  }
109601
109602error_out:
109603  sqlite3BtreeLeaveAll(db);
109604
109605  /* Whether the function call succeeded or failed, set the output parameters
109606  ** to whatever their local counterparts contain. If an error did occur,
109607  ** this has the effect of zeroing all output parameters.
109608  */
109609  if( pzDataType ) *pzDataType = zDataType;
109610  if( pzCollSeq ) *pzCollSeq = zCollSeq;
109611  if( pNotNull ) *pNotNull = notnull;
109612  if( pPrimaryKey ) *pPrimaryKey = primarykey;
109613  if( pAutoinc ) *pAutoinc = autoinc;
109614
109615  if( SQLITE_OK==rc && !pTab ){
109616    sqlite3DbFree(db, zErrMsg);
109617    zErrMsg = sqlite3MPrintf(db, "no such table column: %s.%s", zTableName,
109618        zColumnName);
109619    rc = SQLITE_ERROR;
109620  }
109621  sqlite3Error(db, rc, (zErrMsg?"%s":0), zErrMsg);
109622  sqlite3DbFree(db, zErrMsg);
109623  rc = sqlite3ApiExit(db, rc);
109624  sqlite3_mutex_leave(db->mutex);
109625  return rc;
109626}
109627#endif
109628
109629/*
109630** Sleep for a little while.  Return the amount of time slept.
109631*/
109632SQLITE_API int sqlite3_sleep(int ms){
109633  sqlite3_vfs *pVfs;
109634  int rc;
109635  pVfs = sqlite3_vfs_find(0);
109636  if( pVfs==0 ) return 0;
109637
109638  /* This function works in milliseconds, but the underlying OsSleep()
109639  ** API uses microseconds. Hence the 1000's.
109640  */
109641  rc = (sqlite3OsSleep(pVfs, 1000*ms)/1000);
109642  return rc;
109643}
109644
109645/*
109646** Enable or disable the extended result codes.
109647*/
109648SQLITE_API int sqlite3_extended_result_codes(sqlite3 *db, int onoff){
109649  sqlite3_mutex_enter(db->mutex);
109650  db->errMask = onoff ? 0xffffffff : 0xff;
109651  sqlite3_mutex_leave(db->mutex);
109652  return SQLITE_OK;
109653}
109654
109655/*
109656** Invoke the xFileControl method on a particular database.
109657*/
109658SQLITE_API int sqlite3_file_control(sqlite3 *db, const char *zDbName, int op, void *pArg){
109659  int rc = SQLITE_ERROR;
109660  int iDb;
109661  sqlite3_mutex_enter(db->mutex);
109662  if( zDbName==0 ){
109663    iDb = 0;
109664  }else{
109665    for(iDb=0; iDb<db->nDb; iDb++){
109666      if( strcmp(db->aDb[iDb].zName, zDbName)==0 ) break;
109667    }
109668  }
109669  if( iDb<db->nDb ){
109670    Btree *pBtree = db->aDb[iDb].pBt;
109671    if( pBtree ){
109672      Pager *pPager;
109673      sqlite3_file *fd;
109674      sqlite3BtreeEnter(pBtree);
109675      pPager = sqlite3BtreePager(pBtree);
109676      assert( pPager!=0 );
109677      fd = sqlite3PagerFile(pPager);
109678      assert( fd!=0 );
109679      if( op==SQLITE_FCNTL_FILE_POINTER ){
109680        *(sqlite3_file**)pArg = fd;
109681        rc = SQLITE_OK;
109682      }else if( fd->pMethods ){
109683        rc = sqlite3OsFileControl(fd, op, pArg);
109684      }else{
109685        rc = SQLITE_NOTFOUND;
109686      }
109687      sqlite3BtreeLeave(pBtree);
109688    }
109689  }
109690  sqlite3_mutex_leave(db->mutex);
109691  return rc;
109692}
109693
109694/*
109695** Interface to the testing logic.
109696*/
109697SQLITE_API int sqlite3_test_control(int op, ...){
109698  int rc = 0;
109699#ifndef SQLITE_OMIT_BUILTIN_TEST
109700  va_list ap;
109701  va_start(ap, op);
109702  switch( op ){
109703
109704    /*
109705    ** Save the current state of the PRNG.
109706    */
109707    case SQLITE_TESTCTRL_PRNG_SAVE: {
109708      sqlite3PrngSaveState();
109709      break;
109710    }
109711
109712    /*
109713    ** Restore the state of the PRNG to the last state saved using
109714    ** PRNG_SAVE.  If PRNG_SAVE has never before been called, then
109715    ** this verb acts like PRNG_RESET.
109716    */
109717    case SQLITE_TESTCTRL_PRNG_RESTORE: {
109718      sqlite3PrngRestoreState();
109719      break;
109720    }
109721
109722    /*
109723    ** Reset the PRNG back to its uninitialized state.  The next call
109724    ** to sqlite3_randomness() will reseed the PRNG using a single call
109725    ** to the xRandomness method of the default VFS.
109726    */
109727    case SQLITE_TESTCTRL_PRNG_RESET: {
109728      sqlite3PrngResetState();
109729      break;
109730    }
109731
109732    /*
109733    **  sqlite3_test_control(BITVEC_TEST, size, program)
109734    **
109735    ** Run a test against a Bitvec object of size.  The program argument
109736    ** is an array of integers that defines the test.  Return -1 on a
109737    ** memory allocation error, 0 on success, or non-zero for an error.
109738    ** See the sqlite3BitvecBuiltinTest() for additional information.
109739    */
109740    case SQLITE_TESTCTRL_BITVEC_TEST: {
109741      int sz = va_arg(ap, int);
109742      int *aProg = va_arg(ap, int*);
109743      rc = sqlite3BitvecBuiltinTest(sz, aProg);
109744      break;
109745    }
109746
109747    /*
109748    **  sqlite3_test_control(BENIGN_MALLOC_HOOKS, xBegin, xEnd)
109749    **
109750    ** Register hooks to call to indicate which malloc() failures
109751    ** are benign.
109752    */
109753    case SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS: {
109754      typedef void (*void_function)(void);
109755      void_function xBenignBegin;
109756      void_function xBenignEnd;
109757      xBenignBegin = va_arg(ap, void_function);
109758      xBenignEnd = va_arg(ap, void_function);
109759      sqlite3BenignMallocHooks(xBenignBegin, xBenignEnd);
109760      break;
109761    }
109762
109763    /*
109764    **  sqlite3_test_control(SQLITE_TESTCTRL_PENDING_BYTE, unsigned int X)
109765    **
109766    ** Set the PENDING byte to the value in the argument, if X>0.
109767    ** Make no changes if X==0.  Return the value of the pending byte
109768    ** as it existing before this routine was called.
109769    **
109770    ** IMPORTANT:  Changing the PENDING byte from 0x40000000 results in
109771    ** an incompatible database file format.  Changing the PENDING byte
109772    ** while any database connection is open results in undefined and
109773    ** dileterious behavior.
109774    */
109775    case SQLITE_TESTCTRL_PENDING_BYTE: {
109776      rc = PENDING_BYTE;
109777#ifndef SQLITE_OMIT_WSD
109778      {
109779        unsigned int newVal = va_arg(ap, unsigned int);
109780        if( newVal ) sqlite3PendingByte = newVal;
109781      }
109782#endif
109783      break;
109784    }
109785
109786    /*
109787    **  sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, int X)
109788    **
109789    ** This action provides a run-time test to see whether or not
109790    ** assert() was enabled at compile-time.  If X is true and assert()
109791    ** is enabled, then the return value is true.  If X is true and
109792    ** assert() is disabled, then the return value is zero.  If X is
109793    ** false and assert() is enabled, then the assertion fires and the
109794    ** process aborts.  If X is false and assert() is disabled, then the
109795    ** return value is zero.
109796    */
109797    case SQLITE_TESTCTRL_ASSERT: {
109798      volatile int x = 0;
109799      assert( (x = va_arg(ap,int))!=0 );
109800      rc = x;
109801      break;
109802    }
109803
109804
109805    /*
109806    **  sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, int X)
109807    **
109808    ** This action provides a run-time test to see how the ALWAYS and
109809    ** NEVER macros were defined at compile-time.
109810    **
109811    ** The return value is ALWAYS(X).
109812    **
109813    ** The recommended test is X==2.  If the return value is 2, that means
109814    ** ALWAYS() and NEVER() are both no-op pass-through macros, which is the
109815    ** default setting.  If the return value is 1, then ALWAYS() is either
109816    ** hard-coded to true or else it asserts if its argument is false.
109817    ** The first behavior (hard-coded to true) is the case if
109818    ** SQLITE_TESTCTRL_ASSERT shows that assert() is disabled and the second
109819    ** behavior (assert if the argument to ALWAYS() is false) is the case if
109820    ** SQLITE_TESTCTRL_ASSERT shows that assert() is enabled.
109821    **
109822    ** The run-time test procedure might look something like this:
109823    **
109824    **    if( sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, 2)==2 ){
109825    **      // ALWAYS() and NEVER() are no-op pass-through macros
109826    **    }else if( sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, 1) ){
109827    **      // ALWAYS(x) asserts that x is true. NEVER(x) asserts x is false.
109828    **    }else{
109829    **      // ALWAYS(x) is a constant 1.  NEVER(x) is a constant 0.
109830    **    }
109831    */
109832    case SQLITE_TESTCTRL_ALWAYS: {
109833      int x = va_arg(ap,int);
109834      rc = ALWAYS(x);
109835      break;
109836    }
109837
109838    /*   sqlite3_test_control(SQLITE_TESTCTRL_RESERVE, sqlite3 *db, int N)
109839    **
109840    ** Set the nReserve size to N for the main database on the database
109841    ** connection db.
109842    */
109843    case SQLITE_TESTCTRL_RESERVE: {
109844      sqlite3 *db = va_arg(ap, sqlite3*);
109845      int x = va_arg(ap,int);
109846      sqlite3_mutex_enter(db->mutex);
109847      sqlite3BtreeSetPageSize(db->aDb[0].pBt, 0, x, 0);
109848      sqlite3_mutex_leave(db->mutex);
109849      break;
109850    }
109851
109852    /*  sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS, sqlite3 *db, int N)
109853    **
109854    ** Enable or disable various optimizations for testing purposes.  The
109855    ** argument N is a bitmask of optimizations to be disabled.  For normal
109856    ** operation N should be 0.  The idea is that a test program (like the
109857    ** SQL Logic Test or SLT test module) can run the same SQL multiple times
109858    ** with various optimizations disabled to verify that the same answer
109859    ** is obtained in every case.
109860    */
109861    case SQLITE_TESTCTRL_OPTIMIZATIONS: {
109862      sqlite3 *db = va_arg(ap, sqlite3*);
109863      int x = va_arg(ap,int);
109864      db->flags = (x & SQLITE_OptMask) | (db->flags & ~SQLITE_OptMask);
109865      break;
109866    }
109867
109868#ifdef SQLITE_N_KEYWORD
109869    /* sqlite3_test_control(SQLITE_TESTCTRL_ISKEYWORD, const char *zWord)
109870    **
109871    ** If zWord is a keyword recognized by the parser, then return the
109872    ** number of keywords.  Or if zWord is not a keyword, return 0.
109873    **
109874    ** This test feature is only available in the amalgamation since
109875    ** the SQLITE_N_KEYWORD macro is not defined in this file if SQLite
109876    ** is built using separate source files.
109877    */
109878    case SQLITE_TESTCTRL_ISKEYWORD: {
109879      const char *zWord = va_arg(ap, const char*);
109880      int n = sqlite3Strlen30(zWord);
109881      rc = (sqlite3KeywordCode((u8*)zWord, n)!=TK_ID) ? SQLITE_N_KEYWORD : 0;
109882      break;
109883    }
109884#endif
109885
109886    /* sqlite3_test_control(SQLITE_TESTCTRL_PGHDRSZ)
109887    **
109888    ** Return the size of a pcache header in bytes.
109889    */
109890    case SQLITE_TESTCTRL_PGHDRSZ: {
109891      rc = sizeof(PgHdr);
109892      break;
109893    }
109894
109895    /* sqlite3_test_control(SQLITE_TESTCTRL_SCRATCHMALLOC, sz, &pNew, pFree);
109896    **
109897    ** Pass pFree into sqlite3ScratchFree().
109898    ** If sz>0 then allocate a scratch buffer into pNew.
109899    */
109900    case SQLITE_TESTCTRL_SCRATCHMALLOC: {
109901      void *pFree, **ppNew;
109902      int sz;
109903      sz = va_arg(ap, int);
109904      ppNew = va_arg(ap, void**);
109905      pFree = va_arg(ap, void*);
109906      if( sz ) *ppNew = sqlite3ScratchMalloc(sz);
109907      sqlite3ScratchFree(pFree);
109908      break;
109909    }
109910
109911  }
109912  va_end(ap);
109913#endif /* SQLITE_OMIT_BUILTIN_TEST */
109914  return rc;
109915}
109916
109917/************** End of main.c ************************************************/
109918/************** Begin file notify.c ******************************************/
109919/*
109920** 2009 March 3
109921**
109922** The author disclaims copyright to this source code.  In place of
109923** a legal notice, here is a blessing:
109924**
109925**    May you do good and not evil.
109926**    May you find forgiveness for yourself and forgive others.
109927**    May you share freely, never taking more than you give.
109928**
109929*************************************************************************
109930**
109931** This file contains the implementation of the sqlite3_unlock_notify()
109932** API method and its associated functionality.
109933*/
109934
109935/* Omit this entire file if SQLITE_ENABLE_UNLOCK_NOTIFY is not defined. */
109936#ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
109937
109938/*
109939** Public interfaces:
109940**
109941**   sqlite3ConnectionBlocked()
109942**   sqlite3ConnectionUnlocked()
109943**   sqlite3ConnectionClosed()
109944**   sqlite3_unlock_notify()
109945*/
109946
109947#define assertMutexHeld() \
109948  assert( sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)) )
109949
109950/*
109951** Head of a linked list of all sqlite3 objects created by this process
109952** for which either sqlite3.pBlockingConnection or sqlite3.pUnlockConnection
109953** is not NULL. This variable may only accessed while the STATIC_MASTER
109954** mutex is held.
109955*/
109956static sqlite3 *SQLITE_WSD sqlite3BlockedList = 0;
109957
109958#ifndef NDEBUG
109959/*
109960** This function is a complex assert() that verifies the following
109961** properties of the blocked connections list:
109962**
109963**   1) Each entry in the list has a non-NULL value for either
109964**      pUnlockConnection or pBlockingConnection, or both.
109965**
109966**   2) All entries in the list that share a common value for
109967**      xUnlockNotify are grouped together.
109968**
109969**   3) If the argument db is not NULL, then none of the entries in the
109970**      blocked connections list have pUnlockConnection or pBlockingConnection
109971**      set to db. This is used when closing connection db.
109972*/
109973static void checkListProperties(sqlite3 *db){
109974  sqlite3 *p;
109975  for(p=sqlite3BlockedList; p; p=p->pNextBlocked){
109976    int seen = 0;
109977    sqlite3 *p2;
109978
109979    /* Verify property (1) */
109980    assert( p->pUnlockConnection || p->pBlockingConnection );
109981
109982    /* Verify property (2) */
109983    for(p2=sqlite3BlockedList; p2!=p; p2=p2->pNextBlocked){
109984      if( p2->xUnlockNotify==p->xUnlockNotify ) seen = 1;
109985      assert( p2->xUnlockNotify==p->xUnlockNotify || !seen );
109986      assert( db==0 || p->pUnlockConnection!=db );
109987      assert( db==0 || p->pBlockingConnection!=db );
109988    }
109989  }
109990}
109991#else
109992# define checkListProperties(x)
109993#endif
109994
109995/*
109996** Remove connection db from the blocked connections list. If connection
109997** db is not currently a part of the list, this function is a no-op.
109998*/
109999static void removeFromBlockedList(sqlite3 *db){
110000  sqlite3 **pp;
110001  assertMutexHeld();
110002  for(pp=&sqlite3BlockedList; *pp; pp = &(*pp)->pNextBlocked){
110003    if( *pp==db ){
110004      *pp = (*pp)->pNextBlocked;
110005      break;
110006    }
110007  }
110008}
110009
110010/*
110011** Add connection db to the blocked connections list. It is assumed
110012** that it is not already a part of the list.
110013*/
110014static void addToBlockedList(sqlite3 *db){
110015  sqlite3 **pp;
110016  assertMutexHeld();
110017  for(
110018    pp=&sqlite3BlockedList;
110019    *pp && (*pp)->xUnlockNotify!=db->xUnlockNotify;
110020    pp=&(*pp)->pNextBlocked
110021  );
110022  db->pNextBlocked = *pp;
110023  *pp = db;
110024}
110025
110026/*
110027** Obtain the STATIC_MASTER mutex.
110028*/
110029static void enterMutex(void){
110030  sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
110031  checkListProperties(0);
110032}
110033
110034/*
110035** Release the STATIC_MASTER mutex.
110036*/
110037static void leaveMutex(void){
110038  assertMutexHeld();
110039  checkListProperties(0);
110040  sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
110041}
110042
110043/*
110044** Register an unlock-notify callback.
110045**
110046** This is called after connection "db" has attempted some operation
110047** but has received an SQLITE_LOCKED error because another connection
110048** (call it pOther) in the same process was busy using the same shared
110049** cache.  pOther is found by looking at db->pBlockingConnection.
110050**
110051** If there is no blocking connection, the callback is invoked immediately,
110052** before this routine returns.
110053**
110054** If pOther is already blocked on db, then report SQLITE_LOCKED, to indicate
110055** a deadlock.
110056**
110057** Otherwise, make arrangements to invoke xNotify when pOther drops
110058** its locks.
110059**
110060** Each call to this routine overrides any prior callbacks registered
110061** on the same "db".  If xNotify==0 then any prior callbacks are immediately
110062** cancelled.
110063*/
110064SQLITE_API int sqlite3_unlock_notify(
110065  sqlite3 *db,
110066  void (*xNotify)(void **, int),
110067  void *pArg
110068){
110069  int rc = SQLITE_OK;
110070
110071  sqlite3_mutex_enter(db->mutex);
110072  enterMutex();
110073
110074  if( xNotify==0 ){
110075    removeFromBlockedList(db);
110076    db->pBlockingConnection = 0;
110077    db->pUnlockConnection = 0;
110078    db->xUnlockNotify = 0;
110079    db->pUnlockArg = 0;
110080  }else if( 0==db->pBlockingConnection ){
110081    /* The blocking transaction has been concluded. Or there never was a
110082    ** blocking transaction. In either case, invoke the notify callback
110083    ** immediately.
110084    */
110085    xNotify(&pArg, 1);
110086  }else{
110087    sqlite3 *p;
110088
110089    for(p=db->pBlockingConnection; p && p!=db; p=p->pUnlockConnection){}
110090    if( p ){
110091      rc = SQLITE_LOCKED;              /* Deadlock detected. */
110092    }else{
110093      db->pUnlockConnection = db->pBlockingConnection;
110094      db->xUnlockNotify = xNotify;
110095      db->pUnlockArg = pArg;
110096      removeFromBlockedList(db);
110097      addToBlockedList(db);
110098    }
110099  }
110100
110101  leaveMutex();
110102  assert( !db->mallocFailed );
110103  sqlite3Error(db, rc, (rc?"database is deadlocked":0));
110104  sqlite3_mutex_leave(db->mutex);
110105  return rc;
110106}
110107
110108/*
110109** This function is called while stepping or preparing a statement
110110** associated with connection db. The operation will return SQLITE_LOCKED
110111** to the user because it requires a lock that will not be available
110112** until connection pBlocker concludes its current transaction.
110113*/
110114SQLITE_PRIVATE void sqlite3ConnectionBlocked(sqlite3 *db, sqlite3 *pBlocker){
110115  enterMutex();
110116  if( db->pBlockingConnection==0 && db->pUnlockConnection==0 ){
110117    addToBlockedList(db);
110118  }
110119  db->pBlockingConnection = pBlocker;
110120  leaveMutex();
110121}
110122
110123/*
110124** This function is called when
110125** the transaction opened by database db has just finished. Locks held
110126** by database connection db have been released.
110127**
110128** This function loops through each entry in the blocked connections
110129** list and does the following:
110130**
110131**   1) If the sqlite3.pBlockingConnection member of a list entry is
110132**      set to db, then set pBlockingConnection=0.
110133**
110134**   2) If the sqlite3.pUnlockConnection member of a list entry is
110135**      set to db, then invoke the configured unlock-notify callback and
110136**      set pUnlockConnection=0.
110137**
110138**   3) If the two steps above mean that pBlockingConnection==0 and
110139**      pUnlockConnection==0, remove the entry from the blocked connections
110140**      list.
110141*/
110142SQLITE_PRIVATE void sqlite3ConnectionUnlocked(sqlite3 *db){
110143  void (*xUnlockNotify)(void **, int) = 0; /* Unlock-notify cb to invoke */
110144  int nArg = 0;                            /* Number of entries in aArg[] */
110145  sqlite3 **pp;                            /* Iterator variable */
110146  void **aArg;               /* Arguments to the unlock callback */
110147  void **aDyn = 0;           /* Dynamically allocated space for aArg[] */
110148  void *aStatic[16];         /* Starter space for aArg[].  No malloc required */
110149
110150  aArg = aStatic;
110151  enterMutex();         /* Enter STATIC_MASTER mutex */
110152
110153  /* This loop runs once for each entry in the blocked-connections list. */
110154  for(pp=&sqlite3BlockedList; *pp; /* no-op */ ){
110155    sqlite3 *p = *pp;
110156
110157    /* Step 1. */
110158    if( p->pBlockingConnection==db ){
110159      p->pBlockingConnection = 0;
110160    }
110161
110162    /* Step 2. */
110163    if( p->pUnlockConnection==db ){
110164      assert( p->xUnlockNotify );
110165      if( p->xUnlockNotify!=xUnlockNotify && nArg!=0 ){
110166        xUnlockNotify(aArg, nArg);
110167        nArg = 0;
110168      }
110169
110170      sqlite3BeginBenignMalloc();
110171      assert( aArg==aDyn || (aDyn==0 && aArg==aStatic) );
110172      assert( nArg<=(int)ArraySize(aStatic) || aArg==aDyn );
110173      if( (!aDyn && nArg==(int)ArraySize(aStatic))
110174       || (aDyn && nArg==(int)(sqlite3MallocSize(aDyn)/sizeof(void*)))
110175      ){
110176        /* The aArg[] array needs to grow. */
110177        void **pNew = (void **)sqlite3Malloc(nArg*sizeof(void *)*2);
110178        if( pNew ){
110179          memcpy(pNew, aArg, nArg*sizeof(void *));
110180          sqlite3_free(aDyn);
110181          aDyn = aArg = pNew;
110182        }else{
110183          /* This occurs when the array of context pointers that need to
110184          ** be passed to the unlock-notify callback is larger than the
110185          ** aStatic[] array allocated on the stack and the attempt to
110186          ** allocate a larger array from the heap has failed.
110187          **
110188          ** This is a difficult situation to handle. Returning an error
110189          ** code to the caller is insufficient, as even if an error code
110190          ** is returned the transaction on connection db will still be
110191          ** closed and the unlock-notify callbacks on blocked connections
110192          ** will go unissued. This might cause the application to wait
110193          ** indefinitely for an unlock-notify callback that will never
110194          ** arrive.
110195          **
110196          ** Instead, invoke the unlock-notify callback with the context
110197          ** array already accumulated. We can then clear the array and
110198          ** begin accumulating any further context pointers without
110199          ** requiring any dynamic allocation. This is sub-optimal because
110200          ** it means that instead of one callback with a large array of
110201          ** context pointers the application will receive two or more
110202          ** callbacks with smaller arrays of context pointers, which will
110203          ** reduce the applications ability to prioritize multiple
110204          ** connections. But it is the best that can be done under the
110205          ** circumstances.
110206          */
110207          xUnlockNotify(aArg, nArg);
110208          nArg = 0;
110209        }
110210      }
110211      sqlite3EndBenignMalloc();
110212
110213      aArg[nArg++] = p->pUnlockArg;
110214      xUnlockNotify = p->xUnlockNotify;
110215      p->pUnlockConnection = 0;
110216      p->xUnlockNotify = 0;
110217      p->pUnlockArg = 0;
110218    }
110219
110220    /* Step 3. */
110221    if( p->pBlockingConnection==0 && p->pUnlockConnection==0 ){
110222      /* Remove connection p from the blocked connections list. */
110223      *pp = p->pNextBlocked;
110224      p->pNextBlocked = 0;
110225    }else{
110226      pp = &p->pNextBlocked;
110227    }
110228  }
110229
110230  if( nArg!=0 ){
110231    xUnlockNotify(aArg, nArg);
110232  }
110233  sqlite3_free(aDyn);
110234  leaveMutex();         /* Leave STATIC_MASTER mutex */
110235}
110236
110237/*
110238** This is called when the database connection passed as an argument is
110239** being closed. The connection is removed from the blocked list.
110240*/
110241SQLITE_PRIVATE void sqlite3ConnectionClosed(sqlite3 *db){
110242  sqlite3ConnectionUnlocked(db);
110243  enterMutex();
110244  removeFromBlockedList(db);
110245  checkListProperties(db);
110246  leaveMutex();
110247}
110248#endif
110249
110250/************** End of notify.c **********************************************/
110251/************** Begin file recover.c *****************************************/
110252/*
110253** 2012 Jan 11
110254**
110255** The author disclaims copyright to this source code.  In place of
110256** a legal notice, here is a blessing:
110257**
110258**    May you do good and not evil.
110259**    May you find forgiveness for yourself and forgive others.
110260**    May you share freely, never taking more than you give.
110261*/
110262/* TODO(shess): THIS MODULE IS STILL EXPERIMENTAL.  DO NOT USE IT. */
110263/* Implements a virtual table "recover" which can be used to recover
110264 * data from a corrupt table.  The table is walked manually, with
110265 * corrupt items skipped.  Additionally, any errors while reading will
110266 * be skipped.
110267 *
110268 * Given a table with this definition:
110269 *
110270 * CREATE TABLE Stuff (
110271 *   name TEXT PRIMARY KEY,
110272 *   value TEXT NOT NULL
110273 * );
110274 *
110275 * to recover the data from teh table, you could do something like:
110276 *
110277 * -- Attach another database, the original is not trustworthy.
110278 * ATTACH DATABASE '/tmp/db.db' AS rdb;
110279 * -- Create a new version of the table.
110280 * CREATE TABLE rdb.Stuff (
110281 *   name TEXT PRIMARY KEY,
110282 *   value TEXT NOT NULL
110283 * );
110284 * -- This will read the original table's data.
110285 * CREATE VIRTUAL TABLE temp.recover_Stuff using recover(
110286 *   main.Stuff,
110287 *   name TEXT STRICT NOT NULL,  -- only real TEXT data allowed
110288 *   value TEXT STRICT NOT NULL
110289 * );
110290 * -- Corruption means the UNIQUE constraint may no longer hold for
110291 * -- Stuff, so either OR REPLACE or OR IGNORE must be used.
110292 * INSERT OR REPLACE INTO rdb.Stuff (rowid, name, value )
110293 *   SELECT rowid, name, value FROM temp.recover_Stuff;
110294 * DROP TABLE temp.recover_Stuff;
110295 * DETACH DATABASE rdb;
110296 * -- Move db.db to replace original db in filesystem.
110297 *
110298 *
110299 * Usage
110300 *
110301 * Given the goal of dealing with corruption, it would not be safe to
110302 * create a recovery table in the database being recovered.  So
110303 * recovery tables must be created in the temp database.  They are not
110304 * appropriate to persist, in any case.  [As a bonus, sqlite_master
110305 * tables can be recovered.  Perhaps more cute than useful, though.]
110306 *
110307 * The parameters are a specifier for the table to read, and a column
110308 * definition for each bit of data stored in that table.  The named
110309 * table must be convertable to a root page number by reading the
110310 * sqlite_master table.  Bare table names are assumed to be in
110311 * database 0 ("main"), other databases can be specified in db.table
110312 * fashion.
110313 *
110314 * Column definitions are similar to BUT NOT THE SAME AS those
110315 * provided to CREATE statements:
110316 *  column-def: column-name [type-name [STRICT] [NOT NULL]]
110317 *  type-name: (ANY|ROWID|INTEGER|FLOAT|NUMERIC|TEXT|BLOB)
110318 *
110319 * Only those exact type names are accepted, there is no type
110320 * intuition.  The only constraints accepted are STRICT (see below)
110321 * and NOT NULL.  Anything unexpected will cause the create to fail.
110322 *
110323 * ANY is a convenience to indicate that manifest typing is desired.
110324 * It is equivalent to not specifying a type at all.  The results for
110325 * such columns will have the type of the data's storage.  The exposed
110326 * schema will contain no type for that column.
110327 *
110328 * ROWID is used for columns representing aliases to the rowid
110329 * (INTEGER PRIMARY KEY, with or without AUTOINCREMENT), to make the
110330 * concept explicit.  Such columns are actually stored as NULL, so
110331 * they cannot be simply ignored.  The exposed schema will be INTEGER
110332 * for that column.
110333 *
110334 * NOT NULL causes rows with a NULL in that column to be skipped.  It
110335 * also adds NOT NULL to the column in the exposed schema.  If the
110336 * table has ever had columns added using ALTER TABLE, then those
110337 * columns implicitly contain NULL for rows which have not been
110338 * updated.  [Workaround using COALESCE() in your SELECT statement.]
110339 *
110340 * The created table is read-only, with no indices.  Any SELECT will
110341 * be a full-table scan, returning each valid row read from the
110342 * storage of the backing table.  The rowid will be the rowid of the
110343 * row from the backing table.  "Valid" means:
110344 * - The cell metadata for the row is well-formed.  Mainly this means that
110345 *   the cell header info describes a payload of the size indicated by
110346 *   the cell's payload size.
110347 * - The cell does not run off the page.
110348 * - The cell does not overlap any other cell on the page.
110349 * - The cell contains doesn't contain too many columns.
110350 * - The types of the serialized data match the indicated types (see below).
110351 *
110352 *
110353 * Type affinity versus type storage.
110354 *
110355 * http://www.sqlite.org/datatype3.html describes SQLite's type
110356 * affinity system.  The system provides for automated coercion of
110357 * types in certain cases, transparently enough that many developers
110358 * do not realize that it is happening.  Importantly, it implies that
110359 * the raw data stored in the database may not have the obvious type.
110360 *
110361 * Differences between the stored data types and the expected data
110362 * types may be a signal of corruption.  This module makes some
110363 * allowances for automatic coercion.  It is important to be concious
110364 * of the difference between the schema exposed by the module, and the
110365 * data types read from storage.  The following table describes how
110366 * the module interprets things:
110367 *
110368 * type     schema   data                     STRICT
110369 * ----     ------   ----                     ------
110370 * ANY      <none>   any                      any
110371 * ROWID    INTEGER  n/a                      n/a
110372 * INTEGER  INTEGER  integer                  integer
110373 * FLOAT    FLOAT    integer or float         float
110374 * NUMERIC  NUMERIC  integer, float, or text  integer or float
110375 * TEXT     TEXT     text or blob             text
110376 * BLOB     BLOB     blob                     blob
110377 *
110378 * type is the type provided to the recover module, schema is the
110379 * schema exposed by the module, data is the acceptable types of data
110380 * decoded from storage, and STRICT is a modification of that.
110381 *
110382 * A very loose recovery system might use ANY for all columns, then
110383 * use the appropriate sqlite3_column_*() calls to coerce to expected
110384 * types.  This doesn't provide much protection if a page from a
110385 * different table with the same column count is linked into an
110386 * inappropriate btree.
110387 *
110388 * A very tight recovery system might use STRICT to enforce typing on
110389 * all columns, preferring to skip rows which are valid at the storage
110390 * level but don't contain the right types.  Note that FLOAT STRICT is
110391 * almost certainly not appropriate, since integral values are
110392 * transparently stored as integers, when that is more efficient.
110393 *
110394 * Another option is to use ANY for all columns and inspect each
110395 * result manually (using sqlite3_column_*).  This should only be
110396 * necessary in cases where developers have used manifest typing (test
110397 * to make sure before you decide that you aren't using manifest
110398 * typing!).
110399 *
110400 *
110401 * Caveats
110402 *
110403 * Leaf pages not referenced by interior nodes will not be found.
110404 *
110405 * Leaf pages referenced from interior nodes of other tables will not
110406 * be resolved.
110407 *
110408 * Rows referencing invalid overflow pages will be skipped.
110409 *
110410 * SQlite rows have a header which describes how to interpret the rest
110411 * of the payload.  The header can be valid in cases where the rest of
110412 * the record is actually corrupt (in the sense that the data is not
110413 * the intended data).  This can especially happen WRT overflow pages,
110414 * as lack of atomic updates between pages is the primary form of
110415 * corruption I have seen in the wild.
110416 */
110417/* The implementation is via a series of cursors.  The cursor
110418 * implementations follow the pattern:
110419 *
110420 * // Creates the cursor using various initialization info.
110421 * int cursorCreate(...);
110422 *
110423 * // Returns 1 if there is no more data, 0 otherwise.
110424 * int cursorEOF(Cursor *pCursor);
110425 *
110426 * // Various accessors can be used if not at EOF.
110427 *
110428 * // Move to the next item.
110429 * int cursorNext(Cursor *pCursor);
110430 *
110431 * // Destroy the memory associated with the cursor.
110432 * void cursorDestroy(Cursor *pCursor);
110433 *
110434 * References in the following are to sections at
110435 * http://www.sqlite.org/fileformat2.html .
110436 *
110437 * RecoverLeafCursor iterates the records in a leaf table node
110438 * described in section 1.5 "B-tree Pages".  When the node is
110439 * exhausted, an interior cursor is used to get the next leaf node,
110440 * and iteration continues there.
110441 *
110442 * RecoverInteriorCursor iterates the child pages in an interior table
110443 * node described in section 1.5 "B-tree Pages".  When the node is
110444 * exhausted, a parent interior cursor is used to get the next
110445 * interior node at the same level, and iteration continues there.
110446 *
110447 * Together these record the path from the leaf level to the root of
110448 * the tree.  Iteration happens from the leaves rather than the root
110449 * both for efficiency and putting the special case at the front of
110450 * the list is easier to implement.
110451 *
110452 * RecoverCursor uses a RecoverLeafCursor to iterate the rows of a
110453 * table, returning results via the SQLite virtual table interface.
110454 */
110455/* TODO(shess): It might be useful to allow DEFAULT in types to
110456 * specify what to do for NULL when an ALTER TABLE case comes up.
110457 * Unfortunately, simply adding it to the exposed schema and using
110458 * sqlite3_result_null() does not cause the default to be generate.
110459 * Handling it ourselves seems hard, unfortunately.
110460 */
110461
110462
110463/* Internal SQLite things that are used:
110464 * u32, u64, i64 types.
110465 * Btree, Pager, and DbPage structs.
110466 * DbPage.pData, .pPager, and .pgno
110467 * sqlite3 struct.
110468 * sqlite3BtreePager() and sqlite3BtreeGetPageSize()
110469 * sqlite3PagerAcquire() and sqlite3PagerUnref()
110470 * getVarint().
110471 */
110472
110473/* For debugging. */
110474#if 0
110475#define FNENTRY() fprintf(stderr, "In %s\n", __FUNCTION__)
110476#else
110477#define FNENTRY()
110478#endif
110479
110480/* Generic constants and helper functions. */
110481
110482static const unsigned char kTableLeafPage = 0x0D;
110483static const unsigned char kTableInteriorPage = 0x05;
110484
110485/* From section 1.5. */
110486static const unsigned kiPageTypeOffset = 0;
110487static const unsigned kiPageFreeBlockOffset = 1;
110488static const unsigned kiPageCellCountOffset = 3;
110489static const unsigned kiPageCellContentOffset = 5;
110490static const unsigned kiPageFragmentedBytesOffset = 7;
110491static const unsigned knPageLeafHeaderBytes = 8;
110492/* Interior pages contain an additional field. */
110493static const unsigned kiPageRightChildOffset = 8;
110494static const unsigned kiPageInteriorHeaderBytes = 12;
110495
110496/* Accepted types are specified by a mask. */
110497#define MASK_ROWID (1<<0)
110498#define MASK_INTEGER (1<<1)
110499#define MASK_FLOAT (1<<2)
110500#define MASK_TEXT (1<<3)
110501#define MASK_BLOB (1<<4)
110502#define MASK_NULL (1<<5)
110503
110504/* Helpers to decode fixed-size fields. */
110505static u32 decodeUnsigned16(const unsigned char *pData){
110506  return (pData[0]<<8) + pData[1];
110507}
110508static u32 decodeUnsigned32(const unsigned char *pData){
110509  return (decodeUnsigned16(pData)<<16) + decodeUnsigned16(pData+2);
110510}
110511static i64 decodeSigned(const unsigned char *pData, unsigned nBytes){
110512  i64 r = (char)(*pData);
110513  while( --nBytes ){
110514    r <<= 8;
110515    r += *(++pData);
110516  }
110517  return r;
110518}
110519/* Derived from vdbeaux.c, sqlite3VdbeSerialGet(), case 7. */
110520/* TODO(shess): Determine if swapMixedEndianFloat() applies. */
110521static double decodeFloat64(const unsigned char *pData){
110522#if !defined(NDEBUG)
110523  static const u64 t1 = ((u64)0x3ff00000)<<32;
110524  static const double r1 = 1.0;
110525  u64 t2 = t1;
110526  assert( sizeof(r1)==sizeof(t2) && memcmp(&r1, &t2, sizeof(r1))==0 );
110527#endif
110528  i64 x = decodeSigned(pData, 8);
110529  double d;
110530  memcpy(&d, &x, sizeof(x));
110531  return d;
110532}
110533
110534/* Return true if a varint can safely be read from pData/nData. */
110535/* TODO(shess): DbPage points into the middle of a buffer which
110536 * contains the page data before DbPage.  So code should always be
110537 * able to read a small number of varints safely.  Consider whether to
110538 * trust that or not.
110539 */
110540static int checkVarint(const unsigned char *pData, unsigned nData){
110541  unsigned i;
110542
110543  /* In the worst case the decoder takes all 8 bits of the 9th byte. */
110544  if( nData>=9 ){
110545    return 1;
110546  }
110547
110548  /* Look for a high-bit-clear byte in what's left. */
110549  for( i=0; i<nData; ++i ){
110550    if( !(pData[i]&0x80) ){
110551      return 1;
110552    }
110553  }
110554
110555  /* Cannot decode in the space given. */
110556  return 0;
110557}
110558
110559/* Return 1 if n varints can be read from pData/nData. */
110560static int checkVarints(const unsigned char *pData, unsigned nData,
110561                        unsigned n){
110562  unsigned nCur = 0;   /* Byte offset within current varint. */
110563  unsigned nFound = 0; /* Number of varints found. */
110564  unsigned i;
110565
110566  /* In the worst case the decoder takes all 8 bits of the 9th byte. */
110567  if( nData>=9*n ){
110568    return 1;
110569  }
110570
110571  for( i=0; nFound<n && i<nData; ++i ){
110572    nCur++;
110573    if( nCur==9 || !(pData[i]&0x80) ){
110574      nFound++;
110575      nCur = 0;
110576    }
110577  }
110578
110579  return nFound==n;
110580}
110581
110582/* ctype and str[n]casecmp() can be affected by locale (eg, tr_TR).
110583 * These versions consider only the ASCII space.
110584 */
110585/* TODO(shess): It may be reasonable to just remove the need for these
110586 * entirely.  The module could require "TEXT STRICT NOT NULL", not
110587 * "Text Strict Not Null" or whatever the developer felt like typing
110588 * that day.  Handling corrupt data is a PERFECT place to be pedantic.
110589 */
110590static int ascii_isspace(char c){
110591  /* From fts3_expr.c */
110592  return c==' ' || c=='\t' || c=='\n' || c=='\r' || c=='\v' || c=='\f';
110593}
110594static int ascii_isalnum(int x){
110595  /* From fts3_tokenizer1.c */
110596  return (x>='0' && x<='9') || (x>='A' && x<='Z') || (x>='a' && x<='z');
110597}
110598static int ascii_tolower(int x){
110599  /* From fts3_tokenizer1.c */
110600  return (x>='A' && x<='Z') ? x-'A'+'a' : x;
110601}
110602/* TODO(shess): Consider sqlite3_strnicmp() */
110603static int ascii_strncasecmp(const char *s1, const char *s2, size_t n){
110604  const unsigned char *us1 = (const unsigned char *)s1;
110605  const unsigned char *us2 = (const unsigned char *)s2;
110606  while( *us1 && *us2 && n && ascii_tolower(*us1)==ascii_tolower(*us2) ){
110607    us1++, us2++, n--;
110608  }
110609  return n ? ascii_tolower(*us1)-ascii_tolower(*us2) : 0;
110610}
110611static int ascii_strcasecmp(const char *s1, const char *s2){
110612  /* If s2 is equal through strlen(s1), will exit while() due to s1's
110613   * trailing NUL, and return NUL-s2[strlen(s1)].
110614   */
110615  return ascii_strncasecmp(s1, s2, strlen(s1)+1);
110616}
110617
110618/* For some reason I kept making mistakes with offset calculations. */
110619static const unsigned char *PageData(DbPage *pPage, unsigned iOffset){
110620  assert( iOffset<=pPage->nPageSize );
110621  return (unsigned char *)pPage->pData + iOffset;
110622}
110623
110624/* The first page in the file contains a file header in the first 100
110625 * bytes.  The page's header information comes after that.  Note that
110626 * the offsets in the page's header information are relative to the
110627 * beginning of the page, NOT the end of the page header.
110628 */
110629static const unsigned char *PageHeader(DbPage *pPage){
110630  if( pPage->pgno==1 ){
110631    const unsigned nDatabaseHeader = 100;
110632    return PageData(pPage, nDatabaseHeader);
110633  }else{
110634    return PageData(pPage, 0);
110635  }
110636}
110637
110638/* Helper to fetch the pager and page size for the named database. */
110639static int GetPager(sqlite3 *db, const char *zName,
110640                    Pager **pPager, unsigned *pnPageSize){
110641  Btree *pBt = NULL;
110642  int i;
110643  for( i=0; i<db->nDb; ++i ){
110644    if( ascii_strcasecmp(db->aDb[i].zName, zName)==0 ){
110645      pBt = db->aDb[i].pBt;
110646      break;
110647    }
110648  }
110649  if( !pBt ){
110650    return SQLITE_ERROR;
110651  }
110652
110653  *pPager = sqlite3BtreePager(pBt);
110654  *pnPageSize = sqlite3BtreeGetPageSize(pBt) - sqlite3BtreeGetReserve(pBt);
110655  return SQLITE_OK;
110656}
110657
110658/* iSerialType is a type read from a record header.  See "2.1 Record Format".
110659 */
110660
110661/* Storage size of iSerialType in bytes.  My interpretation of SQLite
110662 * documentation is that text and blob fields can have 32-bit length.
110663 * Values past 2^31-12 will need more than 32 bits to encode, which is
110664 * why iSerialType is u64.
110665 */
110666static u32 SerialTypeLength(u64 iSerialType){
110667  switch( iSerialType ){
110668    case 0 : return 0;  /* NULL */
110669    case 1 : return 1;  /* Various integers. */
110670    case 2 : return 2;
110671    case 3 : return 3;
110672    case 4 : return 4;
110673    case 5 : return 6;
110674    case 6 : return 8;
110675    case 7 : return 8;  /* 64-bit float. */
110676    case 8 : return 0;  /* Constant 0. */
110677    case 9 : return 0;  /* Constant 1. */
110678    case 10 : case 11 : assert( !"RESERVED TYPE"); return 0;
110679  }
110680  return (u32)((iSerialType>>1) - 6);
110681}
110682
110683/* True if iSerialType refers to a blob. */
110684static int SerialTypeIsBlob(u64 iSerialType){
110685  assert( iSerialType>=12 );
110686  return (iSerialType%2)==0;
110687}
110688
110689/* Returns true if the serialized type represented by iSerialType is
110690 * compatible with the given type mask.
110691 */
110692static int SerialTypeIsCompatible(u64 iSerialType, unsigned char mask){
110693  switch( iSerialType ){
110694    case 0  : return (mask&MASK_NULL)!=0;
110695    case 1  : return (mask&MASK_INTEGER)!=0;
110696    case 2  : return (mask&MASK_INTEGER)!=0;
110697    case 3  : return (mask&MASK_INTEGER)!=0;
110698    case 4  : return (mask&MASK_INTEGER)!=0;
110699    case 5  : return (mask&MASK_INTEGER)!=0;
110700    case 6  : return (mask&MASK_INTEGER)!=0;
110701    case 7  : return (mask&MASK_FLOAT)!=0;
110702    case 8  : return (mask&MASK_INTEGER)!=0;
110703    case 9  : return (mask&MASK_INTEGER)!=0;
110704    case 10 : assert( !"RESERVED TYPE"); return 0;
110705    case 11 : assert( !"RESERVED TYPE"); return 0;
110706  }
110707  return (mask&(SerialTypeIsBlob(iSerialType) ? MASK_BLOB : MASK_TEXT));
110708}
110709
110710/* Versions of strdup() with return values appropriate for
110711 * sqlite3_free().  malloc.c has sqlite3DbStrDup()/NDup(), but those
110712 * need sqlite3DbFree(), which seems intrusive.
110713 */
110714static char *sqlite3_strndup(const char *z, unsigned n){
110715  char *zNew;
110716
110717  if( z==NULL ){
110718    return NULL;
110719  }
110720
110721  zNew = sqlite3_malloc(n+1);
110722  if( zNew!=NULL ){
110723    memcpy(zNew, z, n);
110724    zNew[n] = '\0';
110725  }
110726  return zNew;
110727}
110728static char *sqlite3_strdup(const char *z){
110729  if( z==NULL ){
110730    return NULL;
110731  }
110732  return sqlite3_strndup(z, strlen(z));
110733}
110734
110735/* Fetch the page number of zTable in zDb from sqlite_master in zDb,
110736 * and put it in *piRootPage.
110737 */
110738static int getRootPage(sqlite3 *db, const char *zDb, const char *zTable,
110739                       u32 *piRootPage){
110740  char *zSql;  /* SQL selecting root page of named element. */
110741  sqlite3_stmt *pStmt;
110742  int rc;
110743
110744  if( strcmp(zTable, "sqlite_master")==0 ){
110745    *piRootPage = 1;
110746    return SQLITE_OK;
110747  }
110748
110749  zSql = sqlite3_mprintf("SELECT rootpage FROM %s.sqlite_master "
110750                         "WHERE type = 'table' AND tbl_name = %Q",
110751                         zDb, zTable);
110752  if( !zSql ){
110753    return SQLITE_NOMEM;
110754  }
110755
110756  rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
110757  sqlite3_free(zSql);
110758  if( rc!=SQLITE_OK ){
110759    return rc;
110760  }
110761
110762  /* Require a result. */
110763  rc = sqlite3_step(pStmt);
110764  if( rc==SQLITE_DONE ){
110765    rc = SQLITE_CORRUPT;
110766  }else if( rc==SQLITE_ROW ){
110767    *piRootPage = sqlite3_column_int(pStmt, 0);
110768
110769    /* Require only one result. */
110770    rc = sqlite3_step(pStmt);
110771    if( rc==SQLITE_DONE ){
110772      rc = SQLITE_OK;
110773    }else if( rc==SQLITE_ROW ){
110774      rc = SQLITE_CORRUPT;
110775    }
110776  }
110777  sqlite3_finalize(pStmt);
110778  return rc;
110779}
110780
110781static int getEncoding(sqlite3 *db, const char *zDb, int* piEncoding){
110782  sqlite3_stmt *pStmt;
110783  int rc;
110784  char *zSql = sqlite3_mprintf("PRAGMA %s.encoding", zDb);
110785  if( !zSql ){
110786    return SQLITE_NOMEM;
110787  }
110788
110789  rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
110790  sqlite3_free(zSql);
110791  if( rc!=SQLITE_OK ){
110792    return rc;
110793  }
110794
110795  /* Require a result. */
110796  rc = sqlite3_step(pStmt);
110797  if( rc==SQLITE_DONE ){
110798    /* This case should not be possible. */
110799    rc = SQLITE_CORRUPT;
110800  }else if( rc==SQLITE_ROW ){
110801    if( sqlite3_column_type(pStmt, 0)==SQLITE_TEXT ){
110802      const char* z = (const char *)sqlite3_column_text(pStmt, 0);
110803      /* These strings match the literals in pragma.c. */
110804      if( !strcmp(z, "UTF-16le") ){
110805        *piEncoding = SQLITE_UTF16LE;
110806      }else if( !strcmp(z, "UTF-16be") ){
110807        *piEncoding = SQLITE_UTF16BE;
110808      }else if( !strcmp(z, "UTF-8") ){
110809        *piEncoding = SQLITE_UTF8;
110810      }else{
110811        /* This case should not be possible. */
110812        *piEncoding = SQLITE_UTF8;
110813      }
110814    }else{
110815      /* This case should not be possible. */
110816      *piEncoding = SQLITE_UTF8;
110817    }
110818
110819    /* Require only one result. */
110820    rc = sqlite3_step(pStmt);
110821    if( rc==SQLITE_DONE ){
110822      rc = SQLITE_OK;
110823    }else if( rc==SQLITE_ROW ){
110824      /* This case should not be possible. */
110825      rc = SQLITE_CORRUPT;
110826    }
110827  }
110828  sqlite3_finalize(pStmt);
110829  return rc;
110830}
110831
110832/* Cursor for iterating interior nodes.  Interior page cells contain a
110833 * child page number and a rowid.  The child page contains items left
110834 * of the rowid (less than).  The rightmost page of the subtree is
110835 * stored in the page header.
110836 *
110837 * interiorCursorDestroy - release all resources associated with the
110838 *                         cursor and any parent cursors.
110839 * interiorCursorCreate - create a cursor with the given parent and page.
110840 * interiorCursorEOF - returns true if neither the cursor nor the
110841 *                     parent cursors can return any more data.
110842 * interiorCursorNextPage - fetch the next child page from the cursor.
110843 *
110844 * Logically, interiorCursorNextPage() returns the next child page
110845 * number from the page the cursor is currently reading, calling the
110846 * parent cursor as necessary to get new pages to read, until done.
110847 * SQLITE_ROW if a page is returned, SQLITE_DONE if out of pages,
110848 * error otherwise.  Unfortunately, if the table is corrupted
110849 * unexpected pages can be returned.  If any unexpected page is found,
110850 * leaf or otherwise, it is returned to the caller for processing,
110851 * with the interior cursor left empty.  The next call to
110852 * interiorCursorNextPage() will recurse to the parent cursor until an
110853 * interior page to iterate is returned.
110854 *
110855 * Note that while interiorCursorNextPage() will refuse to follow
110856 * loops, it does not keep track of pages returned for purposes of
110857 * preventing duplication.
110858 *
110859 * Note that interiorCursorEOF() could return false (not at EOF), and
110860 * interiorCursorNextPage() could still return SQLITE_DONE.  This
110861 * could happen if there are more cells to iterate in an interior
110862 * page, but those cells refer to invalid pages.
110863 */
110864typedef struct RecoverInteriorCursor RecoverInteriorCursor;
110865struct RecoverInteriorCursor {
110866  RecoverInteriorCursor *pParent; /* Parent node to this node. */
110867  DbPage *pPage;                  /* Reference to leaf page. */
110868  unsigned nPageSize;             /* Size of page. */
110869  unsigned nChildren;             /* Number of children on the page. */
110870  unsigned iChild;                /* Index of next child to return. */
110871};
110872
110873static void interiorCursorDestroy(RecoverInteriorCursor *pCursor){
110874  /* Destroy all the cursors to the root. */
110875  while( pCursor ){
110876    RecoverInteriorCursor *p = pCursor;
110877    pCursor = pCursor->pParent;
110878
110879    if( p->pPage ){
110880      sqlite3PagerUnref(p->pPage);
110881      p->pPage = NULL;
110882    }
110883
110884    memset(p, 0xA5, sizeof(*p));
110885    sqlite3_free(p);
110886  }
110887}
110888
110889/* Internal helper.  Reset storage in preparation for iterating pPage. */
110890static void interiorCursorSetPage(RecoverInteriorCursor *pCursor,
110891                                  DbPage *pPage){
110892  const unsigned knMinCellLength = 2 + 4 + 1;
110893  unsigned nMaxChildren;
110894  assert( PageHeader(pPage)[kiPageTypeOffset]==kTableInteriorPage );
110895
110896  if( pCursor->pPage ){
110897    sqlite3PagerUnref(pCursor->pPage);
110898    pCursor->pPage = NULL;
110899  }
110900  pCursor->pPage = pPage;
110901  pCursor->iChild = 0;
110902
110903  /* A child for each cell, plus one in the header. */
110904  pCursor->nChildren = decodeUnsigned16(PageHeader(pPage) +
110905                                        kiPageCellCountOffset) + 1;
110906
110907  /* The maximum possible value for nChildren is:
110908   *   (nPageSize - kiPageInteriorHeaderBytes) /
110909   *      (sizeof(uint16) + sizeof(uint32) + 1) + 1
110910   * Each child requires a 16-bit offset from an array after the header, and
110911   * each child contains a 32-bit page number and at least a varint (min size of
110912   * one byte).  The final child page is in the header.
110913   */
110914  nMaxChildren =
110915      (pCursor->nPageSize - kiPageInteriorHeaderBytes) / knMinCellLength + 1;
110916  if (pCursor->nChildren > nMaxChildren) {
110917    pCursor->nChildren = nMaxChildren;
110918  }
110919}
110920
110921static int interiorCursorCreate(RecoverInteriorCursor *pParent,
110922                                DbPage *pPage, int nPageSize,
110923                                RecoverInteriorCursor **ppCursor){
110924  RecoverInteriorCursor *pCursor =
110925    sqlite3_malloc(sizeof(RecoverInteriorCursor));
110926  if( !pCursor ){
110927    return SQLITE_NOMEM;
110928  }
110929
110930  memset(pCursor, 0, sizeof(*pCursor));
110931  pCursor->pParent = pParent;
110932  pCursor->nPageSize = nPageSize;
110933  interiorCursorSetPage(pCursor, pPage);
110934  *ppCursor = pCursor;
110935  return SQLITE_OK;
110936}
110937
110938/* Internal helper.  Return the child page number at iChild. */
110939static unsigned interiorCursorChildPage(RecoverInteriorCursor *pCursor){
110940  const unsigned char *pPageHeader;  /* Header of the current page. */
110941  const unsigned char *pCellOffsets; /* Offset to page's cell offsets. */
110942  unsigned iCellOffset;              /* Offset of target cell. */
110943
110944  assert( pCursor->iChild<pCursor->nChildren );
110945
110946  /* Rightmost child is in the header. */
110947  pPageHeader = PageHeader(pCursor->pPage);
110948  if( pCursor->iChild==pCursor->nChildren-1 ){
110949    return decodeUnsigned32(pPageHeader + kiPageRightChildOffset);
110950  }
110951
110952  /* Each cell is a 4-byte integer page number and a varint rowid
110953   * which is greater than the rowid of items in that sub-tree (this
110954   * module ignores ordering). The offset is from the beginning of the
110955   * page, not from the page header.
110956   */
110957  pCellOffsets = pPageHeader + kiPageInteriorHeaderBytes;
110958  iCellOffset = decodeUnsigned16(pCellOffsets + pCursor->iChild*2);
110959  if( iCellOffset<=pCursor->nPageSize-4 ){
110960    return decodeUnsigned32(PageData(pCursor->pPage, iCellOffset));
110961  }
110962
110963  /* TODO(shess): Check for cell overlaps?  Cells require 4 bytes plus
110964   * a varint.  Check could be identical to leaf check (or even a
110965   * shared helper testing for "Cells starting in this range"?).
110966   */
110967
110968  /* If the offset is broken, return an invalid page number. */
110969  return 0;
110970}
110971
110972static int interiorCursorEOF(RecoverInteriorCursor *pCursor){
110973  /* Find a parent with remaining children.  EOF if none found. */
110974  while( pCursor && pCursor->iChild>=pCursor->nChildren ){
110975    pCursor = pCursor->pParent;
110976  }
110977  return pCursor==NULL;
110978}
110979
110980/* Internal helper.  Used to detect if iPage would cause a loop. */
110981static int interiorCursorPageInUse(RecoverInteriorCursor *pCursor,
110982                                   unsigned iPage){
110983  /* Find any parent using the indicated page. */
110984  while( pCursor && pCursor->pPage->pgno!=iPage ){
110985    pCursor = pCursor->pParent;
110986  }
110987  return pCursor!=NULL;
110988}
110989
110990/* Get the next page from the interior cursor at *ppCursor.  Returns
110991 * SQLITE_ROW with the page in *ppPage, or SQLITE_DONE if out of
110992 * pages, or the error SQLite returned.
110993 *
110994 * If the tree is uneven, then when the cursor attempts to get a new
110995 * interior page from the parent cursor, it may get a non-interior
110996 * page.  In that case, the new page is returned, and *ppCursor is
110997 * updated to point to the parent cursor (this cursor is freed).
110998 */
110999/* TODO(shess): I've tried to avoid recursion in most of this code,
111000 * but this case is more challenging because the recursive call is in
111001 * the middle of operation.  One option for converting it without
111002 * adding memory management would be to retain the head pointer and
111003 * use a helper to "back up" as needed.  Another option would be to
111004 * reverse the list during traversal.
111005 */
111006static int interiorCursorNextPage(RecoverInteriorCursor **ppCursor,
111007                                  DbPage **ppPage){
111008  RecoverInteriorCursor *pCursor = *ppCursor;
111009  while( 1 ){
111010    int rc;
111011    const unsigned char *pPageHeader;  /* Header of found page. */
111012
111013    /* Find a valid child page which isn't on the stack. */
111014    while( pCursor->iChild<pCursor->nChildren ){
111015      const unsigned iPage = interiorCursorChildPage(pCursor);
111016      pCursor->iChild++;
111017      if( interiorCursorPageInUse(pCursor, iPage) ){
111018        fprintf(stderr, "Loop detected at %d\n", iPage);
111019      }else{
111020        int rc = sqlite3PagerAcquire(pCursor->pPage->pPager, iPage, ppPage, 0);
111021        if( rc==SQLITE_OK ){
111022          return SQLITE_ROW;
111023        }
111024      }
111025    }
111026
111027    /* This page has no more children.  Get next page from parent. */
111028    if( !pCursor->pParent ){
111029      return SQLITE_DONE;
111030    }
111031    rc = interiorCursorNextPage(&pCursor->pParent, ppPage);
111032    if( rc!=SQLITE_ROW ){
111033      return rc;
111034    }
111035
111036    /* If a non-interior page is received, that either means that the
111037     * tree is uneven, or that a child was re-used (say as an overflow
111038     * page).  Remove this cursor and let the caller handle the page.
111039     */
111040    pPageHeader = PageHeader(*ppPage);
111041    if( pPageHeader[kiPageTypeOffset]!=kTableInteriorPage ){
111042      *ppCursor = pCursor->pParent;
111043      pCursor->pParent = NULL;
111044      interiorCursorDestroy(pCursor);
111045      return SQLITE_ROW;
111046    }
111047
111048    /* Iterate the new page. */
111049    interiorCursorSetPage(pCursor, *ppPage);
111050    *ppPage = NULL;
111051  }
111052
111053  assert(NULL);  /* NOTREACHED() */
111054  return SQLITE_CORRUPT;
111055}
111056
111057/* Large rows are spilled to overflow pages.  The row's main page
111058 * stores the overflow page number after the local payload, with a
111059 * linked list forward from there as necessary.  overflowMaybeCreate()
111060 * and overflowGetSegment() provide an abstraction for accessing such
111061 * data while centralizing the code.
111062 *
111063 * overflowDestroy - releases all resources associated with the structure.
111064 * overflowMaybeCreate - create the overflow structure if it is needed
111065 *                       to represent the given record.  See function comment.
111066 * overflowGetSegment - fetch a segment from the record, accounting
111067 *                      for overflow pages.  Segments which are not
111068 *                      entirely contained with a page are constructed
111069 *                      into a buffer which is returned.  See function comment.
111070 */
111071typedef struct RecoverOverflow RecoverOverflow;
111072struct RecoverOverflow {
111073  RecoverOverflow *pNextOverflow;
111074  DbPage *pPage;
111075  unsigned nPageSize;
111076};
111077
111078static void overflowDestroy(RecoverOverflow *pOverflow){
111079  while( pOverflow ){
111080    RecoverOverflow *p = pOverflow;
111081    pOverflow = p->pNextOverflow;
111082
111083    if( p->pPage ){
111084      sqlite3PagerUnref(p->pPage);
111085      p->pPage = NULL;
111086    }
111087
111088    memset(p, 0xA5, sizeof(*p));
111089    sqlite3_free(p);
111090  }
111091}
111092
111093/* Internal helper.  Used to detect if iPage would cause a loop. */
111094static int overflowPageInUse(RecoverOverflow *pOverflow, unsigned iPage){
111095  while( pOverflow && pOverflow->pPage->pgno!=iPage ){
111096    pOverflow = pOverflow->pNextOverflow;
111097  }
111098  return pOverflow!=NULL;
111099}
111100
111101/* Setup to access an nRecordBytes record beginning at iRecordOffset
111102 * in pPage.  If nRecordBytes can be satisfied entirely from pPage,
111103 * then no overflow pages are needed an *pnLocalRecordBytes is set to
111104 * nRecordBytes.  Otherwise, *ppOverflow is set to the head of a list
111105 * of overflow pages, and *pnLocalRecordBytes is set to the number of
111106 * bytes local to pPage.
111107 *
111108 * overflowGetSegment() will do the right thing regardless of whether
111109 * those values are set to be in-page or not.
111110 */
111111static int overflowMaybeCreate(DbPage *pPage, unsigned nPageSize,
111112                               unsigned iRecordOffset, unsigned nRecordBytes,
111113                               unsigned *pnLocalRecordBytes,
111114                               RecoverOverflow **ppOverflow){
111115  unsigned nLocalRecordBytes;  /* Record bytes in the leaf page. */
111116  unsigned iNextPage;          /* Next page number for record data. */
111117  unsigned nBytes;             /* Maximum record bytes as of current page. */
111118  int rc;
111119  RecoverOverflow *pFirstOverflow;  /* First in linked list of pages. */
111120  RecoverOverflow *pLastOverflow;   /* End of linked list. */
111121
111122  /* Calculations from the "Table B-Tree Leaf Cell" part of section
111123   * 1.5 of http://www.sqlite.org/fileformat2.html .  maxLocal and
111124   * minLocal to match naming in btree.c.
111125   */
111126  const unsigned maxLocal = nPageSize - 35;
111127  const unsigned minLocal = ((nPageSize-12)*32/255)-23;  /* m */
111128
111129  /* Always fit anything smaller than maxLocal. */
111130  if( nRecordBytes<=maxLocal ){
111131    *pnLocalRecordBytes = nRecordBytes;
111132    *ppOverflow = NULL;
111133    return SQLITE_OK;
111134  }
111135
111136  /* Calculate the remainder after accounting for minLocal on the leaf
111137   * page and what packs evenly into overflow pages.  If the remainder
111138   * does not fit into maxLocal, then a partially-full overflow page
111139   * will be required in any case, so store as little as possible locally.
111140   */
111141  nLocalRecordBytes = minLocal+((nRecordBytes-minLocal)%(nPageSize-4));
111142  if( maxLocal<nLocalRecordBytes ){
111143    nLocalRecordBytes = minLocal;
111144  }
111145
111146  /* Don't read off the end of the page. */
111147  if( iRecordOffset+nLocalRecordBytes+4>nPageSize ){
111148    return SQLITE_CORRUPT;
111149  }
111150
111151  /* First overflow page number is after the local bytes. */
111152  iNextPage =
111153      decodeUnsigned32(PageData(pPage, iRecordOffset + nLocalRecordBytes));
111154  nBytes = nLocalRecordBytes;
111155
111156  /* While there are more pages to read, and more bytes are needed,
111157   * get another page.
111158   */
111159  pFirstOverflow = pLastOverflow = NULL;
111160  rc = SQLITE_OK;
111161  while( iNextPage && nBytes<nRecordBytes ){
111162    RecoverOverflow *pOverflow;  /* New overflow page for the list. */
111163
111164    rc = sqlite3PagerAcquire(pPage->pPager, iNextPage, &pPage, 0);
111165    if( rc!=SQLITE_OK ){
111166      break;
111167    }
111168
111169    pOverflow = sqlite3_malloc(sizeof(RecoverOverflow));
111170    if( !pOverflow ){
111171      sqlite3PagerUnref(pPage);
111172      rc = SQLITE_NOMEM;
111173      break;
111174    }
111175    memset(pOverflow, 0, sizeof(*pOverflow));
111176    pOverflow->pPage = pPage;
111177    pOverflow->nPageSize = nPageSize;
111178
111179    if( !pFirstOverflow ){
111180      pFirstOverflow = pOverflow;
111181    }else{
111182      pLastOverflow->pNextOverflow = pOverflow;
111183    }
111184    pLastOverflow = pOverflow;
111185
111186    iNextPage = decodeUnsigned32(pPage->pData);
111187    nBytes += nPageSize-4;
111188
111189    /* Avoid loops. */
111190    if( overflowPageInUse(pFirstOverflow, iNextPage) ){
111191      fprintf(stderr, "Overflow loop detected at %d\n", iNextPage);
111192      rc = SQLITE_CORRUPT;
111193      break;
111194    }
111195  }
111196
111197  /* If there were not enough pages, or too many, things are corrupt.
111198   * Not having enough pages is an obvious problem, all the data
111199   * cannot be read.  Too many pages means that the contents of the
111200   * row between the main page and the overflow page(s) is
111201   * inconsistent (most likely one or more of the overflow pages does
111202   * not really belong to this row).
111203   */
111204  if( rc==SQLITE_OK && (nBytes<nRecordBytes || iNextPage) ){
111205    rc = SQLITE_CORRUPT;
111206  }
111207
111208  if( rc==SQLITE_OK ){
111209    *ppOverflow = pFirstOverflow;
111210    *pnLocalRecordBytes = nLocalRecordBytes;
111211  }else if( pFirstOverflow ){
111212    overflowDestroy(pFirstOverflow);
111213  }
111214  return rc;
111215}
111216
111217/* Use in concert with overflowMaybeCreate() to efficiently read parts
111218 * of a potentially-overflowing record.  pPage and iRecordOffset are
111219 * the values passed into overflowMaybeCreate(), nLocalRecordBytes and
111220 * pOverflow are the values returned by that call.
111221 *
111222 * On SQLITE_OK, *ppBase points to nRequestBytes of data at
111223 * iRequestOffset within the record.  If the data exists contiguously
111224 * in a page, a direct pointer is returned, otherwise a buffer from
111225 * sqlite3_malloc() is returned with the data.  *pbFree is set true if
111226 * sqlite3_free() should be called on *ppBase.
111227 */
111228/* Operation of this function is subtle.  At any time, pPage is the
111229 * current page, with iRecordOffset and nLocalRecordBytes being record
111230 * data within pPage, and pOverflow being the overflow page after
111231 * pPage.  This allows the code to handle both the initial leaf page
111232 * and overflow pages consistently by adjusting the values
111233 * appropriately.
111234 */
111235static int overflowGetSegment(DbPage *pPage, unsigned iRecordOffset,
111236                              unsigned nLocalRecordBytes,
111237                              RecoverOverflow *pOverflow,
111238                              unsigned iRequestOffset, unsigned nRequestBytes,
111239                              unsigned char **ppBase, int *pbFree){
111240  unsigned nBase;         /* Amount of data currently collected. */
111241  unsigned char *pBase;   /* Buffer to collect record data into. */
111242
111243  /* Skip to the page containing the start of the data. */
111244  while( iRequestOffset>=nLocalRecordBytes && pOverflow ){
111245    /* Factor out current page's contribution. */
111246    iRequestOffset -= nLocalRecordBytes;
111247
111248    /* Move forward to the next page in the list. */
111249    pPage = pOverflow->pPage;
111250    iRecordOffset = 4;
111251    nLocalRecordBytes = pOverflow->nPageSize - iRecordOffset;
111252    pOverflow = pOverflow->pNextOverflow;
111253  }
111254
111255  /* If the requested data is entirely within this page, return a
111256   * pointer into the page.
111257   */
111258  if( iRequestOffset+nRequestBytes<=nLocalRecordBytes ){
111259    /* TODO(shess): "assignment discards qualifiers from pointer target type"
111260     * Having ppBase be const makes sense, but sqlite3_free() takes non-const.
111261     */
111262    *ppBase = (unsigned char *)PageData(pPage, iRecordOffset + iRequestOffset);
111263    *pbFree = 0;
111264    return SQLITE_OK;
111265  }
111266
111267  /* The data range would require additional pages. */
111268  if( !pOverflow ){
111269    /* Should never happen, the range is outside the nRecordBytes
111270     * passed to overflowMaybeCreate().
111271     */
111272    assert(NULL);  /* NOTREACHED */
111273    return SQLITE_ERROR;
111274  }
111275
111276  /* Get a buffer to construct into. */
111277  nBase = 0;
111278  pBase = sqlite3_malloc(nRequestBytes);
111279  if( !pBase ){
111280    return SQLITE_NOMEM;
111281  }
111282  while( nBase<nRequestBytes ){
111283    /* Copy over data present on this page. */
111284    unsigned nCopyBytes = nRequestBytes - nBase;
111285    if( nLocalRecordBytes-iRequestOffset<nCopyBytes ){
111286      nCopyBytes = nLocalRecordBytes - iRequestOffset;
111287    }
111288    memcpy(pBase + nBase, PageData(pPage, iRecordOffset + iRequestOffset),
111289           nCopyBytes);
111290    nBase += nCopyBytes;
111291
111292    if( pOverflow ){
111293      /* Copy from start of record data in future pages. */
111294      iRequestOffset = 0;
111295
111296      /* Move forward to the next page in the list.  Should match
111297       * first while() loop.
111298       */
111299      pPage = pOverflow->pPage;
111300      iRecordOffset = 4;
111301      nLocalRecordBytes = pOverflow->nPageSize - iRecordOffset;
111302      pOverflow = pOverflow->pNextOverflow;
111303    }else if( nBase<nRequestBytes ){
111304      /* Ran out of overflow pages with data left to deliver.  Not
111305       * possible if the requested range fits within nRecordBytes
111306       * passed to overflowMaybeCreate() when creating pOverflow.
111307       */
111308      assert(NULL);  /* NOTREACHED */
111309      sqlite3_free(pBase);
111310      return SQLITE_ERROR;
111311    }
111312  }
111313  assert( nBase==nRequestBytes );
111314  *ppBase = pBase;
111315  *pbFree = 1;
111316  return SQLITE_OK;
111317}
111318
111319/* Primary structure for iterating the contents of a table.
111320 *
111321 * leafCursorDestroy - release all resources associated with the cursor.
111322 * leafCursorCreate - create a cursor to iterate items from tree at
111323 *                    the provided root page.
111324 * leafCursorNextValidCell - get the cursor ready to access data from
111325 *                           the next valid cell in the table.
111326 * leafCursorCellRowid - get the current cell's rowid.
111327 * leafCursorCellColumns - get current cell's column count.
111328 * leafCursorCellColInfo - get type and data for a column in current cell.
111329 *
111330 * leafCursorNextValidCell skips cells which fail simple integrity
111331 * checks, such as overlapping other cells, or being located at
111332 * impossible offsets, or where header data doesn't correctly describe
111333 * payload data.  Returns SQLITE_ROW if a valid cell is found,
111334 * SQLITE_DONE if all pages in the tree were exhausted.
111335 *
111336 * leafCursorCellColInfo() accounts for overflow pages in the style of
111337 * overflowGetSegment().
111338 */
111339typedef struct RecoverLeafCursor RecoverLeafCursor;
111340struct RecoverLeafCursor {
111341  RecoverInteriorCursor *pParent;  /* Parent node to this node. */
111342  DbPage *pPage;                   /* Reference to leaf page. */
111343  unsigned nPageSize;              /* Size of pPage. */
111344  unsigned nCells;                 /* Number of cells in pPage. */
111345  unsigned iCell;                  /* Current cell. */
111346
111347  /* Info parsed from data in iCell. */
111348  i64 iRowid;                      /* rowid parsed. */
111349  unsigned nRecordCols;            /* how many items in the record. */
111350  u64 iRecordOffset;               /* offset to record data. */
111351  /* TODO(shess): nRecordBytes and nRecordHeaderBytes are used in
111352   * leafCursorCellColInfo() to prevent buffer overruns.
111353   * leafCursorCellDecode() already verified that the cell is valid, so
111354   * those checks should be redundant.
111355   */
111356  u64 nRecordBytes;                /* Size of record data. */
111357  unsigned nLocalRecordBytes;      /* Amount of record data in-page. */
111358  unsigned nRecordHeaderBytes;     /* Size of record header data. */
111359  unsigned char *pRecordHeader;    /* Pointer to record header data. */
111360  int bFreeRecordHeader;           /* True if record header requires free. */
111361  RecoverOverflow *pOverflow;      /* Cell overflow info, if needed. */
111362};
111363
111364/* Internal helper shared between next-page and create-cursor.  If
111365 * pPage is a leaf page, it will be stored in the cursor and state
111366 * initialized for reading cells.
111367 *
111368 * If pPage is an interior page, a new parent cursor is created and
111369 * injected on the stack.  This is necessary to handle trees with
111370 * uneven depth, but also is used during initial setup.
111371 *
111372 * If pPage is not a table page at all, it is discarded.
111373 *
111374 * If SQLITE_OK is returned, the caller no longer owns pPage,
111375 * otherwise the caller is responsible for discarding it.
111376 */
111377static int leafCursorLoadPage(RecoverLeafCursor *pCursor, DbPage *pPage){
111378  const unsigned char *pPageHeader;  /* Header of *pPage */
111379
111380  /* Release the current page. */
111381  if( pCursor->pPage ){
111382    sqlite3PagerUnref(pCursor->pPage);
111383    pCursor->pPage = NULL;
111384    pCursor->iCell = pCursor->nCells = 0;
111385  }
111386
111387  /* If the page is an unexpected interior node, inject a new stack
111388   * layer and try again from there.
111389   */
111390  pPageHeader = PageHeader(pPage);
111391  if( pPageHeader[kiPageTypeOffset]==kTableInteriorPage ){
111392    RecoverInteriorCursor *pParent;
111393    int rc = interiorCursorCreate(pCursor->pParent, pPage, pCursor->nPageSize,
111394                                  &pParent);
111395    if( rc!=SQLITE_OK ){
111396      return rc;
111397    }
111398    pCursor->pParent = pParent;
111399    return SQLITE_OK;
111400  }
111401
111402  /* Not a leaf page, skip it. */
111403  if( pPageHeader[kiPageTypeOffset]!=kTableLeafPage ){
111404    sqlite3PagerUnref(pPage);
111405    return SQLITE_OK;
111406  }
111407
111408  /* Take ownership of the page and start decoding. */
111409  pCursor->pPage = pPage;
111410  pCursor->iCell = 0;
111411  pCursor->nCells = decodeUnsigned16(pPageHeader + kiPageCellCountOffset);
111412  return SQLITE_OK;
111413}
111414
111415/* Get the next leaf-level page in the tree.  Returns SQLITE_ROW when
111416 * a leaf page is found, SQLITE_DONE when no more leaves exist, or any
111417 * error which occurred.
111418 */
111419static int leafCursorNextPage(RecoverLeafCursor *pCursor){
111420  if( !pCursor->pParent ){
111421    return SQLITE_DONE;
111422  }
111423
111424  /* Repeatedly load the parent's next child page until a leaf is found. */
111425  do {
111426    DbPage *pNextPage;
111427    int rc = interiorCursorNextPage(&pCursor->pParent, &pNextPage);
111428    if( rc!=SQLITE_ROW ){
111429      assert( rc==SQLITE_DONE );
111430      return rc;
111431    }
111432
111433    rc = leafCursorLoadPage(pCursor, pNextPage);
111434    if( rc!=SQLITE_OK ){
111435      sqlite3PagerUnref(pNextPage);
111436      return rc;
111437    }
111438  } while( !pCursor->pPage );
111439
111440  return SQLITE_ROW;
111441}
111442
111443static void leafCursorDestroyCellData(RecoverLeafCursor *pCursor){
111444  if( pCursor->bFreeRecordHeader ){
111445    sqlite3_free(pCursor->pRecordHeader);
111446  }
111447  pCursor->bFreeRecordHeader = 0;
111448  pCursor->pRecordHeader = NULL;
111449
111450  if( pCursor->pOverflow ){
111451    overflowDestroy(pCursor->pOverflow);
111452    pCursor->pOverflow = NULL;
111453  }
111454}
111455
111456static void leafCursorDestroy(RecoverLeafCursor *pCursor){
111457  leafCursorDestroyCellData(pCursor);
111458
111459  if( pCursor->pParent ){
111460    interiorCursorDestroy(pCursor->pParent);
111461    pCursor->pParent = NULL;
111462  }
111463
111464  if( pCursor->pPage ){
111465    sqlite3PagerUnref(pCursor->pPage);
111466    pCursor->pPage = NULL;
111467  }
111468
111469  memset(pCursor, 0xA5, sizeof(*pCursor));
111470  sqlite3_free(pCursor);
111471}
111472
111473/* Create a cursor to iterate the rows from the leaf pages of a table
111474 * rooted at iRootPage.
111475 */
111476/* TODO(shess): recoverOpen() calls this to setup the cursor, and I
111477 * think that recoverFilter() may make a hard assumption that the
111478 * cursor returned will turn up at least one valid cell.
111479 *
111480 * The cases I can think of which break this assumption are:
111481 * - pPage is a valid leaf page with no valid cells.
111482 * - pPage is a valid interior page with no valid leaves.
111483 * - pPage is a valid interior page who's leaves contain no valid cells.
111484 * - pPage is not a valid leaf or interior page.
111485 */
111486static int leafCursorCreate(Pager *pPager, unsigned nPageSize,
111487                            u32 iRootPage, RecoverLeafCursor **ppCursor){
111488  DbPage *pPage;               /* Reference to page at iRootPage. */
111489  RecoverLeafCursor *pCursor;  /* Leaf cursor being constructed. */
111490  int rc;
111491
111492  /* Start out with the root page. */
111493  rc = sqlite3PagerAcquire(pPager, iRootPage, &pPage, 0);
111494  if( rc!=SQLITE_OK ){
111495    return rc;
111496  }
111497
111498  pCursor = sqlite3_malloc(sizeof(RecoverLeafCursor));
111499  if( !pCursor ){
111500    sqlite3PagerUnref(pPage);
111501    return SQLITE_NOMEM;
111502  }
111503  memset(pCursor, 0, sizeof(*pCursor));
111504
111505  pCursor->nPageSize = nPageSize;
111506
111507  rc = leafCursorLoadPage(pCursor, pPage);
111508  if( rc!=SQLITE_OK ){
111509    sqlite3PagerUnref(pPage);
111510    leafCursorDestroy(pCursor);
111511    return rc;
111512  }
111513
111514  /* pPage wasn't a leaf page, find the next leaf page. */
111515  if( !pCursor->pPage ){
111516    rc = leafCursorNextPage(pCursor);
111517    if( rc!=SQLITE_DONE && rc!=SQLITE_ROW ){
111518      leafCursorDestroy(pCursor);
111519      return rc;
111520    }
111521  }
111522
111523  *ppCursor = pCursor;
111524  return SQLITE_OK;
111525}
111526
111527/* Useful for setting breakpoints. */
111528static int ValidateError(){
111529  return SQLITE_ERROR;
111530}
111531
111532/* Setup the cursor for reading the information from cell iCell. */
111533static int leafCursorCellDecode(RecoverLeafCursor *pCursor){
111534  const unsigned char *pPageHeader;  /* Header of current page. */
111535  const unsigned char *pPageEnd;     /* Byte after end of current page. */
111536  const unsigned char *pCellOffsets; /* Pointer to page's cell offsets. */
111537  unsigned iCellOffset;              /* Offset of current cell (iCell). */
111538  const unsigned char *pCell;        /* Pointer to data at iCellOffset. */
111539  unsigned nCellMaxBytes;            /* Maximum local size of iCell. */
111540  unsigned iEndOffset;               /* End of iCell's in-page data. */
111541  u64 nRecordBytes;                  /* Expected size of cell, w/overflow. */
111542  u64 iRowid;                        /* iCell's rowid (in table). */
111543  unsigned nRead;                    /* Amount of cell read. */
111544  unsigned nRecordHeaderRead;        /* Header data read. */
111545  u64 nRecordHeaderBytes;            /* Header size expected. */
111546  unsigned nRecordCols;              /* Columns read from header. */
111547  u64 nRecordColBytes;               /* Bytes in payload for those columns. */
111548  unsigned i;
111549  int rc;
111550
111551  assert( pCursor->iCell<pCursor->nCells );
111552
111553  leafCursorDestroyCellData(pCursor);
111554
111555  /* Find the offset to the row. */
111556  pPageHeader = PageHeader(pCursor->pPage);
111557  pCellOffsets = pPageHeader + knPageLeafHeaderBytes;
111558  pPageEnd = PageData(pCursor->pPage, pCursor->nPageSize);
111559  if( pCellOffsets + pCursor->iCell*2 + 2 > pPageEnd ){
111560    return ValidateError();
111561  }
111562  iCellOffset = decodeUnsigned16(pCellOffsets + pCursor->iCell*2);
111563  if( iCellOffset>=pCursor->nPageSize ){
111564    return ValidateError();
111565  }
111566
111567  pCell = PageData(pCursor->pPage, iCellOffset);
111568  nCellMaxBytes = pCursor->nPageSize - iCellOffset;
111569
111570  /* B-tree leaf cells lead with varint record size, varint rowid and
111571   * varint header size.
111572   */
111573  /* TODO(shess): The smallest page size is 512 bytes, which has an m
111574   * of 39.  Three varints need at most 27 bytes to encode.  I think.
111575   */
111576  if( !checkVarints(pCell, nCellMaxBytes, 3) ){
111577    return ValidateError();
111578  }
111579
111580  nRead = getVarint(pCell, &nRecordBytes);
111581  assert( iCellOffset+nRead<=pCursor->nPageSize );
111582  pCursor->nRecordBytes = nRecordBytes;
111583
111584  nRead += getVarint(pCell + nRead, &iRowid);
111585  assert( iCellOffset+nRead<=pCursor->nPageSize );
111586  pCursor->iRowid = (i64)iRowid;
111587
111588  pCursor->iRecordOffset = iCellOffset + nRead;
111589
111590  /* Start overflow setup here because nLocalRecordBytes is needed to
111591   * check cell overlap.
111592   */
111593  rc = overflowMaybeCreate(pCursor->pPage, pCursor->nPageSize,
111594                           pCursor->iRecordOffset, pCursor->nRecordBytes,
111595                           &pCursor->nLocalRecordBytes,
111596                           &pCursor->pOverflow);
111597  if( rc!=SQLITE_OK ){
111598    return ValidateError();
111599  }
111600
111601  /* Check that no other cell starts within this cell. */
111602  iEndOffset = pCursor->iRecordOffset + pCursor->nLocalRecordBytes;
111603  for( i=0; i<pCursor->nCells && pCellOffsets + i*2 + 2 <= pPageEnd; ++i ){
111604    const unsigned iOtherOffset = decodeUnsigned16(pCellOffsets + i*2);
111605    if( iOtherOffset>iCellOffset && iOtherOffset<iEndOffset ){
111606      return ValidateError();
111607    }
111608  }
111609
111610  nRecordHeaderRead = getVarint(pCell + nRead, &nRecordHeaderBytes);
111611  assert( nRecordHeaderBytes<=nRecordBytes );
111612  pCursor->nRecordHeaderBytes = nRecordHeaderBytes;
111613
111614  /* Large headers could overflow if pages are small. */
111615  rc = overflowGetSegment(pCursor->pPage,
111616                          pCursor->iRecordOffset, pCursor->nLocalRecordBytes,
111617                          pCursor->pOverflow, 0, nRecordHeaderBytes,
111618                          &pCursor->pRecordHeader, &pCursor->bFreeRecordHeader);
111619  if( rc!=SQLITE_OK ){
111620    return ValidateError();
111621  }
111622
111623  /* Tally up the column count and size of data. */
111624  nRecordCols = 0;
111625  nRecordColBytes = 0;
111626  while( nRecordHeaderRead<nRecordHeaderBytes ){
111627    u64 iSerialType;  /* Type descriptor for current column. */
111628    if( !checkVarint(pCursor->pRecordHeader + nRecordHeaderRead,
111629                     nRecordHeaderBytes - nRecordHeaderRead) ){
111630      return ValidateError();
111631    }
111632    nRecordHeaderRead += getVarint(pCursor->pRecordHeader + nRecordHeaderRead,
111633                                   &iSerialType);
111634    if( iSerialType==10 || iSerialType==11 ){
111635      return ValidateError();
111636    }
111637    nRecordColBytes += SerialTypeLength(iSerialType);
111638    nRecordCols++;
111639  }
111640  pCursor->nRecordCols = nRecordCols;
111641
111642  /* Parsing the header used as many bytes as expected. */
111643  if( nRecordHeaderRead!=nRecordHeaderBytes ){
111644    return ValidateError();
111645  }
111646
111647  /* Calculated record is size of expected record. */
111648  if( nRecordHeaderBytes+nRecordColBytes!=nRecordBytes ){
111649    return ValidateError();
111650  }
111651
111652  return SQLITE_OK;
111653}
111654
111655static i64 leafCursorCellRowid(RecoverLeafCursor *pCursor){
111656  return pCursor->iRowid;
111657}
111658
111659static unsigned leafCursorCellColumns(RecoverLeafCursor *pCursor){
111660  return pCursor->nRecordCols;
111661}
111662
111663/* Get the column info for the cell.  Pass NULL for ppBase to prevent
111664 * retrieving the data segment.  If *pbFree is true, *ppBase must be
111665 * freed by the caller using sqlite3_free().
111666 */
111667static int leafCursorCellColInfo(RecoverLeafCursor *pCursor,
111668                                 unsigned iCol, u64 *piColType,
111669                                 unsigned char **ppBase, int *pbFree){
111670  const unsigned char *pRecordHeader;  /* Current cell's header. */
111671  u64 nRecordHeaderBytes;              /* Bytes in pRecordHeader. */
111672  unsigned nRead;                      /* Bytes read from header. */
111673  u64 iColEndOffset;                   /* Offset to end of column in cell. */
111674  unsigned nColsSkipped;               /* Count columns as procesed. */
111675  u64 iSerialType;                     /* Type descriptor for current column. */
111676
111677  /* Implicit NULL for columns past the end.  This case happens when
111678   * rows have not been updated since an ALTER TABLE added columns.
111679   * It is more convenient to address here than in callers.
111680   */
111681  if( iCol>=pCursor->nRecordCols ){
111682    *piColType = 0;
111683    if( ppBase ){
111684      *ppBase = 0;
111685      *pbFree = 0;
111686    }
111687    return SQLITE_OK;
111688  }
111689
111690  /* Must be able to decode header size. */
111691  pRecordHeader = pCursor->pRecordHeader;
111692  if( !checkVarint(pRecordHeader, pCursor->nRecordHeaderBytes) ){
111693    return SQLITE_CORRUPT;
111694  }
111695
111696  /* Rather than caching the header size and how many bytes it took,
111697   * decode it every time.
111698   */
111699  nRead = getVarint(pRecordHeader, &nRecordHeaderBytes);
111700  assert( nRecordHeaderBytes==pCursor->nRecordHeaderBytes );
111701
111702  /* Scan forward to the indicated column.  Scans to _after_ column
111703   * for later range checking.
111704   */
111705  /* TODO(shess): This could get expensive for very wide tables.  An
111706   * array of iSerialType could be built in leafCursorCellDecode(), but
111707   * the number of columns is dynamic per row, so it would add memory
111708   * management complexity.  Enough info to efficiently forward
111709   * iterate could be kept, if all clients forward iterate
111710   * (recoverColumn() may not).
111711   */
111712  iColEndOffset = 0;
111713  nColsSkipped = 0;
111714  while( nColsSkipped<=iCol && nRead<nRecordHeaderBytes ){
111715    if( !checkVarint(pRecordHeader + nRead, nRecordHeaderBytes - nRead) ){
111716      return SQLITE_CORRUPT;
111717    }
111718    nRead += getVarint(pRecordHeader + nRead, &iSerialType);
111719    iColEndOffset += SerialTypeLength(iSerialType);
111720    nColsSkipped++;
111721  }
111722
111723  /* Column's data extends past record's end. */
111724  if( nRecordHeaderBytes+iColEndOffset>pCursor->nRecordBytes ){
111725    return SQLITE_CORRUPT;
111726  }
111727
111728  *piColType = iSerialType;
111729  if( ppBase ){
111730    const u32 nColBytes = SerialTypeLength(iSerialType);
111731
111732    /* Offset from start of record to beginning of column. */
111733    const unsigned iColOffset = nRecordHeaderBytes+iColEndOffset-nColBytes;
111734
111735    return overflowGetSegment(pCursor->pPage, pCursor->iRecordOffset,
111736                              pCursor->nLocalRecordBytes, pCursor->pOverflow,
111737                              iColOffset, nColBytes, ppBase, pbFree);
111738  }
111739  return SQLITE_OK;
111740}
111741
111742static int leafCursorNextValidCell(RecoverLeafCursor *pCursor){
111743  while( 1 ){
111744    int rc;
111745
111746    /* Move to the next cell. */
111747    pCursor->iCell++;
111748
111749    /* No more cells, get the next leaf. */
111750    if( pCursor->iCell>=pCursor->nCells ){
111751      rc = leafCursorNextPage(pCursor);
111752      if( rc!=SQLITE_ROW ){
111753        return rc;
111754      }
111755      assert( pCursor->iCell==0 );
111756    }
111757
111758    /* If the cell is valid, indicate that a row is available. */
111759    rc = leafCursorCellDecode(pCursor);
111760    if( rc==SQLITE_OK ){
111761      return SQLITE_ROW;
111762    }
111763
111764    /* Iterate until done or a valid row is found. */
111765    /* TODO(shess): Remove debugging output. */
111766    fprintf(stderr, "Skipping invalid cell\n");
111767  }
111768  return SQLITE_ERROR;
111769}
111770
111771typedef struct Recover Recover;
111772struct Recover {
111773  sqlite3_vtab base;
111774  sqlite3 *db;                /* Host database connection */
111775  char *zDb;                  /* Database containing target table */
111776  char *zTable;               /* Target table */
111777  unsigned nCols;             /* Number of columns in target table */
111778  unsigned char *pTypes;      /* Types of columns in target table */
111779};
111780
111781/* Internal helper for deleting the module. */
111782static void recoverRelease(Recover *pRecover){
111783  sqlite3_free(pRecover->zDb);
111784  sqlite3_free(pRecover->zTable);
111785  sqlite3_free(pRecover->pTypes);
111786  memset(pRecover, 0xA5, sizeof(*pRecover));
111787  sqlite3_free(pRecover);
111788}
111789
111790/* Helper function for initializing the module.  Forward-declared so
111791 * recoverCreate() and recoverConnect() can see it.
111792 */
111793static int recoverInit(
111794  sqlite3 *, void *, int, const char *const*, sqlite3_vtab **, char **
111795);
111796
111797static int recoverCreate(
111798  sqlite3 *db,
111799  void *pAux,
111800  int argc, const char *const*argv,
111801  sqlite3_vtab **ppVtab,
111802  char **pzErr
111803){
111804  FNENTRY();
111805  return recoverInit(db, pAux, argc, argv, ppVtab, pzErr);
111806}
111807
111808/* This should never be called. */
111809static int recoverConnect(
111810  sqlite3 *db,
111811  void *pAux,
111812  int argc, const char *const*argv,
111813  sqlite3_vtab **ppVtab,
111814  char **pzErr
111815){
111816  FNENTRY();
111817  return recoverInit(db, pAux, argc, argv, ppVtab, pzErr);
111818}
111819
111820/* No indices supported. */
111821static int recoverBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){
111822  FNENTRY();
111823  return SQLITE_OK;
111824}
111825
111826/* Logically, this should never be called. */
111827static int recoverDisconnect(sqlite3_vtab *pVtab){
111828  FNENTRY();
111829  recoverRelease((Recover*)pVtab);
111830  return SQLITE_OK;
111831}
111832
111833static int recoverDestroy(sqlite3_vtab *pVtab){
111834  FNENTRY();
111835  recoverRelease((Recover*)pVtab);
111836  return SQLITE_OK;
111837}
111838
111839typedef struct RecoverCursor RecoverCursor;
111840struct RecoverCursor {
111841  sqlite3_vtab_cursor base;
111842  RecoverLeafCursor *pLeafCursor;
111843  int iEncoding;
111844  int bEOF;
111845};
111846
111847static int recoverOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
111848  Recover *pRecover = (Recover*)pVTab;
111849  u32 iRootPage;                   /* Root page of the backing table. */
111850  int iEncoding;                   /* UTF encoding for backing database. */
111851  unsigned nPageSize;              /* Size of pages in backing database. */
111852  Pager *pPager;                   /* Backing database pager. */
111853  RecoverLeafCursor *pLeafCursor;  /* Cursor to read table's leaf pages. */
111854  RecoverCursor *pCursor;          /* Cursor to read rows from leaves. */
111855  int rc;
111856
111857  FNENTRY();
111858
111859  iRootPage = 0;
111860  rc = getRootPage(pRecover->db, pRecover->zDb, pRecover->zTable,
111861                   &iRootPage);
111862  if( rc!=SQLITE_OK ){
111863    return rc;
111864  }
111865
111866  iEncoding = 0;
111867  rc = getEncoding(pRecover->db, pRecover->zDb, &iEncoding);
111868  if( rc!=SQLITE_OK ){
111869    return rc;
111870  }
111871
111872  rc = GetPager(pRecover->db, pRecover->zDb, &pPager, &nPageSize);
111873  if( rc!=SQLITE_OK ){
111874    return rc;
111875  }
111876
111877  rc = leafCursorCreate(pPager, nPageSize, iRootPage, &pLeafCursor);
111878  if( rc!=SQLITE_OK ){
111879    return rc;
111880  }
111881
111882  pCursor = sqlite3_malloc(sizeof(RecoverCursor));
111883  if( !pCursor ){
111884    leafCursorDestroy(pLeafCursor);
111885    return SQLITE_NOMEM;
111886  }
111887  memset(pCursor, 0, sizeof(*pCursor));
111888  pCursor->base.pVtab = pVTab;
111889  pCursor->pLeafCursor = pLeafCursor;
111890  pCursor->iEncoding = iEncoding;
111891
111892  /* If no leaf pages were found, empty result set. */
111893  /* TODO(shess): leafCursorNextValidCell() would return SQLITE_ROW or
111894   * SQLITE_DONE to indicate whether there is further data to consider.
111895   */
111896  pCursor->bEOF = (pLeafCursor->pPage==NULL);
111897
111898  *ppCursor = (sqlite3_vtab_cursor*)pCursor;
111899  return SQLITE_OK;
111900}
111901
111902static int recoverClose(sqlite3_vtab_cursor *cur){
111903  RecoverCursor *pCursor = (RecoverCursor*)cur;
111904  FNENTRY();
111905  if( pCursor->pLeafCursor ){
111906    leafCursorDestroy(pCursor->pLeafCursor);
111907    pCursor->pLeafCursor = NULL;
111908  }
111909  memset(pCursor, 0xA5, sizeof(*pCursor));
111910  sqlite3_free(cur);
111911  return SQLITE_OK;
111912}
111913
111914/* Helpful place to set a breakpoint. */
111915static int RecoverInvalidCell(){
111916  return SQLITE_ERROR;
111917}
111918
111919/* Returns SQLITE_OK if the cell has an appropriate number of columns
111920 * with the appropriate types of data.
111921 */
111922static int recoverValidateLeafCell(Recover *pRecover, RecoverCursor *pCursor){
111923  unsigned i;
111924
111925  /* If the row's storage has too many columns, skip it. */
111926  if( leafCursorCellColumns(pCursor->pLeafCursor)>pRecover->nCols ){
111927    return RecoverInvalidCell();
111928  }
111929
111930  /* Skip rows with unexpected types. */
111931  for( i=0; i<pRecover->nCols; ++i ){
111932    u64 iType;  /* Storage type of column i. */
111933    int rc;
111934
111935    /* ROWID alias. */
111936    if( (pRecover->pTypes[i]&MASK_ROWID) ){
111937      continue;
111938    }
111939
111940    rc = leafCursorCellColInfo(pCursor->pLeafCursor, i, &iType, NULL, NULL);
111941    assert( rc==SQLITE_OK );
111942    if( rc!=SQLITE_OK || !SerialTypeIsCompatible(iType, pRecover->pTypes[i]) ){
111943      return RecoverInvalidCell();
111944    }
111945  }
111946
111947  return SQLITE_OK;
111948}
111949
111950static int recoverNext(sqlite3_vtab_cursor *pVtabCursor){
111951  RecoverCursor *pCursor = (RecoverCursor*)pVtabCursor;
111952  Recover *pRecover = (Recover*)pCursor->base.pVtab;
111953  int rc;
111954
111955  FNENTRY();
111956
111957  /* Scan forward to the next cell with valid storage, then check that
111958   * the stored data matches the schema.
111959   */
111960  while( (rc = leafCursorNextValidCell(pCursor->pLeafCursor))==SQLITE_ROW ){
111961    if( recoverValidateLeafCell(pRecover, pCursor)==SQLITE_OK ){
111962      return SQLITE_OK;
111963    }
111964  }
111965
111966  if( rc==SQLITE_DONE ){
111967    pCursor->bEOF = 1;
111968    return SQLITE_OK;
111969  }
111970
111971  assert( rc!=SQLITE_OK );
111972  return rc;
111973}
111974
111975static int recoverFilter(
111976  sqlite3_vtab_cursor *pVtabCursor,
111977  int idxNum, const char *idxStr,
111978  int argc, sqlite3_value **argv
111979){
111980  RecoverCursor *pCursor = (RecoverCursor*)pVtabCursor;
111981  Recover *pRecover = (Recover*)pCursor->base.pVtab;
111982  int rc;
111983
111984  FNENTRY();
111985
111986  /* There were no valid leaf pages in the table. */
111987  if( pCursor->bEOF ){
111988    return SQLITE_OK;
111989  }
111990
111991  /* Load the first cell, and iterate forward if it's not valid.  If no cells at
111992   * all are valid, recoverNext() sets bEOF and returns appropriately.
111993   */
111994  rc = leafCursorCellDecode(pCursor->pLeafCursor);
111995  if( rc!=SQLITE_OK || recoverValidateLeafCell(pRecover, pCursor)!=SQLITE_OK ){
111996    return recoverNext(pVtabCursor);
111997  }
111998
111999  return SQLITE_OK;
112000}
112001
112002static int recoverEof(sqlite3_vtab_cursor *pVtabCursor){
112003  RecoverCursor *pCursor = (RecoverCursor*)pVtabCursor;
112004  FNENTRY();
112005  return pCursor->bEOF;
112006}
112007
112008static int recoverColumn(sqlite3_vtab_cursor *cur, sqlite3_context *ctx, int i){
112009  RecoverCursor *pCursor = (RecoverCursor*)cur;
112010  Recover *pRecover = (Recover*)pCursor->base.pVtab;
112011  u64 iColType;             /* Storage type of column i. */
112012  unsigned char *pColData;  /* Column i's data. */
112013  int shouldFree;           /* Non-zero if pColData should be freed. */
112014  int rc;
112015
112016  FNENTRY();
112017
112018  if( i>=pRecover->nCols ){
112019    return SQLITE_ERROR;
112020  }
112021
112022  /* ROWID alias. */
112023  if( (pRecover->pTypes[i]&MASK_ROWID) ){
112024    sqlite3_result_int64(ctx, leafCursorCellRowid(pCursor->pLeafCursor));
112025    return SQLITE_OK;
112026  }
112027
112028  pColData = NULL;
112029  shouldFree = 0;
112030  rc = leafCursorCellColInfo(pCursor->pLeafCursor, i, &iColType,
112031                             &pColData, &shouldFree);
112032  if( rc!=SQLITE_OK ){
112033    return rc;
112034  }
112035  /* recoverValidateLeafCell() should guarantee that this will never
112036   * occur.
112037   */
112038  if( !SerialTypeIsCompatible(iColType, pRecover->pTypes[i]) ){
112039    if( shouldFree ){
112040      sqlite3_free(pColData);
112041    }
112042    return SQLITE_ERROR;
112043  }
112044
112045  switch( iColType ){
112046    case 0 : sqlite3_result_null(ctx); break;
112047    case 1 : sqlite3_result_int64(ctx, decodeSigned(pColData, 1)); break;
112048    case 2 : sqlite3_result_int64(ctx, decodeSigned(pColData, 2)); break;
112049    case 3 : sqlite3_result_int64(ctx, decodeSigned(pColData, 3)); break;
112050    case 4 : sqlite3_result_int64(ctx, decodeSigned(pColData, 4)); break;
112051    case 5 : sqlite3_result_int64(ctx, decodeSigned(pColData, 6)); break;
112052    case 6 : sqlite3_result_int64(ctx, decodeSigned(pColData, 8)); break;
112053    case 7 : sqlite3_result_double(ctx, decodeFloat64(pColData)); break;
112054    case 8 : sqlite3_result_int(ctx, 0); break;
112055    case 9 : sqlite3_result_int(ctx, 1); break;
112056    case 10 : assert( iColType!=10 ); break;
112057    case 11 : assert( iColType!=11 ); break;
112058
112059    default : {
112060      u32 l = SerialTypeLength(iColType);
112061
112062      /* If pColData was already allocated, arrange to pass ownership. */
112063      sqlite3_destructor_type pFn = SQLITE_TRANSIENT;
112064      if( shouldFree ){
112065        pFn = sqlite3_free;
112066        shouldFree = 0;
112067      }
112068
112069      if( SerialTypeIsBlob(iColType) ){
112070        sqlite3_result_blob(ctx, pColData, l, pFn);
112071      }else{
112072        if( pCursor->iEncoding==SQLITE_UTF16LE ){
112073          sqlite3_result_text16le(ctx, (const void*)pColData, l, pFn);
112074        }else if( pCursor->iEncoding==SQLITE_UTF16BE ){
112075          sqlite3_result_text16be(ctx, (const void*)pColData, l, pFn);
112076        }else{
112077          sqlite3_result_text(ctx, (const char*)pColData, l, pFn);
112078        }
112079      }
112080    } break;
112081  }
112082  if( shouldFree ){
112083    sqlite3_free(pColData);
112084  }
112085  return SQLITE_OK;
112086}
112087
112088static int recoverRowid(sqlite3_vtab_cursor *pVtabCursor, sqlite_int64 *pRowid){
112089  RecoverCursor *pCursor = (RecoverCursor*)pVtabCursor;
112090  FNENTRY();
112091  *pRowid = leafCursorCellRowid(pCursor->pLeafCursor);
112092  return SQLITE_OK;
112093}
112094
112095static sqlite3_module recoverModule = {
112096  0,                         /* iVersion */
112097  recoverCreate,             /* xCreate - create a table */
112098  recoverConnect,            /* xConnect - connect to an existing table */
112099  recoverBestIndex,          /* xBestIndex - Determine search strategy */
112100  recoverDisconnect,         /* xDisconnect - Disconnect from a table */
112101  recoverDestroy,            /* xDestroy - Drop a table */
112102  recoverOpen,               /* xOpen - open a cursor */
112103  recoverClose,              /* xClose - close a cursor */
112104  recoverFilter,             /* xFilter - configure scan constraints */
112105  recoverNext,               /* xNext - advance a cursor */
112106  recoverEof,                /* xEof */
112107  recoverColumn,             /* xColumn - read data */
112108  recoverRowid,              /* xRowid - read data */
112109  0,                         /* xUpdate - write data */
112110  0,                         /* xBegin - begin transaction */
112111  0,                         /* xSync - sync transaction */
112112  0,                         /* xCommit - commit transaction */
112113  0,                         /* xRollback - rollback transaction */
112114  0,                         /* xFindFunction - function overloading */
112115  0,                         /* xRename - rename the table */
112116};
112117
112118int recoverVtableInit(sqlite3 *db){
112119  return sqlite3_create_module_v2(db, "recover", &recoverModule, NULL, 0);
112120}
112121
112122/* This section of code is for parsing the create input and
112123 * initializing the module.
112124 */
112125
112126/* Find the next word in zText and place the endpoints in pzWord*.
112127 * Returns true if the word is non-empty.  "Word" is defined as
112128 * ASCII alphanumeric plus '_' at this time.
112129 */
112130static int findWord(const char *zText,
112131                    const char **pzWordStart, const char **pzWordEnd){
112132  int r;
112133  while( ascii_isspace(*zText) ){
112134    zText++;
112135  }
112136  *pzWordStart = zText;
112137  while( ascii_isalnum(*zText) || *zText=='_' ){
112138    zText++;
112139  }
112140  r = zText>*pzWordStart;  /* In case pzWordStart==pzWordEnd */
112141  *pzWordEnd = zText;
112142  return r;
112143}
112144
112145/* Return true if the next word in zText is zWord, also setting
112146 * *pzContinue to the character after the word.
112147 */
112148static int expectWord(const char *zText, const char *zWord,
112149                      const char **pzContinue){
112150  const char *zWordStart, *zWordEnd;
112151  if( findWord(zText, &zWordStart, &zWordEnd) &&
112152      ascii_strncasecmp(zWord, zWordStart, zWordEnd - zWordStart)==0 ){
112153    *pzContinue = zWordEnd;
112154    return 1;
112155  }
112156  return 0;
112157}
112158
112159/* Parse the name and type information out of parameter.  In case of
112160 * success, *pzNameStart/End contain the name of the column,
112161 * *pzTypeStart/End contain the top-level type, and *pTypeMask has the
112162 * type mask to use for the column.
112163 */
112164static int findNameAndType(const char *parameter,
112165                           const char **pzNameStart, const char **pzNameEnd,
112166                           const char **pzTypeStart, const char **pzTypeEnd,
112167                           unsigned char *pTypeMask){
112168  unsigned nNameLen;   /* Length of found name. */
112169  const char *zEnd;    /* Current end of parsed column information. */
112170  int bNotNull;        /* Non-zero if NULL is not allowed for name. */
112171  int bStrict;         /* Non-zero if column requires exact type match. */
112172  const char *zDummy;  /* Dummy parameter, result unused. */
112173  unsigned i;
112174
112175  /* strictMask is used for STRICT, strictMask|otherMask if STRICT is
112176   * not supplied.  zReplace provides an alternate type to expose to
112177   * the caller.
112178   */
112179  static struct {
112180    const char *zName;
112181    unsigned char strictMask;
112182    unsigned char otherMask;
112183    const char *zReplace;
112184  } kTypeInfo[] = {
112185    { "ANY",
112186      MASK_INTEGER | MASK_FLOAT | MASK_BLOB | MASK_TEXT | MASK_NULL,
112187      0, "",
112188    },
112189    { "ROWID",   MASK_INTEGER | MASK_ROWID,             0, "INTEGER", },
112190    { "INTEGER", MASK_INTEGER | MASK_NULL,              0, NULL, },
112191    { "FLOAT",   MASK_FLOAT | MASK_NULL,                MASK_INTEGER, NULL, },
112192    { "NUMERIC", MASK_INTEGER | MASK_FLOAT | MASK_NULL, MASK_TEXT, NULL, },
112193    { "TEXT",    MASK_TEXT | MASK_NULL,                 MASK_BLOB, NULL, },
112194    { "BLOB",    MASK_BLOB | MASK_NULL,                 0, NULL, },
112195  };
112196
112197  if( !findWord(parameter, pzNameStart, pzNameEnd) ){
112198    return SQLITE_MISUSE;
112199  }
112200
112201  /* Manifest typing, accept any storage type. */
112202  if( !findWord(*pzNameEnd, pzTypeStart, pzTypeEnd) ){
112203    *pzTypeEnd = *pzTypeStart = "";
112204    *pTypeMask = MASK_INTEGER | MASK_FLOAT | MASK_BLOB | MASK_TEXT | MASK_NULL;
112205    return SQLITE_OK;
112206  }
112207
112208  nNameLen = *pzTypeEnd - *pzTypeStart;
112209  for( i=0; i<ArraySize(kTypeInfo); ++i ){
112210    if( ascii_strncasecmp(kTypeInfo[i].zName, *pzTypeStart, nNameLen)==0 ){
112211      break;
112212    }
112213  }
112214  if( i==ArraySize(kTypeInfo) ){
112215    return SQLITE_MISUSE;
112216  }
112217
112218  zEnd = *pzTypeEnd;
112219  bStrict = 0;
112220  if( expectWord(zEnd, "STRICT", &zEnd) ){
112221    /* TODO(shess): Ick.  But I don't want another single-purpose
112222     * flag, either.
112223     */
112224    if( kTypeInfo[i].zReplace && !kTypeInfo[i].zReplace[0] ){
112225      return SQLITE_MISUSE;
112226    }
112227    bStrict = 1;
112228  }
112229
112230  bNotNull = 0;
112231  if( expectWord(zEnd, "NOT", &zEnd) ){
112232    if( expectWord(zEnd, "NULL", &zEnd) ){
112233      bNotNull = 1;
112234    }else{
112235      /* Anything other than NULL after NOT is an error. */
112236      return SQLITE_MISUSE;
112237    }
112238  }
112239
112240  /* Anything else is an error. */
112241  if( findWord(zEnd, &zDummy, &zDummy) ){
112242    return SQLITE_MISUSE;
112243  }
112244
112245  *pTypeMask = kTypeInfo[i].strictMask;
112246  if( !bStrict ){
112247    *pTypeMask |= kTypeInfo[i].otherMask;
112248  }
112249  if( bNotNull ){
112250    *pTypeMask &= ~MASK_NULL;
112251  }
112252  if( kTypeInfo[i].zReplace ){
112253    *pzTypeStart = kTypeInfo[i].zReplace;
112254    *pzTypeEnd = *pzTypeStart + strlen(*pzTypeStart);
112255  }
112256  return SQLITE_OK;
112257}
112258
112259/* Parse the arguments, placing type masks in *pTypes and the exposed
112260 * schema in *pzCreateSql (for sqlite3_declare_vtab).
112261 */
112262static int ParseColumnsAndGenerateCreate(unsigned nCols,
112263                                         const char *const *pCols,
112264                                         char **pzCreateSql,
112265                                         unsigned char *pTypes,
112266                                         char **pzErr){
112267  unsigned i;
112268  char *zCreateSql = sqlite3_mprintf("CREATE TABLE x(");
112269  if( !zCreateSql ){
112270    return SQLITE_NOMEM;
112271  }
112272
112273  for( i=0; i<nCols; i++ ){
112274    const char *zSep = (i < nCols - 1 ? ", " : ")");
112275    const char *zNotNull = "";
112276    const char *zNameStart, *zNameEnd;
112277    const char *zTypeStart, *zTypeEnd;
112278    int rc = findNameAndType(pCols[i],
112279                             &zNameStart, &zNameEnd,
112280                             &zTypeStart, &zTypeEnd,
112281                             &pTypes[i]);
112282    if( rc!=SQLITE_OK ){
112283      *pzErr = sqlite3_mprintf("unable to parse column %d", i);
112284      sqlite3_free(zCreateSql);
112285      return rc;
112286    }
112287
112288    if( !(pTypes[i]&MASK_NULL) ){
112289      zNotNull = " NOT NULL";
112290    }
112291
112292    /* Add name and type to the create statement. */
112293    zCreateSql = sqlite3_mprintf("%z%.*s %.*s%s%s",
112294                                 zCreateSql,
112295                                 zNameEnd - zNameStart, zNameStart,
112296                                 zTypeEnd - zTypeStart, zTypeStart,
112297                                 zNotNull, zSep);
112298    if( !zCreateSql ){
112299      return SQLITE_NOMEM;
112300    }
112301  }
112302
112303  *pzCreateSql = zCreateSql;
112304  return SQLITE_OK;
112305}
112306
112307/* Helper function for initializing the module. */
112308/* argv[0] module name
112309 * argv[1] db name for virtual table
112310 * argv[2] virtual table name
112311 * argv[3] backing table name
112312 * argv[4] columns
112313 */
112314/* TODO(shess): Since connect isn't supported, could inline into
112315 * recoverCreate().
112316 */
112317/* TODO(shess): Explore cases where it would make sense to set *pzErr. */
112318static int recoverInit(
112319  sqlite3 *db,                        /* Database connection */
112320  void *pAux,                         /* unused */
112321  int argc, const char *const*argv,   /* Parameters to CREATE TABLE statement */
112322  sqlite3_vtab **ppVtab,              /* OUT: New virtual table */
112323  char **pzErr                        /* OUT: Error message, if any */
112324){
112325  const unsigned kTypeCol = 4;  /* First argument with column type info. */
112326  Recover *pRecover;            /* Virtual table structure being created. */
112327  char *zDot;                   /* Any dot found in "db.table" backing. */
112328  u32 iRootPage;                /* Root page of backing table. */
112329  char *zCreateSql;             /* Schema of created virtual table. */
112330  int rc;
112331
112332  /* Require to be in the temp database. */
112333  if( ascii_strcasecmp(argv[1], "temp")!=0 ){
112334    *pzErr = sqlite3_mprintf("recover table must be in temp database");
112335    return SQLITE_MISUSE;
112336  }
112337
112338  /* Need the backing table and at least one column. */
112339  if( argc<=kTypeCol ){
112340    *pzErr = sqlite3_mprintf("no columns specified");
112341    return SQLITE_MISUSE;
112342  }
112343
112344  pRecover = sqlite3_malloc(sizeof(Recover));
112345  if( !pRecover ){
112346    return SQLITE_NOMEM;
112347  }
112348  memset(pRecover, 0, sizeof(*pRecover));
112349  pRecover->base.pModule = &recoverModule;
112350  pRecover->db = db;
112351
112352  /* Parse out db.table, assuming main if no dot. */
112353  zDot = strchr(argv[3], '.');
112354  if( !zDot ){
112355    pRecover->zDb = sqlite3_strdup(db->aDb[0].zName);
112356    pRecover->zTable = sqlite3_strdup(argv[3]);
112357  }else if( zDot>argv[3] && zDot[1]!='\0' ){
112358    pRecover->zDb = sqlite3_strndup(argv[3], zDot - argv[3]);
112359    pRecover->zTable = sqlite3_strdup(zDot + 1);
112360  }else{
112361    /* ".table" or "db." not allowed. */
112362    *pzErr = sqlite3_mprintf("ill-formed table specifier");
112363    recoverRelease(pRecover);
112364    return SQLITE_ERROR;
112365  }
112366
112367  pRecover->nCols = argc - kTypeCol;
112368  pRecover->pTypes = sqlite3_malloc(pRecover->nCols);
112369  if( !pRecover->zDb || !pRecover->zTable || !pRecover->pTypes ){
112370    recoverRelease(pRecover);
112371    return SQLITE_NOMEM;
112372  }
112373
112374  /* Require the backing table to exist. */
112375  /* TODO(shess): Be more pedantic about the form of the descriptor
112376   * string.  This already fails for poorly-formed strings, simply
112377   * because there won't be a root page, but it would make more sense
112378   * to be explicit.
112379   */
112380  rc = getRootPage(pRecover->db, pRecover->zDb, pRecover->zTable, &iRootPage);
112381  if( rc!=SQLITE_OK ){
112382    *pzErr = sqlite3_mprintf("unable to find backing table");
112383    recoverRelease(pRecover);
112384    return rc;
112385  }
112386
112387  /* Parse the column definitions. */
112388  rc = ParseColumnsAndGenerateCreate(pRecover->nCols, argv + kTypeCol,
112389                                     &zCreateSql, pRecover->pTypes, pzErr);
112390  if( rc!=SQLITE_OK ){
112391    recoverRelease(pRecover);
112392    return rc;
112393  }
112394
112395  rc = sqlite3_declare_vtab(db, zCreateSql);
112396  sqlite3_free(zCreateSql);
112397  if( rc!=SQLITE_OK ){
112398    recoverRelease(pRecover);
112399    return rc;
112400  }
112401
112402  *ppVtab = (sqlite3_vtab *)pRecover;
112403  return SQLITE_OK;
112404}
112405
112406/************** End of recover.c *********************************************/
112407/************** Begin file fts3.c ********************************************/
112408/*
112409** 2006 Oct 10
112410**
112411** The author disclaims copyright to this source code.  In place of
112412** a legal notice, here is a blessing:
112413**
112414**    May you do good and not evil.
112415**    May you find forgiveness for yourself and forgive others.
112416**    May you share freely, never taking more than you give.
112417**
112418******************************************************************************
112419**
112420** This is an SQLite module implementing full-text search.
112421*/
112422
112423/*
112424** The code in this file is only compiled if:
112425**
112426**     * The FTS3 module is being built as an extension
112427**       (in which case SQLITE_CORE is not defined), or
112428**
112429**     * The FTS3 module is being built into the core of
112430**       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
112431*/
112432
112433/* The full-text index is stored in a series of b+tree (-like)
112434** structures called segments which map terms to doclists.  The
112435** structures are like b+trees in layout, but are constructed from the
112436** bottom up in optimal fashion and are not updatable.  Since trees
112437** are built from the bottom up, things will be described from the
112438** bottom up.
112439**
112440**
112441**** Varints ****
112442** The basic unit of encoding is a variable-length integer called a
112443** varint.  We encode variable-length integers in little-endian order
112444** using seven bits * per byte as follows:
112445**
112446** KEY:
112447**         A = 0xxxxxxx    7 bits of data and one flag bit
112448**         B = 1xxxxxxx    7 bits of data and one flag bit
112449**
112450**  7 bits - A
112451** 14 bits - BA
112452** 21 bits - BBA
112453** and so on.
112454**
112455** This is similar in concept to how sqlite encodes "varints" but
112456** the encoding is not the same.  SQLite varints are big-endian
112457** are are limited to 9 bytes in length whereas FTS3 varints are
112458** little-endian and can be up to 10 bytes in length (in theory).
112459**
112460** Example encodings:
112461**
112462**     1:    0x01
112463**   127:    0x7f
112464**   128:    0x81 0x00
112465**
112466**
112467**** Document lists ****
112468** A doclist (document list) holds a docid-sorted list of hits for a
112469** given term.  Doclists hold docids and associated token positions.
112470** A docid is the unique integer identifier for a single document.
112471** A position is the index of a word within the document.  The first
112472** word of the document has a position of 0.
112473**
112474** FTS3 used to optionally store character offsets using a compile-time
112475** option.  But that functionality is no longer supported.
112476**
112477** A doclist is stored like this:
112478**
112479** array {
112480**   varint docid;
112481**   array {                (position list for column 0)
112482**     varint position;     (2 more than the delta from previous position)
112483**   }
112484**   array {
112485**     varint POS_COLUMN;   (marks start of position list for new column)
112486**     varint column;       (index of new column)
112487**     array {
112488**       varint position;   (2 more than the delta from previous position)
112489**     }
112490**   }
112491**   varint POS_END;        (marks end of positions for this document.
112492** }
112493**
112494** Here, array { X } means zero or more occurrences of X, adjacent in
112495** memory.  A "position" is an index of a token in the token stream
112496** generated by the tokenizer. Note that POS_END and POS_COLUMN occur
112497** in the same logical place as the position element, and act as sentinals
112498** ending a position list array.  POS_END is 0.  POS_COLUMN is 1.
112499** The positions numbers are not stored literally but rather as two more
112500** than the difference from the prior position, or the just the position plus
112501** 2 for the first position.  Example:
112502**
112503**   label:       A B C D E  F  G H   I  J K
112504**   value:     123 5 9 1 1 14 35 0 234 72 0
112505**
112506** The 123 value is the first docid.  For column zero in this document
112507** there are two matches at positions 3 and 10 (5-2 and 9-2+3).  The 1
112508** at D signals the start of a new column; the 1 at E indicates that the
112509** new column is column number 1.  There are two positions at 12 and 45
112510** (14-2 and 35-2+12).  The 0 at H indicate the end-of-document.  The
112511** 234 at I is the next docid.  It has one position 72 (72-2) and then
112512** terminates with the 0 at K.
112513**
112514** A "position-list" is the list of positions for multiple columns for
112515** a single docid.  A "column-list" is the set of positions for a single
112516** column.  Hence, a position-list consists of one or more column-lists,
112517** a document record consists of a docid followed by a position-list and
112518** a doclist consists of one or more document records.
112519**
112520** A bare doclist omits the position information, becoming an
112521** array of varint-encoded docids.
112522**
112523**** Segment leaf nodes ****
112524** Segment leaf nodes store terms and doclists, ordered by term.  Leaf
112525** nodes are written using LeafWriter, and read using LeafReader (to
112526** iterate through a single leaf node's data) and LeavesReader (to
112527** iterate through a segment's entire leaf layer).  Leaf nodes have
112528** the format:
112529**
112530** varint iHeight;             (height from leaf level, always 0)
112531** varint nTerm;               (length of first term)
112532** char pTerm[nTerm];          (content of first term)
112533** varint nDoclist;            (length of term's associated doclist)
112534** char pDoclist[nDoclist];    (content of doclist)
112535** array {
112536**                             (further terms are delta-encoded)
112537**   varint nPrefix;           (length of prefix shared with previous term)
112538**   varint nSuffix;           (length of unshared suffix)
112539**   char pTermSuffix[nSuffix];(unshared suffix of next term)
112540**   varint nDoclist;          (length of term's associated doclist)
112541**   char pDoclist[nDoclist];  (content of doclist)
112542** }
112543**
112544** Here, array { X } means zero or more occurrences of X, adjacent in
112545** memory.
112546**
112547** Leaf nodes are broken into blocks which are stored contiguously in
112548** the %_segments table in sorted order.  This means that when the end
112549** of a node is reached, the next term is in the node with the next
112550** greater node id.
112551**
112552** New data is spilled to a new leaf node when the current node
112553** exceeds LEAF_MAX bytes (default 2048).  New data which itself is
112554** larger than STANDALONE_MIN (default 1024) is placed in a standalone
112555** node (a leaf node with a single term and doclist).  The goal of
112556** these settings is to pack together groups of small doclists while
112557** making it efficient to directly access large doclists.  The
112558** assumption is that large doclists represent terms which are more
112559** likely to be query targets.
112560**
112561** TODO(shess) It may be useful for blocking decisions to be more
112562** dynamic.  For instance, it may make more sense to have a 2.5k leaf
112563** node rather than splitting into 2k and .5k nodes.  My intuition is
112564** that this might extend through 2x or 4x the pagesize.
112565**
112566**
112567**** Segment interior nodes ****
112568** Segment interior nodes store blockids for subtree nodes and terms
112569** to describe what data is stored by the each subtree.  Interior
112570** nodes are written using InteriorWriter, and read using
112571** InteriorReader.  InteriorWriters are created as needed when
112572** SegmentWriter creates new leaf nodes, or when an interior node
112573** itself grows too big and must be split.  The format of interior
112574** nodes:
112575**
112576** varint iHeight;           (height from leaf level, always >0)
112577** varint iBlockid;          (block id of node's leftmost subtree)
112578** optional {
112579**   varint nTerm;           (length of first term)
112580**   char pTerm[nTerm];      (content of first term)
112581**   array {
112582**                                (further terms are delta-encoded)
112583**     varint nPrefix;            (length of shared prefix with previous term)
112584**     varint nSuffix;            (length of unshared suffix)
112585**     char pTermSuffix[nSuffix]; (unshared suffix of next term)
112586**   }
112587** }
112588**
112589** Here, optional { X } means an optional element, while array { X }
112590** means zero or more occurrences of X, adjacent in memory.
112591**
112592** An interior node encodes n terms separating n+1 subtrees.  The
112593** subtree blocks are contiguous, so only the first subtree's blockid
112594** is encoded.  The subtree at iBlockid will contain all terms less
112595** than the first term encoded (or all terms if no term is encoded).
112596** Otherwise, for terms greater than or equal to pTerm[i] but less
112597** than pTerm[i+1], the subtree for that term will be rooted at
112598** iBlockid+i.  Interior nodes only store enough term data to
112599** distinguish adjacent children (if the rightmost term of the left
112600** child is "something", and the leftmost term of the right child is
112601** "wicked", only "w" is stored).
112602**
112603** New data is spilled to a new interior node at the same height when
112604** the current node exceeds INTERIOR_MAX bytes (default 2048).
112605** INTERIOR_MIN_TERMS (default 7) keeps large terms from monopolizing
112606** interior nodes and making the tree too skinny.  The interior nodes
112607** at a given height are naturally tracked by interior nodes at
112608** height+1, and so on.
112609**
112610**
112611**** Segment directory ****
112612** The segment directory in table %_segdir stores meta-information for
112613** merging and deleting segments, and also the root node of the
112614** segment's tree.
112615**
112616** The root node is the top node of the segment's tree after encoding
112617** the entire segment, restricted to ROOT_MAX bytes (default 1024).
112618** This could be either a leaf node or an interior node.  If the top
112619** node requires more than ROOT_MAX bytes, it is flushed to %_segments
112620** and a new root interior node is generated (which should always fit
112621** within ROOT_MAX because it only needs space for 2 varints, the
112622** height and the blockid of the previous root).
112623**
112624** The meta-information in the segment directory is:
112625**   level               - segment level (see below)
112626**   idx                 - index within level
112627**                       - (level,idx uniquely identify a segment)
112628**   start_block         - first leaf node
112629**   leaves_end_block    - last leaf node
112630**   end_block           - last block (including interior nodes)
112631**   root                - contents of root node
112632**
112633** If the root node is a leaf node, then start_block,
112634** leaves_end_block, and end_block are all 0.
112635**
112636**
112637**** Segment merging ****
112638** To amortize update costs, segments are grouped into levels and
112639** merged in batches.  Each increase in level represents exponentially
112640** more documents.
112641**
112642** New documents (actually, document updates) are tokenized and
112643** written individually (using LeafWriter) to a level 0 segment, with
112644** incrementing idx.  When idx reaches MERGE_COUNT (default 16), all
112645** level 0 segments are merged into a single level 1 segment.  Level 1
112646** is populated like level 0, and eventually MERGE_COUNT level 1
112647** segments are merged to a single level 2 segment (representing
112648** MERGE_COUNT^2 updates), and so on.
112649**
112650** A segment merge traverses all segments at a given level in
112651** parallel, performing a straightforward sorted merge.  Since segment
112652** leaf nodes are written in to the %_segments table in order, this
112653** merge traverses the underlying sqlite disk structures efficiently.
112654** After the merge, all segment blocks from the merged level are
112655** deleted.
112656**
112657** MERGE_COUNT controls how often we merge segments.  16 seems to be
112658** somewhat of a sweet spot for insertion performance.  32 and 64 show
112659** very similar performance numbers to 16 on insertion, though they're
112660** a tiny bit slower (perhaps due to more overhead in merge-time
112661** sorting).  8 is about 20% slower than 16, 4 about 50% slower than
112662** 16, 2 about 66% slower than 16.
112663**
112664** At query time, high MERGE_COUNT increases the number of segments
112665** which need to be scanned and merged.  For instance, with 100k docs
112666** inserted:
112667**
112668**    MERGE_COUNT   segments
112669**       16           25
112670**        8           12
112671**        4           10
112672**        2            6
112673**
112674** This appears to have only a moderate impact on queries for very
112675** frequent terms (which are somewhat dominated by segment merge
112676** costs), and infrequent and non-existent terms still seem to be fast
112677** even with many segments.
112678**
112679** TODO(shess) That said, it would be nice to have a better query-side
112680** argument for MERGE_COUNT of 16.  Also, it is possible/likely that
112681** optimizations to things like doclist merging will swing the sweet
112682** spot around.
112683**
112684**
112685**
112686**** Handling of deletions and updates ****
112687** Since we're using a segmented structure, with no docid-oriented
112688** index into the term index, we clearly cannot simply update the term
112689** index when a document is deleted or updated.  For deletions, we
112690** write an empty doclist (varint(docid) varint(POS_END)), for updates
112691** we simply write the new doclist.  Segment merges overwrite older
112692** data for a particular docid with newer data, so deletes or updates
112693** will eventually overtake the earlier data and knock it out.  The
112694** query logic likewise merges doclists so that newer data knocks out
112695** older data.
112696**
112697** TODO(shess) Provide a VACUUM type operation to clear out all
112698** deletions and duplications.  This would basically be a forced merge
112699** into a single segment.
112700*/
112701#define CHROMIUM_FTS3_CHANGES 1
112702
112703#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
112704
112705#if defined(SQLITE_ENABLE_FTS3) && !defined(SQLITE_CORE)
112706# define SQLITE_CORE 1
112707#endif
112708
112709/************** Include fts3Int.h in the middle of fts3.c ********************/
112710/************** Begin file fts3Int.h *****************************************/
112711/*
112712** 2009 Nov 12
112713**
112714** The author disclaims copyright to this source code.  In place of
112715** a legal notice, here is a blessing:
112716**
112717**    May you do good and not evil.
112718**    May you find forgiveness for yourself and forgive others.
112719**    May you share freely, never taking more than you give.
112720**
112721******************************************************************************
112722**
112723*/
112724
112725#ifndef _FTSINT_H
112726#define _FTSINT_H
112727
112728#if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
112729# define NDEBUG 1
112730#endif
112731
112732/************** Include fts3_tokenizer.h in the middle of fts3Int.h **********/
112733/************** Begin file fts3_tokenizer.h **********************************/
112734/*
112735** 2006 July 10
112736**
112737** The author disclaims copyright to this source code.
112738**
112739*************************************************************************
112740** Defines the interface to tokenizers used by fulltext-search.  There
112741** are three basic components:
112742**
112743** sqlite3_tokenizer_module is a singleton defining the tokenizer
112744** interface functions.  This is essentially the class structure for
112745** tokenizers.
112746**
112747** sqlite3_tokenizer is used to define a particular tokenizer, perhaps
112748** including customization information defined at creation time.
112749**
112750** sqlite3_tokenizer_cursor is generated by a tokenizer to generate
112751** tokens from a particular input.
112752*/
112753#ifndef _FTS3_TOKENIZER_H_
112754#define _FTS3_TOKENIZER_H_
112755
112756/* TODO(shess) Only used for SQLITE_OK and SQLITE_DONE at this time.
112757** If tokenizers are to be allowed to call sqlite3_*() functions, then
112758** we will need a way to register the API consistently.
112759*/
112760
112761/*
112762** Structures used by the tokenizer interface. When a new tokenizer
112763** implementation is registered, the caller provides a pointer to
112764** an sqlite3_tokenizer_module containing pointers to the callback
112765** functions that make up an implementation.
112766**
112767** When an fts3 table is created, it passes any arguments passed to
112768** the tokenizer clause of the CREATE VIRTUAL TABLE statement to the
112769** sqlite3_tokenizer_module.xCreate() function of the requested tokenizer
112770** implementation. The xCreate() function in turn returns an
112771** sqlite3_tokenizer structure representing the specific tokenizer to
112772** be used for the fts3 table (customized by the tokenizer clause arguments).
112773**
112774** To tokenize an input buffer, the sqlite3_tokenizer_module.xOpen()
112775** method is called. It returns an sqlite3_tokenizer_cursor object
112776** that may be used to tokenize a specific input buffer based on
112777** the tokenization rules supplied by a specific sqlite3_tokenizer
112778** object.
112779*/
112780typedef struct sqlite3_tokenizer_module sqlite3_tokenizer_module;
112781typedef struct sqlite3_tokenizer sqlite3_tokenizer;
112782typedef struct sqlite3_tokenizer_cursor sqlite3_tokenizer_cursor;
112783
112784struct sqlite3_tokenizer_module {
112785
112786  /*
112787  ** Structure version. Should always be set to 0.
112788  */
112789  int iVersion;
112790
112791  /*
112792  ** Create a new tokenizer. The values in the argv[] array are the
112793  ** arguments passed to the "tokenizer" clause of the CREATE VIRTUAL
112794  ** TABLE statement that created the fts3 table. For example, if
112795  ** the following SQL is executed:
112796  **
112797  **   CREATE .. USING fts3( ... , tokenizer <tokenizer-name> arg1 arg2)
112798  **
112799  ** then argc is set to 2, and the argv[] array contains pointers
112800  ** to the strings "arg1" and "arg2".
112801  **
112802  ** This method should return either SQLITE_OK (0), or an SQLite error
112803  ** code. If SQLITE_OK is returned, then *ppTokenizer should be set
112804  ** to point at the newly created tokenizer structure. The generic
112805  ** sqlite3_tokenizer.pModule variable should not be initialised by
112806  ** this callback. The caller will do so.
112807  */
112808  int (*xCreate)(
112809    int argc,                           /* Size of argv array */
112810    const char *const*argv,             /* Tokenizer argument strings */
112811    sqlite3_tokenizer **ppTokenizer     /* OUT: Created tokenizer */
112812  );
112813
112814  /*
112815  ** Destroy an existing tokenizer. The fts3 module calls this method
112816  ** exactly once for each successful call to xCreate().
112817  */
112818  int (*xDestroy)(sqlite3_tokenizer *pTokenizer);
112819
112820  /*
112821  ** Create a tokenizer cursor to tokenize an input buffer. The caller
112822  ** is responsible for ensuring that the input buffer remains valid
112823  ** until the cursor is closed (using the xClose() method).
112824  */
112825  int (*xOpen)(
112826    sqlite3_tokenizer *pTokenizer,       /* Tokenizer object */
112827    const char *pInput, int nBytes,      /* Input buffer */
112828    sqlite3_tokenizer_cursor **ppCursor  /* OUT: Created tokenizer cursor */
112829  );
112830
112831  /*
112832  ** Destroy an existing tokenizer cursor. The fts3 module calls this
112833  ** method exactly once for each successful call to xOpen().
112834  */
112835  int (*xClose)(sqlite3_tokenizer_cursor *pCursor);
112836
112837  /*
112838  ** Retrieve the next token from the tokenizer cursor pCursor. This
112839  ** method should either return SQLITE_OK and set the values of the
112840  ** "OUT" variables identified below, or SQLITE_DONE to indicate that
112841  ** the end of the buffer has been reached, or an SQLite error code.
112842  **
112843  ** *ppToken should be set to point at a buffer containing the
112844  ** normalized version of the token (i.e. after any case-folding and/or
112845  ** stemming has been performed). *pnBytes should be set to the length
112846  ** of this buffer in bytes. The input text that generated the token is
112847  ** identified by the byte offsets returned in *piStartOffset and
112848  ** *piEndOffset. *piStartOffset should be set to the index of the first
112849  ** byte of the token in the input buffer. *piEndOffset should be set
112850  ** to the index of the first byte just past the end of the token in
112851  ** the input buffer.
112852  **
112853  ** The buffer *ppToken is set to point at is managed by the tokenizer
112854  ** implementation. It is only required to be valid until the next call
112855  ** to xNext() or xClose().
112856  */
112857  /* TODO(shess) current implementation requires pInput to be
112858  ** nul-terminated.  This should either be fixed, or pInput/nBytes
112859  ** should be converted to zInput.
112860  */
112861  int (*xNext)(
112862    sqlite3_tokenizer_cursor *pCursor,   /* Tokenizer cursor */
112863    const char **ppToken, int *pnBytes,  /* OUT: Normalized text for token */
112864    int *piStartOffset,  /* OUT: Byte offset of token in input buffer */
112865    int *piEndOffset,    /* OUT: Byte offset of end of token in input buffer */
112866    int *piPosition      /* OUT: Number of tokens returned before this one */
112867  );
112868};
112869
112870struct sqlite3_tokenizer {
112871  const sqlite3_tokenizer_module *pModule;  /* The module for this tokenizer */
112872  /* Tokenizer implementations will typically add additional fields */
112873};
112874
112875struct sqlite3_tokenizer_cursor {
112876  sqlite3_tokenizer *pTokenizer;       /* Tokenizer for this cursor. */
112877  /* Tokenizer implementations will typically add additional fields */
112878};
112879
112880int fts3_global_term_cnt(int iTerm, int iCol);
112881int fts3_term_cnt(int iTerm, int iCol);
112882
112883
112884#endif /* _FTS3_TOKENIZER_H_ */
112885
112886/************** End of fts3_tokenizer.h **************************************/
112887/************** Continuing where we left off in fts3Int.h ********************/
112888/************** Include fts3_hash.h in the middle of fts3Int.h ***************/
112889/************** Begin file fts3_hash.h ***************************************/
112890/*
112891** 2001 September 22
112892**
112893** The author disclaims copyright to this source code.  In place of
112894** a legal notice, here is a blessing:
112895**
112896**    May you do good and not evil.
112897**    May you find forgiveness for yourself and forgive others.
112898**    May you share freely, never taking more than you give.
112899**
112900*************************************************************************
112901** This is the header file for the generic hash-table implemenation
112902** used in SQLite.  We've modified it slightly to serve as a standalone
112903** hash table implementation for the full-text indexing module.
112904**
112905*/
112906#ifndef _FTS3_HASH_H_
112907#define _FTS3_HASH_H_
112908
112909/* Forward declarations of structures. */
112910typedef struct Fts3Hash Fts3Hash;
112911typedef struct Fts3HashElem Fts3HashElem;
112912
112913/* A complete hash table is an instance of the following structure.
112914** The internals of this structure are intended to be opaque -- client
112915** code should not attempt to access or modify the fields of this structure
112916** directly.  Change this structure only by using the routines below.
112917** However, many of the "procedures" and "functions" for modifying and
112918** accessing this structure are really macros, so we can't really make
112919** this structure opaque.
112920*/
112921struct Fts3Hash {
112922  char keyClass;          /* HASH_INT, _POINTER, _STRING, _BINARY */
112923  char copyKey;           /* True if copy of key made on insert */
112924  int count;              /* Number of entries in this table */
112925  Fts3HashElem *first;    /* The first element of the array */
112926  int htsize;             /* Number of buckets in the hash table */
112927  struct _fts3ht {        /* the hash table */
112928    int count;               /* Number of entries with this hash */
112929    Fts3HashElem *chain;     /* Pointer to first entry with this hash */
112930  } *ht;
112931};
112932
112933/* Each element in the hash table is an instance of the following
112934** structure.  All elements are stored on a single doubly-linked list.
112935**
112936** Again, this structure is intended to be opaque, but it can't really
112937** be opaque because it is used by macros.
112938*/
112939struct Fts3HashElem {
112940  Fts3HashElem *next, *prev; /* Next and previous elements in the table */
112941  void *data;                /* Data associated with this element */
112942  void *pKey; int nKey;      /* Key associated with this element */
112943};
112944
112945/*
112946** There are 2 different modes of operation for a hash table:
112947**
112948**   FTS3_HASH_STRING        pKey points to a string that is nKey bytes long
112949**                           (including the null-terminator, if any).  Case
112950**                           is respected in comparisons.
112951**
112952**   FTS3_HASH_BINARY        pKey points to binary data nKey bytes long.
112953**                           memcmp() is used to compare keys.
112954**
112955** A copy of the key is made if the copyKey parameter to fts3HashInit is 1.
112956*/
112957#define FTS3_HASH_STRING    1
112958#define FTS3_HASH_BINARY    2
112959
112960/*
112961** Access routines.  To delete, insert a NULL pointer.
112962*/
112963SQLITE_PRIVATE void sqlite3Fts3HashInit(Fts3Hash *pNew, char keyClass, char copyKey);
112964SQLITE_PRIVATE void *sqlite3Fts3HashInsert(Fts3Hash*, const void *pKey, int nKey, void *pData);
112965SQLITE_PRIVATE void *sqlite3Fts3HashFind(const Fts3Hash*, const void *pKey, int nKey);
112966SQLITE_PRIVATE void sqlite3Fts3HashClear(Fts3Hash*);
112967SQLITE_PRIVATE Fts3HashElem *sqlite3Fts3HashFindElem(const Fts3Hash *, const void *, int);
112968
112969/*
112970** Shorthand for the functions above
112971*/
112972#define fts3HashInit     sqlite3Fts3HashInit
112973#define fts3HashInsert   sqlite3Fts3HashInsert
112974#define fts3HashFind     sqlite3Fts3HashFind
112975#define fts3HashClear    sqlite3Fts3HashClear
112976#define fts3HashFindElem sqlite3Fts3HashFindElem
112977
112978/*
112979** Macros for looping over all elements of a hash table.  The idiom is
112980** like this:
112981**
112982**   Fts3Hash h;
112983**   Fts3HashElem *p;
112984**   ...
112985**   for(p=fts3HashFirst(&h); p; p=fts3HashNext(p)){
112986**     SomeStructure *pData = fts3HashData(p);
112987**     // do something with pData
112988**   }
112989*/
112990#define fts3HashFirst(H)  ((H)->first)
112991#define fts3HashNext(E)   ((E)->next)
112992#define fts3HashData(E)   ((E)->data)
112993#define fts3HashKey(E)    ((E)->pKey)
112994#define fts3HashKeysize(E) ((E)->nKey)
112995
112996/*
112997** Number of entries in a hash table
112998*/
112999#define fts3HashCount(H)  ((H)->count)
113000
113001#endif /* _FTS3_HASH_H_ */
113002
113003/************** End of fts3_hash.h *******************************************/
113004/************** Continuing where we left off in fts3Int.h ********************/
113005
113006/*
113007** This constant controls how often segments are merged. Once there are
113008** FTS3_MERGE_COUNT segments of level N, they are merged into a single
113009** segment of level N+1.
113010*/
113011#define FTS3_MERGE_COUNT 16
113012
113013/*
113014** This is the maximum amount of data (in bytes) to store in the
113015** Fts3Table.pendingTerms hash table. Normally, the hash table is
113016** populated as documents are inserted/updated/deleted in a transaction
113017** and used to create a new segment when the transaction is committed.
113018** However if this limit is reached midway through a transaction, a new
113019** segment is created and the hash table cleared immediately.
113020*/
113021#define FTS3_MAX_PENDING_DATA (1*1024*1024)
113022
113023/*
113024** Macro to return the number of elements in an array. SQLite has a
113025** similar macro called ArraySize(). Use a different name to avoid
113026** a collision when building an amalgamation with built-in FTS3.
113027*/
113028#define SizeofArray(X) ((int)(sizeof(X)/sizeof(X[0])))
113029
113030/*
113031** Maximum length of a varint encoded integer. The varint format is different
113032** from that used by SQLite, so the maximum length is 10, not 9.
113033*/
113034#define FTS3_VARINT_MAX 10
113035
113036/*
113037** The testcase() macro is only used by the amalgamation.  If undefined,
113038** make it a no-op.
113039*/
113040#ifndef testcase
113041# define testcase(X)
113042#endif
113043
113044/*
113045** Terminator values for position-lists and column-lists.
113046*/
113047#define POS_COLUMN  (1)     /* Column-list terminator */
113048#define POS_END     (0)     /* Position-list terminator */
113049
113050/*
113051** This section provides definitions to allow the
113052** FTS3 extension to be compiled outside of the
113053** amalgamation.
113054*/
113055#ifndef SQLITE_AMALGAMATION
113056/*
113057** Macros indicating that conditional expressions are always true or
113058** false.
113059*/
113060#ifdef SQLITE_COVERAGE_TEST
113061# define ALWAYS(x) (1)
113062# define NEVER(X)  (0)
113063#else
113064# define ALWAYS(x) (x)
113065# define NEVER(X)  (x)
113066#endif
113067
113068/*
113069** Internal types used by SQLite.
113070*/
113071typedef unsigned char u8;         /* 1-byte (or larger) unsigned integer */
113072typedef short int i16;            /* 2-byte (or larger) signed integer */
113073typedef unsigned int u32;         /* 4-byte unsigned integer */
113074typedef sqlite3_uint64 u64;       /* 8-byte unsigned integer */
113075/*
113076** Macro used to suppress compiler warnings for unused parameters.
113077*/
113078#define UNUSED_PARAMETER(x) (void)(x)
113079#endif
113080
113081typedef struct Fts3Table Fts3Table;
113082typedef struct Fts3Cursor Fts3Cursor;
113083typedef struct Fts3Expr Fts3Expr;
113084typedef struct Fts3Phrase Fts3Phrase;
113085typedef struct Fts3PhraseToken Fts3PhraseToken;
113086
113087typedef struct Fts3SegFilter Fts3SegFilter;
113088typedef struct Fts3DeferredToken Fts3DeferredToken;
113089typedef struct Fts3SegReader Fts3SegReader;
113090typedef struct Fts3SegReaderCursor Fts3SegReaderCursor;
113091
113092/*
113093** A connection to a fulltext index is an instance of the following
113094** structure. The xCreate and xConnect methods create an instance
113095** of this structure and xDestroy and xDisconnect free that instance.
113096** All other methods receive a pointer to the structure as one of their
113097** arguments.
113098*/
113099struct Fts3Table {
113100  sqlite3_vtab base;              /* Base class used by SQLite core */
113101  sqlite3 *db;                    /* The database connection */
113102  const char *zDb;                /* logical database name */
113103  const char *zName;              /* virtual table name */
113104  int nColumn;                    /* number of named columns in virtual table */
113105  char **azColumn;                /* column names.  malloced */
113106  sqlite3_tokenizer *pTokenizer;  /* tokenizer for inserts and queries */
113107
113108  /* Precompiled statements used by the implementation. Each of these
113109  ** statements is run and reset within a single virtual table API call.
113110  */
113111  sqlite3_stmt *aStmt[24];
113112
113113  char *zReadExprlist;
113114  char *zWriteExprlist;
113115
113116  int nNodeSize;                  /* Soft limit for node size */
113117  u8 bHasStat;                    /* True if %_stat table exists */
113118  u8 bHasDocsize;                 /* True if %_docsize table exists */
113119  int nPgsz;                      /* Page size for host database */
113120  char *zSegmentsTbl;             /* Name of %_segments table */
113121  sqlite3_blob *pSegments;        /* Blob handle open on %_segments table */
113122
113123  /* The following hash table is used to buffer pending index updates during
113124  ** transactions. Variable nPendingData estimates the memory size of the
113125  ** pending data, including hash table overhead, but not malloc overhead.
113126  ** When nPendingData exceeds nMaxPendingData, the buffer is flushed
113127  ** automatically. Variable iPrevDocid is the docid of the most recently
113128  ** inserted record.
113129  */
113130  int nMaxPendingData;
113131  int nPendingData;
113132  sqlite_int64 iPrevDocid;
113133  Fts3Hash pendingTerms;
113134};
113135
113136/*
113137** When the core wants to read from the virtual table, it creates a
113138** virtual table cursor (an instance of the following structure) using
113139** the xOpen method. Cursors are destroyed using the xClose method.
113140*/
113141struct Fts3Cursor {
113142  sqlite3_vtab_cursor base;       /* Base class used by SQLite core */
113143  i16 eSearch;                    /* Search strategy (see below) */
113144  u8 isEof;                       /* True if at End Of Results */
113145  u8 isRequireSeek;               /* True if must seek pStmt to %_content row */
113146  sqlite3_stmt *pStmt;            /* Prepared statement in use by the cursor */
113147  Fts3Expr *pExpr;                /* Parsed MATCH query string */
113148  int nPhrase;                    /* Number of matchable phrases in query */
113149  Fts3DeferredToken *pDeferred;   /* Deferred search tokens, if any */
113150  sqlite3_int64 iPrevId;          /* Previous id read from aDoclist */
113151  char *pNextId;                  /* Pointer into the body of aDoclist */
113152  char *aDoclist;                 /* List of docids for full-text queries */
113153  int nDoclist;                   /* Size of buffer at aDoclist */
113154  int eEvalmode;                  /* An FTS3_EVAL_XX constant */
113155  int nRowAvg;                    /* Average size of database rows, in pages */
113156
113157  int isMatchinfoNeeded;          /* True when aMatchinfo[] needs filling in */
113158  u32 *aMatchinfo;                /* Information about most recent match */
113159  int nMatchinfo;                 /* Number of elements in aMatchinfo[] */
113160  char *zMatchinfo;               /* Matchinfo specification */
113161};
113162
113163#define FTS3_EVAL_FILTER    0
113164#define FTS3_EVAL_NEXT      1
113165#define FTS3_EVAL_MATCHINFO 2
113166
113167/*
113168** The Fts3Cursor.eSearch member is always set to one of the following.
113169** Actualy, Fts3Cursor.eSearch can be greater than or equal to
113170** FTS3_FULLTEXT_SEARCH.  If so, then Fts3Cursor.eSearch - 2 is the index
113171** of the column to be searched.  For example, in
113172**
113173**     CREATE VIRTUAL TABLE ex1 USING fts3(a,b,c,d);
113174**     SELECT docid FROM ex1 WHERE b MATCH 'one two three';
113175**
113176** Because the LHS of the MATCH operator is 2nd column "b",
113177** Fts3Cursor.eSearch will be set to FTS3_FULLTEXT_SEARCH+1.  (+0 for a,
113178** +1 for b, +2 for c, +3 for d.)  If the LHS of MATCH were "ex1"
113179** indicating that all columns should be searched,
113180** then eSearch would be set to FTS3_FULLTEXT_SEARCH+4.
113181*/
113182#define FTS3_FULLSCAN_SEARCH 0    /* Linear scan of %_content table */
113183#define FTS3_DOCID_SEARCH    1    /* Lookup by rowid on %_content table */
113184#define FTS3_FULLTEXT_SEARCH 2    /* Full-text index search */
113185
113186/*
113187** A "phrase" is a sequence of one or more tokens that must match in
113188** sequence.  A single token is the base case and the most common case.
113189** For a sequence of tokens contained in double-quotes (i.e. "one two three")
113190** nToken will be the number of tokens in the string.
113191**
113192** The nDocMatch and nMatch variables contain data that may be used by the
113193** matchinfo() function. They are populated when the full-text index is
113194** queried for hits on the phrase. If one or more tokens in the phrase
113195** are deferred, the nDocMatch and nMatch variables are populated based
113196** on the assumption that the
113197*/
113198struct Fts3PhraseToken {
113199  char *z;                        /* Text of the token */
113200  int n;                          /* Number of bytes in buffer z */
113201  int isPrefix;                   /* True if token ends with a "*" character */
113202  int bFulltext;                  /* True if full-text index was used */
113203  Fts3SegReaderCursor *pSegcsr;   /* Segment-reader for this token */
113204  Fts3DeferredToken *pDeferred;   /* Deferred token object for this token */
113205};
113206
113207struct Fts3Phrase {
113208  /* Variables populated by fts3_expr.c when parsing a MATCH expression */
113209  int nToken;                /* Number of tokens in the phrase */
113210  int iColumn;               /* Index of column this phrase must match */
113211  int isNot;                 /* Phrase prefixed by unary not (-) operator */
113212  Fts3PhraseToken aToken[1]; /* One entry for each token in the phrase */
113213};
113214
113215/*
113216** A tree of these objects forms the RHS of a MATCH operator.
113217**
113218** If Fts3Expr.eType is either FTSQUERY_NEAR or FTSQUERY_PHRASE and isLoaded
113219** is true, then aDoclist points to a malloced buffer, size nDoclist bytes,
113220** containing the results of the NEAR or phrase query in FTS3 doclist
113221** format. As usual, the initial "Length" field found in doclists stored
113222** on disk is omitted from this buffer.
113223**
113224** Variable pCurrent always points to the start of a docid field within
113225** aDoclist. Since the doclist is usually scanned in docid order, this can
113226** be used to accelerate seeking to the required docid within the doclist.
113227*/
113228struct Fts3Expr {
113229  int eType;                 /* One of the FTSQUERY_XXX values defined below */
113230  int nNear;                 /* Valid if eType==FTSQUERY_NEAR */
113231  Fts3Expr *pParent;         /* pParent->pLeft==this or pParent->pRight==this */
113232  Fts3Expr *pLeft;           /* Left operand */
113233  Fts3Expr *pRight;          /* Right operand */
113234  Fts3Phrase *pPhrase;       /* Valid if eType==FTSQUERY_PHRASE */
113235
113236  int isLoaded;              /* True if aDoclist/nDoclist are initialized. */
113237  char *aDoclist;            /* Buffer containing doclist */
113238  int nDoclist;              /* Size of aDoclist in bytes */
113239
113240  sqlite3_int64 iCurrent;
113241  char *pCurrent;
113242};
113243
113244/*
113245** Candidate values for Fts3Query.eType. Note that the order of the first
113246** four values is in order of precedence when parsing expressions. For
113247** example, the following:
113248**
113249**   "a OR b AND c NOT d NEAR e"
113250**
113251** is equivalent to:
113252**
113253**   "a OR (b AND (c NOT (d NEAR e)))"
113254*/
113255#define FTSQUERY_NEAR   1
113256#define FTSQUERY_NOT    2
113257#define FTSQUERY_AND    3
113258#define FTSQUERY_OR     4
113259#define FTSQUERY_PHRASE 5
113260
113261
113262/* fts3_write.c */
113263SQLITE_PRIVATE int sqlite3Fts3UpdateMethod(sqlite3_vtab*,int,sqlite3_value**,sqlite3_int64*);
113264SQLITE_PRIVATE int sqlite3Fts3PendingTermsFlush(Fts3Table *);
113265SQLITE_PRIVATE void sqlite3Fts3PendingTermsClear(Fts3Table *);
113266SQLITE_PRIVATE int sqlite3Fts3Optimize(Fts3Table *);
113267SQLITE_PRIVATE int sqlite3Fts3SegReaderNew(int, sqlite3_int64,
113268  sqlite3_int64, sqlite3_int64, const char *, int, Fts3SegReader**);
113269SQLITE_PRIVATE int sqlite3Fts3SegReaderPending(Fts3Table*,const char*,int,int,Fts3SegReader**);
113270SQLITE_PRIVATE void sqlite3Fts3SegReaderFree(Fts3SegReader *);
113271SQLITE_PRIVATE int sqlite3Fts3SegReaderCost(Fts3Cursor *, Fts3SegReader *, int *);
113272SQLITE_PRIVATE int sqlite3Fts3AllSegdirs(Fts3Table*, int, sqlite3_stmt **);
113273SQLITE_PRIVATE int sqlite3Fts3ReadLock(Fts3Table *);
113274SQLITE_PRIVATE int sqlite3Fts3ReadBlock(Fts3Table*, sqlite3_int64, char **, int*);
113275
113276SQLITE_PRIVATE int sqlite3Fts3SelectDoctotal(Fts3Table *, sqlite3_stmt **);
113277SQLITE_PRIVATE int sqlite3Fts3SelectDocsize(Fts3Table *, sqlite3_int64, sqlite3_stmt **);
113278
113279SQLITE_PRIVATE void sqlite3Fts3FreeDeferredTokens(Fts3Cursor *);
113280SQLITE_PRIVATE int sqlite3Fts3DeferToken(Fts3Cursor *, Fts3PhraseToken *, int);
113281SQLITE_PRIVATE int sqlite3Fts3CacheDeferredDoclists(Fts3Cursor *);
113282SQLITE_PRIVATE void sqlite3Fts3FreeDeferredDoclists(Fts3Cursor *);
113283SQLITE_PRIVATE char *sqlite3Fts3DeferredDoclist(Fts3DeferredToken *, int *);
113284SQLITE_PRIVATE void sqlite3Fts3SegmentsClose(Fts3Table *);
113285
113286#define FTS3_SEGCURSOR_PENDING -1
113287#define FTS3_SEGCURSOR_ALL     -2
113288
113289SQLITE_PRIVATE int sqlite3Fts3SegReaderStart(Fts3Table*, Fts3SegReaderCursor*, Fts3SegFilter*);
113290SQLITE_PRIVATE int sqlite3Fts3SegReaderStep(Fts3Table *, Fts3SegReaderCursor *);
113291SQLITE_PRIVATE void sqlite3Fts3SegReaderFinish(Fts3SegReaderCursor *);
113292SQLITE_PRIVATE int sqlite3Fts3SegReaderCursor(
113293    Fts3Table *, int, const char *, int, int, int, Fts3SegReaderCursor *);
113294
113295/* Flags allowed as part of the 4th argument to SegmentReaderIterate() */
113296#define FTS3_SEGMENT_REQUIRE_POS   0x00000001
113297#define FTS3_SEGMENT_IGNORE_EMPTY  0x00000002
113298#define FTS3_SEGMENT_COLUMN_FILTER 0x00000004
113299#define FTS3_SEGMENT_PREFIX        0x00000008
113300#define FTS3_SEGMENT_SCAN          0x00000010
113301
113302/* Type passed as 4th argument to SegmentReaderIterate() */
113303struct Fts3SegFilter {
113304  const char *zTerm;
113305  int nTerm;
113306  int iCol;
113307  int flags;
113308};
113309
113310struct Fts3SegReaderCursor {
113311  /* Used internally by sqlite3Fts3SegReaderXXX() calls */
113312  Fts3SegReader **apSegment;      /* Array of Fts3SegReader objects */
113313  int nSegment;                   /* Size of apSegment array */
113314  int nAdvance;                   /* How many seg-readers to advance */
113315  Fts3SegFilter *pFilter;         /* Pointer to filter object */
113316  char *aBuffer;                  /* Buffer to merge doclists in */
113317  int nBuffer;                    /* Allocated size of aBuffer[] in bytes */
113318
113319  /* Cost of running this iterator. Used by fts3.c only. */
113320  int nCost;
113321
113322  /* Output values. Valid only after Fts3SegReaderStep() returns SQLITE_ROW. */
113323  char *zTerm;                    /* Pointer to term buffer */
113324  int nTerm;                      /* Size of zTerm in bytes */
113325  char *aDoclist;                 /* Pointer to doclist buffer */
113326  int nDoclist;                   /* Size of aDoclist[] in bytes */
113327};
113328
113329/* fts3.c */
113330SQLITE_PRIVATE int sqlite3Fts3PutVarint(char *, sqlite3_int64);
113331SQLITE_PRIVATE int sqlite3Fts3GetVarint(const char *, sqlite_int64 *);
113332SQLITE_PRIVATE int sqlite3Fts3GetVarint32(const char *, int *);
113333SQLITE_PRIVATE int sqlite3Fts3VarintLen(sqlite3_uint64);
113334SQLITE_PRIVATE void sqlite3Fts3Dequote(char *);
113335
113336SQLITE_PRIVATE char *sqlite3Fts3FindPositions(Fts3Expr *, sqlite3_int64, int);
113337SQLITE_PRIVATE int sqlite3Fts3ExprLoadDoclist(Fts3Cursor *, Fts3Expr *);
113338SQLITE_PRIVATE int sqlite3Fts3ExprLoadFtDoclist(Fts3Cursor *, Fts3Expr *, char **, int *);
113339SQLITE_PRIVATE int sqlite3Fts3ExprNearTrim(Fts3Expr *, Fts3Expr *, int);
113340
113341/* fts3_tokenizer.c */
113342SQLITE_PRIVATE const char *sqlite3Fts3NextToken(const char *, int *);
113343SQLITE_PRIVATE int sqlite3Fts3InitHashTable(sqlite3 *, Fts3Hash *, const char *);
113344SQLITE_PRIVATE int sqlite3Fts3InitTokenizer(Fts3Hash *pHash, const char *,
113345    sqlite3_tokenizer **, char **
113346);
113347SQLITE_PRIVATE int sqlite3Fts3IsIdChar(char);
113348
113349/* fts3_snippet.c */
113350SQLITE_PRIVATE void sqlite3Fts3Offsets(sqlite3_context*, Fts3Cursor*);
113351SQLITE_PRIVATE void sqlite3Fts3Snippet(sqlite3_context *, Fts3Cursor *, const char *,
113352  const char *, const char *, int, int
113353);
113354SQLITE_PRIVATE void sqlite3Fts3Matchinfo(sqlite3_context *, Fts3Cursor *, const char *);
113355
113356/* fts3_expr.c */
113357SQLITE_PRIVATE int sqlite3Fts3ExprParse(sqlite3_tokenizer *,
113358  char **, int, int, const char *, int, Fts3Expr **
113359);
113360SQLITE_PRIVATE void sqlite3Fts3ExprFree(Fts3Expr *);
113361#ifdef SQLITE_TEST
113362SQLITE_PRIVATE int sqlite3Fts3ExprInitTestInterface(sqlite3 *db);
113363#endif
113364
113365/* fts3_aux.c */
113366SQLITE_PRIVATE int sqlite3Fts3InitAux(sqlite3 *db);
113367
113368#endif /* _FTSINT_H */
113369
113370/************** End of fts3Int.h *********************************************/
113371/************** Continuing where we left off in fts3.c ***********************/
113372
113373
113374#ifndef SQLITE_CORE
113375  SQLITE_EXTENSION_INIT1
113376#endif
113377
113378/*
113379** Write a 64-bit variable-length integer to memory starting at p[0].
113380** The length of data written will be between 1 and FTS3_VARINT_MAX bytes.
113381** The number of bytes written is returned.
113382*/
113383SQLITE_PRIVATE int sqlite3Fts3PutVarint(char *p, sqlite_int64 v){
113384  unsigned char *q = (unsigned char *) p;
113385  sqlite_uint64 vu = v;
113386  do{
113387    *q++ = (unsigned char) ((vu & 0x7f) | 0x80);
113388    vu >>= 7;
113389  }while( vu!=0 );
113390  q[-1] &= 0x7f;  /* turn off high bit in final byte */
113391  assert( q - (unsigned char *)p <= FTS3_VARINT_MAX );
113392  return (int) (q - (unsigned char *)p);
113393}
113394
113395/*
113396** Read a 64-bit variable-length integer from memory starting at p[0].
113397** Return the number of bytes read, or 0 on error.
113398** The value is stored in *v.
113399*/
113400SQLITE_PRIVATE int sqlite3Fts3GetVarint(const char *p, sqlite_int64 *v){
113401  const unsigned char *q = (const unsigned char *) p;
113402  sqlite_uint64 x = 0, y = 1;
113403  while( (*q&0x80)==0x80 && q-(unsigned char *)p<FTS3_VARINT_MAX ){
113404    x += y * (*q++ & 0x7f);
113405    y <<= 7;
113406  }
113407  x += y * (*q++);
113408  *v = (sqlite_int64) x;
113409  return (int) (q - (unsigned char *)p);
113410}
113411
113412/*
113413** Similar to sqlite3Fts3GetVarint(), except that the output is truncated to a
113414** 32-bit integer before it is returned.
113415*/
113416SQLITE_PRIVATE int sqlite3Fts3GetVarint32(const char *p, int *pi){
113417 sqlite_int64 i;
113418 int ret = sqlite3Fts3GetVarint(p, &i);
113419 *pi = (int) i;
113420 return ret;
113421}
113422
113423/*
113424** Return the number of bytes required to encode v as a varint
113425*/
113426SQLITE_PRIVATE int sqlite3Fts3VarintLen(sqlite3_uint64 v){
113427  int i = 0;
113428  do{
113429    i++;
113430    v >>= 7;
113431  }while( v!=0 );
113432  return i;
113433}
113434
113435/*
113436** Convert an SQL-style quoted string into a normal string by removing
113437** the quote characters.  The conversion is done in-place.  If the
113438** input does not begin with a quote character, then this routine
113439** is a no-op.
113440**
113441** Examples:
113442**
113443**     "abc"   becomes   abc
113444**     'xyz'   becomes   xyz
113445**     [pqr]   becomes   pqr
113446**     `mno`   becomes   mno
113447**
113448*/
113449SQLITE_PRIVATE void sqlite3Fts3Dequote(char *z){
113450  char quote;                     /* Quote character (if any ) */
113451
113452  quote = z[0];
113453  if( quote=='[' || quote=='\'' || quote=='"' || quote=='`' ){
113454    int iIn = 1;                  /* Index of next byte to read from input */
113455    int iOut = 0;                 /* Index of next byte to write to output */
113456
113457    /* If the first byte was a '[', then the close-quote character is a ']' */
113458    if( quote=='[' ) quote = ']';
113459
113460    while( ALWAYS(z[iIn]) ){
113461      if( z[iIn]==quote ){
113462        if( z[iIn+1]!=quote ) break;
113463        z[iOut++] = quote;
113464        iIn += 2;
113465      }else{
113466        z[iOut++] = z[iIn++];
113467      }
113468    }
113469    z[iOut] = '\0';
113470  }
113471}
113472
113473/*
113474** Read a single varint from the doclist at *pp and advance *pp to point
113475** to the first byte past the end of the varint.  Add the value of the varint
113476** to *pVal.
113477*/
113478static void fts3GetDeltaVarint(char **pp, sqlite3_int64 *pVal){
113479  sqlite3_int64 iVal;
113480  *pp += sqlite3Fts3GetVarint(*pp, &iVal);
113481  *pVal += iVal;
113482}
113483
113484/*
113485** As long as *pp has not reached its end (pEnd), then do the same
113486** as fts3GetDeltaVarint(): read a single varint and add it to *pVal.
113487** But if we have reached the end of the varint, just set *pp=0 and
113488** leave *pVal unchanged.
113489*/
113490static void fts3GetDeltaVarint2(char **pp, char *pEnd, sqlite3_int64 *pVal){
113491  if( *pp>=pEnd ){
113492    *pp = 0;
113493  }else{
113494    fts3GetDeltaVarint(pp, pVal);
113495  }
113496}
113497
113498/*
113499** The xDisconnect() virtual table method.
113500*/
113501static int fts3DisconnectMethod(sqlite3_vtab *pVtab){
113502  Fts3Table *p = (Fts3Table *)pVtab;
113503  int i;
113504
113505  assert( p->nPendingData==0 );
113506  assert( p->pSegments==0 );
113507
113508  /* Free any prepared statements held */
113509  for(i=0; i<SizeofArray(p->aStmt); i++){
113510    sqlite3_finalize(p->aStmt[i]);
113511  }
113512  sqlite3_free(p->zSegmentsTbl);
113513  sqlite3_free(p->zReadExprlist);
113514  sqlite3_free(p->zWriteExprlist);
113515
113516  /* Invoke the tokenizer destructor to free the tokenizer. */
113517  p->pTokenizer->pModule->xDestroy(p->pTokenizer);
113518
113519  sqlite3_free(p);
113520  return SQLITE_OK;
113521}
113522
113523/*
113524** Construct one or more SQL statements from the format string given
113525** and then evaluate those statements. The success code is written
113526** into *pRc.
113527**
113528** If *pRc is initially non-zero then this routine is a no-op.
113529*/
113530static void fts3DbExec(
113531  int *pRc,              /* Success code */
113532  sqlite3 *db,           /* Database in which to run SQL */
113533  const char *zFormat,   /* Format string for SQL */
113534  ...                    /* Arguments to the format string */
113535){
113536  va_list ap;
113537  char *zSql;
113538  if( *pRc ) return;
113539  va_start(ap, zFormat);
113540  zSql = sqlite3_vmprintf(zFormat, ap);
113541  va_end(ap);
113542  if( zSql==0 ){
113543    *pRc = SQLITE_NOMEM;
113544  }else{
113545    *pRc = sqlite3_exec(db, zSql, 0, 0, 0);
113546    sqlite3_free(zSql);
113547  }
113548}
113549
113550/*
113551** The xDestroy() virtual table method.
113552*/
113553static int fts3DestroyMethod(sqlite3_vtab *pVtab){
113554  int rc = SQLITE_OK;              /* Return code */
113555  Fts3Table *p = (Fts3Table *)pVtab;
113556  sqlite3 *db = p->db;
113557
113558  /* Drop the shadow tables */
113559  fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_content'", p->zDb, p->zName);
113560  fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_segments'", p->zDb,p->zName);
113561  fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_segdir'", p->zDb, p->zName);
113562  fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_docsize'", p->zDb, p->zName);
113563  fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_stat'", p->zDb, p->zName);
113564
113565  /* If everything has worked, invoke fts3DisconnectMethod() to free the
113566  ** memory associated with the Fts3Table structure and return SQLITE_OK.
113567  ** Otherwise, return an SQLite error code.
113568  */
113569  return (rc==SQLITE_OK ? fts3DisconnectMethod(pVtab) : rc);
113570}
113571
113572
113573/*
113574** Invoke sqlite3_declare_vtab() to declare the schema for the FTS3 table
113575** passed as the first argument. This is done as part of the xConnect()
113576** and xCreate() methods.
113577**
113578** If *pRc is non-zero when this function is called, it is a no-op.
113579** Otherwise, if an error occurs, an SQLite error code is stored in *pRc
113580** before returning.
113581*/
113582static void fts3DeclareVtab(int *pRc, Fts3Table *p){
113583  if( *pRc==SQLITE_OK ){
113584    int i;                        /* Iterator variable */
113585    int rc;                       /* Return code */
113586    char *zSql;                   /* SQL statement passed to declare_vtab() */
113587    char *zCols;                  /* List of user defined columns */
113588
113589    /* Create a list of user columns for the virtual table */
113590    zCols = sqlite3_mprintf("%Q, ", p->azColumn[0]);
113591    for(i=1; zCols && i<p->nColumn; i++){
113592      zCols = sqlite3_mprintf("%z%Q, ", zCols, p->azColumn[i]);
113593    }
113594
113595    /* Create the whole "CREATE TABLE" statement to pass to SQLite */
113596    zSql = sqlite3_mprintf(
113597        "CREATE TABLE x(%s %Q HIDDEN, docid HIDDEN)", zCols, p->zName
113598    );
113599    if( !zCols || !zSql ){
113600      rc = SQLITE_NOMEM;
113601    }else{
113602      rc = sqlite3_declare_vtab(p->db, zSql);
113603    }
113604
113605    sqlite3_free(zSql);
113606    sqlite3_free(zCols);
113607    *pRc = rc;
113608  }
113609}
113610
113611/*
113612** Create the backing store tables (%_content, %_segments and %_segdir)
113613** required by the FTS3 table passed as the only argument. This is done
113614** as part of the vtab xCreate() method.
113615**
113616** If the p->bHasDocsize boolean is true (indicating that this is an
113617** FTS4 table, not an FTS3 table) then also create the %_docsize and
113618** %_stat tables required by FTS4.
113619*/
113620static int fts3CreateTables(Fts3Table *p){
113621  int rc = SQLITE_OK;             /* Return code */
113622  int i;                          /* Iterator variable */
113623  char *zContentCols;             /* Columns of %_content table */
113624  sqlite3 *db = p->db;            /* The database connection */
113625
113626  /* Create a list of user columns for the content table */
113627  zContentCols = sqlite3_mprintf("docid INTEGER PRIMARY KEY");
113628  for(i=0; zContentCols && i<p->nColumn; i++){
113629    char *z = p->azColumn[i];
113630    zContentCols = sqlite3_mprintf("%z, 'c%d%q'", zContentCols, i, z);
113631  }
113632  if( zContentCols==0 ) rc = SQLITE_NOMEM;
113633
113634  /* Create the content table */
113635  fts3DbExec(&rc, db,
113636     "CREATE TABLE %Q.'%q_content'(%s)",
113637     p->zDb, p->zName, zContentCols
113638  );
113639  sqlite3_free(zContentCols);
113640  /* Create other tables */
113641  fts3DbExec(&rc, db,
113642      "CREATE TABLE %Q.'%q_segments'(blockid INTEGER PRIMARY KEY, block BLOB);",
113643      p->zDb, p->zName
113644  );
113645  fts3DbExec(&rc, db,
113646      "CREATE TABLE %Q.'%q_segdir'("
113647        "level INTEGER,"
113648        "idx INTEGER,"
113649        "start_block INTEGER,"
113650        "leaves_end_block INTEGER,"
113651        "end_block INTEGER,"
113652        "root BLOB,"
113653        "PRIMARY KEY(level, idx)"
113654      ");",
113655      p->zDb, p->zName
113656  );
113657  if( p->bHasDocsize ){
113658    fts3DbExec(&rc, db,
113659        "CREATE TABLE %Q.'%q_docsize'(docid INTEGER PRIMARY KEY, size BLOB);",
113660        p->zDb, p->zName
113661    );
113662  }
113663  if( p->bHasStat ){
113664    fts3DbExec(&rc, db,
113665        "CREATE TABLE %Q.'%q_stat'(id INTEGER PRIMARY KEY, value BLOB);",
113666        p->zDb, p->zName
113667    );
113668  }
113669  return rc;
113670}
113671
113672/*
113673** Store the current database page-size in bytes in p->nPgsz.
113674**
113675** If *pRc is non-zero when this function is called, it is a no-op.
113676** Otherwise, if an error occurs, an SQLite error code is stored in *pRc
113677** before returning.
113678*/
113679static void fts3DatabasePageSize(int *pRc, Fts3Table *p){
113680  if( *pRc==SQLITE_OK ){
113681    int rc;                       /* Return code */
113682    char *zSql;                   /* SQL text "PRAGMA %Q.page_size" */
113683    sqlite3_stmt *pStmt;          /* Compiled "PRAGMA %Q.page_size" statement */
113684
113685    zSql = sqlite3_mprintf("PRAGMA %Q.page_size", p->zDb);
113686    if( !zSql ){
113687      rc = SQLITE_NOMEM;
113688    }else{
113689      rc = sqlite3_prepare(p->db, zSql, -1, &pStmt, 0);
113690      if( rc==SQLITE_OK ){
113691        sqlite3_step(pStmt);
113692        p->nPgsz = sqlite3_column_int(pStmt, 0);
113693        rc = sqlite3_finalize(pStmt);
113694      }else if( rc==SQLITE_AUTH ){
113695        p->nPgsz = 1024;
113696        rc = SQLITE_OK;
113697      }
113698    }
113699    assert( p->nPgsz>0 || rc!=SQLITE_OK );
113700    sqlite3_free(zSql);
113701    *pRc = rc;
113702  }
113703}
113704
113705/*
113706** "Special" FTS4 arguments are column specifications of the following form:
113707**
113708**   <key> = <value>
113709**
113710** There may not be whitespace surrounding the "=" character. The <value>
113711** term may be quoted, but the <key> may not.
113712*/
113713static int fts3IsSpecialColumn(
113714  const char *z,
113715  int *pnKey,
113716  char **pzValue
113717){
113718  char *zValue;
113719  const char *zCsr = z;
113720
113721  while( *zCsr!='=' ){
113722    if( *zCsr=='\0' ) return 0;
113723    zCsr++;
113724  }
113725
113726  *pnKey = (int)(zCsr-z);
113727  zValue = sqlite3_mprintf("%s", &zCsr[1]);
113728  if( zValue ){
113729    sqlite3Fts3Dequote(zValue);
113730  }
113731  *pzValue = zValue;
113732  return 1;
113733}
113734
113735/*
113736** Append the output of a printf() style formatting to an existing string.
113737*/
113738static void fts3Appendf(
113739  int *pRc,                       /* IN/OUT: Error code */
113740  char **pz,                      /* IN/OUT: Pointer to string buffer */
113741  const char *zFormat,            /* Printf format string to append */
113742  ...                             /* Arguments for printf format string */
113743){
113744  if( *pRc==SQLITE_OK ){
113745    va_list ap;
113746    char *z;
113747    va_start(ap, zFormat);
113748    z = sqlite3_vmprintf(zFormat, ap);
113749    if( z && *pz ){
113750      char *z2 = sqlite3_mprintf("%s%s", *pz, z);
113751      sqlite3_free(z);
113752      z = z2;
113753    }
113754    if( z==0 ) *pRc = SQLITE_NOMEM;
113755    sqlite3_free(*pz);
113756    *pz = z;
113757  }
113758}
113759
113760/*
113761** Return a copy of input string zInput enclosed in double-quotes (") and
113762** with all double quote characters escaped. For example:
113763**
113764**     fts3QuoteId("un \"zip\"")   ->    "un \"\"zip\"\""
113765**
113766** The pointer returned points to memory obtained from sqlite3_malloc(). It
113767** is the callers responsibility to call sqlite3_free() to release this
113768** memory.
113769*/
113770static char *fts3QuoteId(char const *zInput){
113771  int nRet;
113772  char *zRet;
113773  nRet = 2 + strlen(zInput)*2 + 1;
113774  zRet = sqlite3_malloc(nRet);
113775  if( zRet ){
113776    int i;
113777    char *z = zRet;
113778    *(z++) = '"';
113779    for(i=0; zInput[i]; i++){
113780      if( zInput[i]=='"' ) *(z++) = '"';
113781      *(z++) = zInput[i];
113782    }
113783    *(z++) = '"';
113784    *(z++) = '\0';
113785  }
113786  return zRet;
113787}
113788
113789/*
113790** Return a list of comma separated SQL expressions that could be used
113791** in a SELECT statement such as the following:
113792**
113793**     SELECT <list of expressions> FROM %_content AS x ...
113794**
113795** to return the docid, followed by each column of text data in order
113796** from left to write. If parameter zFunc is not NULL, then instead of
113797** being returned directly each column of text data is passed to an SQL
113798** function named zFunc first. For example, if zFunc is "unzip" and the
113799** table has the three user-defined columns "a", "b", and "c", the following
113800** string is returned:
113801**
113802**     "docid, unzip(x.'a'), unzip(x.'b'), unzip(x.'c')"
113803**
113804** The pointer returned points to a buffer allocated by sqlite3_malloc(). It
113805** is the responsibility of the caller to eventually free it.
113806**
113807** If *pRc is not SQLITE_OK when this function is called, it is a no-op (and
113808** a NULL pointer is returned). Otherwise, if an OOM error is encountered
113809** by this function, NULL is returned and *pRc is set to SQLITE_NOMEM. If
113810** no error occurs, *pRc is left unmodified.
113811*/
113812static char *fts3ReadExprList(Fts3Table *p, const char *zFunc, int *pRc){
113813  char *zRet = 0;
113814  char *zFree = 0;
113815  char *zFunction;
113816  int i;
113817
113818  if( !zFunc ){
113819    zFunction = "";
113820  }else{
113821    zFree = zFunction = fts3QuoteId(zFunc);
113822  }
113823  fts3Appendf(pRc, &zRet, "docid");
113824  for(i=0; i<p->nColumn; i++){
113825    fts3Appendf(pRc, &zRet, ",%s(x.'c%d%q')", zFunction, i, p->azColumn[i]);
113826  }
113827  sqlite3_free(zFree);
113828  return zRet;
113829}
113830
113831/*
113832** Return a list of N comma separated question marks, where N is the number
113833** of columns in the %_content table (one for the docid plus one for each
113834** user-defined text column).
113835**
113836** If argument zFunc is not NULL, then all but the first question mark
113837** is preceded by zFunc and an open bracket, and followed by a closed
113838** bracket. For example, if zFunc is "zip" and the FTS3 table has three
113839** user-defined text columns, the following string is returned:
113840**
113841**     "?, zip(?), zip(?), zip(?)"
113842**
113843** The pointer returned points to a buffer allocated by sqlite3_malloc(). It
113844** is the responsibility of the caller to eventually free it.
113845**
113846** If *pRc is not SQLITE_OK when this function is called, it is a no-op (and
113847** a NULL pointer is returned). Otherwise, if an OOM error is encountered
113848** by this function, NULL is returned and *pRc is set to SQLITE_NOMEM. If
113849** no error occurs, *pRc is left unmodified.
113850*/
113851static char *fts3WriteExprList(Fts3Table *p, const char *zFunc, int *pRc){
113852  char *zRet = 0;
113853  char *zFree = 0;
113854  char *zFunction;
113855  int i;
113856
113857  if( !zFunc ){
113858    zFunction = "";
113859  }else{
113860    zFree = zFunction = fts3QuoteId(zFunc);
113861  }
113862  fts3Appendf(pRc, &zRet, "?");
113863  for(i=0; i<p->nColumn; i++){
113864    fts3Appendf(pRc, &zRet, ",%s(?)", zFunction);
113865  }
113866  sqlite3_free(zFree);
113867  return zRet;
113868}
113869
113870/*
113871** This function is the implementation of both the xConnect and xCreate
113872** methods of the FTS3 virtual table.
113873**
113874** The argv[] array contains the following:
113875**
113876**   argv[0]   -> module name  ("fts3" or "fts4")
113877**   argv[1]   -> database name
113878**   argv[2]   -> table name
113879**   argv[...] -> "column name" and other module argument fields.
113880*/
113881static int fts3InitVtab(
113882  int isCreate,                   /* True for xCreate, false for xConnect */
113883  sqlite3 *db,                    /* The SQLite database connection */
113884  void *pAux,                     /* Hash table containing tokenizers */
113885  int argc,                       /* Number of elements in argv array */
113886  const char * const *argv,       /* xCreate/xConnect argument array */
113887  sqlite3_vtab **ppVTab,          /* Write the resulting vtab structure here */
113888  char **pzErr                    /* Write any error message here */
113889){
113890  Fts3Hash *pHash = (Fts3Hash *)pAux;
113891  Fts3Table *p = 0;               /* Pointer to allocated vtab */
113892  int rc = SQLITE_OK;             /* Return code */
113893  int i;                          /* Iterator variable */
113894  int nByte;                      /* Size of allocation used for *p */
113895  int iCol;                       /* Column index */
113896  int nString = 0;                /* Bytes required to hold all column names */
113897  int nCol = 0;                   /* Number of columns in the FTS table */
113898  char *zCsr;                     /* Space for holding column names */
113899  int nDb;                        /* Bytes required to hold database name */
113900  int nName;                      /* Bytes required to hold table name */
113901  int isFts4 = (argv[0][3]=='4'); /* True for FTS4, false for FTS3 */
113902  int bNoDocsize = 0;             /* True to omit %_docsize table */
113903  const char **aCol;              /* Array of column names */
113904  sqlite3_tokenizer *pTokenizer = 0;        /* Tokenizer for this table */
113905
113906  char *zCompress = 0;
113907  char *zUncompress = 0;
113908
113909  assert( strlen(argv[0])==4 );
113910  assert( (sqlite3_strnicmp(argv[0], "fts4", 4)==0 && isFts4)
113911       || (sqlite3_strnicmp(argv[0], "fts3", 4)==0 && !isFts4)
113912  );
113913
113914  nDb = (int)strlen(argv[1]) + 1;
113915  nName = (int)strlen(argv[2]) + 1;
113916
113917  aCol = (const char **)sqlite3_malloc(sizeof(const char *) * (argc-2) );
113918  if( !aCol ) return SQLITE_NOMEM;
113919  memset((void *)aCol, 0, sizeof(const char *) * (argc-2));
113920
113921  /* Loop through all of the arguments passed by the user to the FTS3/4
113922  ** module (i.e. all the column names and special arguments). This loop
113923  ** does the following:
113924  **
113925  **   + Figures out the number of columns the FTSX table will have, and
113926  **     the number of bytes of space that must be allocated to store copies
113927  **     of the column names.
113928  **
113929  **   + If there is a tokenizer specification included in the arguments,
113930  **     initializes the tokenizer pTokenizer.
113931  */
113932  for(i=3; rc==SQLITE_OK && i<argc; i++){
113933    char const *z = argv[i];
113934    int nKey;
113935    char *zVal;
113936
113937    /* Check if this is a tokenizer specification */
113938    if( !pTokenizer
113939     && strlen(z)>8
113940     && 0==sqlite3_strnicmp(z, "tokenize", 8)
113941     && 0==sqlite3Fts3IsIdChar(z[8])
113942    ){
113943      rc = sqlite3Fts3InitTokenizer(pHash, &z[9], &pTokenizer, pzErr);
113944    }
113945
113946    /* Check if it is an FTS4 special argument. */
113947    else if( isFts4 && fts3IsSpecialColumn(z, &nKey, &zVal) ){
113948      if( !zVal ){
113949        rc = SQLITE_NOMEM;
113950        goto fts3_init_out;
113951      }
113952      if( nKey==9 && 0==sqlite3_strnicmp(z, "matchinfo", 9) ){
113953        if( strlen(zVal)==4 && 0==sqlite3_strnicmp(zVal, "fts3", 4) ){
113954          bNoDocsize = 1;
113955        }else{
113956          *pzErr = sqlite3_mprintf("unrecognized matchinfo: %s", zVal);
113957          rc = SQLITE_ERROR;
113958        }
113959      }else if( nKey==8 && 0==sqlite3_strnicmp(z, "compress", 8) ){
113960        zCompress = zVal;
113961        zVal = 0;
113962      }else if( nKey==10 && 0==sqlite3_strnicmp(z, "uncompress", 10) ){
113963        zUncompress = zVal;
113964        zVal = 0;
113965      }else{
113966        *pzErr = sqlite3_mprintf("unrecognized parameter: %s", z);
113967        rc = SQLITE_ERROR;
113968      }
113969      sqlite3_free(zVal);
113970    }
113971
113972    /* Otherwise, the argument is a column name. */
113973    else {
113974      nString += (int)(strlen(z) + 1);
113975      aCol[nCol++] = z;
113976    }
113977  }
113978  if( rc!=SQLITE_OK ) goto fts3_init_out;
113979
113980  if( nCol==0 ){
113981    assert( nString==0 );
113982    aCol[0] = "content";
113983    nString = 8;
113984    nCol = 1;
113985  }
113986
113987  if( pTokenizer==0 ){
113988    rc = sqlite3Fts3InitTokenizer(pHash, "simple", &pTokenizer, pzErr);
113989    if( rc!=SQLITE_OK ) goto fts3_init_out;
113990  }
113991  assert( pTokenizer );
113992
113993
113994  /* Allocate and populate the Fts3Table structure. */
113995  nByte = sizeof(Fts3Table) +              /* Fts3Table */
113996          nCol * sizeof(char *) +              /* azColumn */
113997          nName +                              /* zName */
113998          nDb +                                /* zDb */
113999          nString;                             /* Space for azColumn strings */
114000  p = (Fts3Table*)sqlite3_malloc(nByte);
114001  if( p==0 ){
114002    rc = SQLITE_NOMEM;
114003    goto fts3_init_out;
114004  }
114005  memset(p, 0, nByte);
114006  p->db = db;
114007  p->nColumn = nCol;
114008  p->nPendingData = 0;
114009  p->azColumn = (char **)&p[1];
114010  p->pTokenizer = pTokenizer;
114011  p->nNodeSize = 1000;
114012  p->nMaxPendingData = FTS3_MAX_PENDING_DATA;
114013  p->bHasDocsize = (isFts4 && bNoDocsize==0);
114014  p->bHasStat = isFts4;
114015  fts3HashInit(&p->pendingTerms, FTS3_HASH_STRING, 1);
114016
114017  /* Fill in the zName and zDb fields of the vtab structure. */
114018  zCsr = (char *)&p->azColumn[nCol];
114019  p->zName = zCsr;
114020  memcpy(zCsr, argv[2], nName);
114021  zCsr += nName;
114022  p->zDb = zCsr;
114023  memcpy(zCsr, argv[1], nDb);
114024  zCsr += nDb;
114025
114026  /* Fill in the azColumn array */
114027  for(iCol=0; iCol<nCol; iCol++){
114028    char *z;
114029    int n;
114030    z = (char *)sqlite3Fts3NextToken(aCol[iCol], &n);
114031    memcpy(zCsr, z, n);
114032    zCsr[n] = '\0';
114033    sqlite3Fts3Dequote(zCsr);
114034    p->azColumn[iCol] = zCsr;
114035    zCsr += n+1;
114036    assert( zCsr <= &((char *)p)[nByte] );
114037  }
114038
114039  if( (zCompress==0)!=(zUncompress==0) ){
114040    char const *zMiss = (zCompress==0 ? "compress" : "uncompress");
114041    rc = SQLITE_ERROR;
114042    *pzErr = sqlite3_mprintf("missing %s parameter in fts4 constructor", zMiss);
114043  }
114044  p->zReadExprlist = fts3ReadExprList(p, zUncompress, &rc);
114045  p->zWriteExprlist = fts3WriteExprList(p, zCompress, &rc);
114046  if( rc!=SQLITE_OK ) goto fts3_init_out;
114047
114048  /* If this is an xCreate call, create the underlying tables in the
114049  ** database. TODO: For xConnect(), it could verify that said tables exist.
114050  */
114051  if( isCreate ){
114052    rc = fts3CreateTables(p);
114053  }
114054
114055  /* Figure out the page-size for the database. This is required in order to
114056  ** estimate the cost of loading large doclists from the database (see
114057  ** function sqlite3Fts3SegReaderCost() for details).
114058  */
114059  fts3DatabasePageSize(&rc, p);
114060
114061  /* Declare the table schema to SQLite. */
114062  fts3DeclareVtab(&rc, p);
114063
114064fts3_init_out:
114065  sqlite3_free(zCompress);
114066  sqlite3_free(zUncompress);
114067  sqlite3_free((void *)aCol);
114068  if( rc!=SQLITE_OK ){
114069    if( p ){
114070      fts3DisconnectMethod((sqlite3_vtab *)p);
114071    }else if( pTokenizer ){
114072      pTokenizer->pModule->xDestroy(pTokenizer);
114073    }
114074  }else{
114075    *ppVTab = &p->base;
114076  }
114077  return rc;
114078}
114079
114080/*
114081** The xConnect() and xCreate() methods for the virtual table. All the
114082** work is done in function fts3InitVtab().
114083*/
114084static int fts3ConnectMethod(
114085  sqlite3 *db,                    /* Database connection */
114086  void *pAux,                     /* Pointer to tokenizer hash table */
114087  int argc,                       /* Number of elements in argv array */
114088  const char * const *argv,       /* xCreate/xConnect argument array */
114089  sqlite3_vtab **ppVtab,          /* OUT: New sqlite3_vtab object */
114090  char **pzErr                    /* OUT: sqlite3_malloc'd error message */
114091){
114092  return fts3InitVtab(0, db, pAux, argc, argv, ppVtab, pzErr);
114093}
114094static int fts3CreateMethod(
114095  sqlite3 *db,                    /* Database connection */
114096  void *pAux,                     /* Pointer to tokenizer hash table */
114097  int argc,                       /* Number of elements in argv array */
114098  const char * const *argv,       /* xCreate/xConnect argument array */
114099  sqlite3_vtab **ppVtab,          /* OUT: New sqlite3_vtab object */
114100  char **pzErr                    /* OUT: sqlite3_malloc'd error message */
114101){
114102  return fts3InitVtab(1, db, pAux, argc, argv, ppVtab, pzErr);
114103}
114104
114105/*
114106** Implementation of the xBestIndex method for FTS3 tables. There
114107** are three possible strategies, in order of preference:
114108**
114109**   1. Direct lookup by rowid or docid.
114110**   2. Full-text search using a MATCH operator on a non-docid column.
114111**   3. Linear scan of %_content table.
114112*/
114113static int fts3BestIndexMethod(sqlite3_vtab *pVTab, sqlite3_index_info *pInfo){
114114  Fts3Table *p = (Fts3Table *)pVTab;
114115  int i;                          /* Iterator variable */
114116  int iCons = -1;                 /* Index of constraint to use */
114117
114118  /* By default use a full table scan. This is an expensive option,
114119  ** so search through the constraints to see if a more efficient
114120  ** strategy is possible.
114121  */
114122  pInfo->idxNum = FTS3_FULLSCAN_SEARCH;
114123  pInfo->estimatedCost = 500000;
114124  for(i=0; i<pInfo->nConstraint; i++){
114125    struct sqlite3_index_constraint *pCons = &pInfo->aConstraint[i];
114126    if( pCons->usable==0 ) continue;
114127
114128    /* A direct lookup on the rowid or docid column. Assign a cost of 1.0. */
114129    if( pCons->op==SQLITE_INDEX_CONSTRAINT_EQ
114130     && (pCons->iColumn<0 || pCons->iColumn==p->nColumn+1 )
114131    ){
114132      pInfo->idxNum = FTS3_DOCID_SEARCH;
114133      pInfo->estimatedCost = 1.0;
114134      iCons = i;
114135    }
114136
114137    /* A MATCH constraint. Use a full-text search.
114138    **
114139    ** If there is more than one MATCH constraint available, use the first
114140    ** one encountered. If there is both a MATCH constraint and a direct
114141    ** rowid/docid lookup, prefer the MATCH strategy. This is done even
114142    ** though the rowid/docid lookup is faster than a MATCH query, selecting
114143    ** it would lead to an "unable to use function MATCH in the requested
114144    ** context" error.
114145    */
114146    if( pCons->op==SQLITE_INDEX_CONSTRAINT_MATCH
114147     && pCons->iColumn>=0 && pCons->iColumn<=p->nColumn
114148    ){
114149      pInfo->idxNum = FTS3_FULLTEXT_SEARCH + pCons->iColumn;
114150      pInfo->estimatedCost = 2.0;
114151      iCons = i;
114152      break;
114153    }
114154  }
114155
114156  if( iCons>=0 ){
114157    pInfo->aConstraintUsage[iCons].argvIndex = 1;
114158    pInfo->aConstraintUsage[iCons].omit = 1;
114159  }
114160  return SQLITE_OK;
114161}
114162
114163/*
114164** Implementation of xOpen method.
114165*/
114166static int fts3OpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
114167  sqlite3_vtab_cursor *pCsr;               /* Allocated cursor */
114168
114169  UNUSED_PARAMETER(pVTab);
114170
114171  /* Allocate a buffer large enough for an Fts3Cursor structure. If the
114172  ** allocation succeeds, zero it and return SQLITE_OK. Otherwise,
114173  ** if the allocation fails, return SQLITE_NOMEM.
114174  */
114175  *ppCsr = pCsr = (sqlite3_vtab_cursor *)sqlite3_malloc(sizeof(Fts3Cursor));
114176  if( !pCsr ){
114177    return SQLITE_NOMEM;
114178  }
114179  memset(pCsr, 0, sizeof(Fts3Cursor));
114180  return SQLITE_OK;
114181}
114182
114183/*
114184** Close the cursor.  For additional information see the documentation
114185** on the xClose method of the virtual table interface.
114186*/
114187static int fts3CloseMethod(sqlite3_vtab_cursor *pCursor){
114188  Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
114189  assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
114190  sqlite3_finalize(pCsr->pStmt);
114191  sqlite3Fts3ExprFree(pCsr->pExpr);
114192  sqlite3Fts3FreeDeferredTokens(pCsr);
114193  sqlite3_free(pCsr->aDoclist);
114194  sqlite3_free(pCsr->aMatchinfo);
114195  sqlite3_free(pCsr);
114196  return SQLITE_OK;
114197}
114198
114199/*
114200** Position the pCsr->pStmt statement so that it is on the row
114201** of the %_content table that contains the last match.  Return
114202** SQLITE_OK on success.
114203*/
114204static int fts3CursorSeek(sqlite3_context *pContext, Fts3Cursor *pCsr){
114205  if( pCsr->isRequireSeek ){
114206    pCsr->isRequireSeek = 0;
114207    sqlite3_bind_int64(pCsr->pStmt, 1, pCsr->iPrevId);
114208    if( SQLITE_ROW==sqlite3_step(pCsr->pStmt) ){
114209      return SQLITE_OK;
114210    }else{
114211      int rc = sqlite3_reset(pCsr->pStmt);
114212      if( rc==SQLITE_OK ){
114213        /* If no row was found and no error has occured, then the %_content
114214        ** table is missing a row that is present in the full-text index.
114215        ** The data structures are corrupt.
114216        */
114217        rc = SQLITE_CORRUPT;
114218      }
114219      pCsr->isEof = 1;
114220      if( pContext ){
114221        sqlite3_result_error_code(pContext, rc);
114222      }
114223      return rc;
114224    }
114225  }else{
114226    return SQLITE_OK;
114227  }
114228}
114229
114230/*
114231** This function is used to process a single interior node when searching
114232** a b-tree for a term or term prefix. The node data is passed to this
114233** function via the zNode/nNode parameters. The term to search for is
114234** passed in zTerm/nTerm.
114235**
114236** If piFirst is not NULL, then this function sets *piFirst to the blockid
114237** of the child node that heads the sub-tree that may contain the term.
114238**
114239** If piLast is not NULL, then *piLast is set to the right-most child node
114240** that heads a sub-tree that may contain a term for which zTerm/nTerm is
114241** a prefix.
114242**
114243** If an OOM error occurs, SQLITE_NOMEM is returned. Otherwise, SQLITE_OK.
114244*/
114245static int fts3ScanInteriorNode(
114246  const char *zTerm,              /* Term to select leaves for */
114247  int nTerm,                      /* Size of term zTerm in bytes */
114248  const char *zNode,              /* Buffer containing segment interior node */
114249  int nNode,                      /* Size of buffer at zNode */
114250  sqlite3_int64 *piFirst,         /* OUT: Selected child node */
114251  sqlite3_int64 *piLast           /* OUT: Selected child node */
114252){
114253  int rc = SQLITE_OK;             /* Return code */
114254  const char *zCsr = zNode;       /* Cursor to iterate through node */
114255  const char *zEnd = &zCsr[nNode];/* End of interior node buffer */
114256  char *zBuffer = 0;              /* Buffer to load terms into */
114257  int nAlloc = 0;                 /* Size of allocated buffer */
114258  int isFirstTerm = 1;            /* True when processing first term on page */
114259  sqlite3_int64 iChild;           /* Block id of child node to descend to */
114260
114261  /* Skip over the 'height' varint that occurs at the start of every
114262  ** interior node. Then load the blockid of the left-child of the b-tree
114263  ** node into variable iChild.
114264  **
114265  ** Even if the data structure on disk is corrupted, this (reading two
114266  ** varints from the buffer) does not risk an overread. If zNode is a
114267  ** root node, then the buffer comes from a SELECT statement. SQLite does
114268  ** not make this guarantee explicitly, but in practice there are always
114269  ** either more than 20 bytes of allocated space following the nNode bytes of
114270  ** contents, or two zero bytes. Or, if the node is read from the %_segments
114271  ** table, then there are always 20 bytes of zeroed padding following the
114272  ** nNode bytes of content (see sqlite3Fts3ReadBlock() for details).
114273  */
114274  zCsr += sqlite3Fts3GetVarint(zCsr, &iChild);
114275  zCsr += sqlite3Fts3GetVarint(zCsr, &iChild);
114276  if( zCsr>zEnd ){
114277    return SQLITE_CORRUPT;
114278  }
114279
114280  while( zCsr<zEnd && (piFirst || piLast) ){
114281    int cmp;                      /* memcmp() result */
114282    int nSuffix;                  /* Size of term suffix */
114283    int nPrefix = 0;              /* Size of term prefix */
114284    int nBuffer;                  /* Total term size */
114285
114286    /* Load the next term on the node into zBuffer. Use realloc() to expand
114287    ** the size of zBuffer if required.  */
114288    if( !isFirstTerm ){
114289      zCsr += sqlite3Fts3GetVarint32(zCsr, &nPrefix);
114290    }
114291    isFirstTerm = 0;
114292    zCsr += sqlite3Fts3GetVarint32(zCsr, &nSuffix);
114293
114294    /* NOTE(shess): Previous code checked for negative nPrefix and
114295    ** nSuffix and suffix overrunning zEnd.  Additionally corrupt if
114296    ** the prefix is longer than the previous term, or if the suffix
114297    ** causes overflow.
114298    */
114299    if( nPrefix<0 || nSuffix<0 /* || nPrefix>nBuffer */
114300     || &zCsr[nSuffix]<zCsr || &zCsr[nSuffix]>zEnd ){
114301      rc = SQLITE_CORRUPT;
114302      goto finish_scan;
114303    }
114304    if( nPrefix+nSuffix>nAlloc ){
114305      char *zNew;
114306      nAlloc = (nPrefix+nSuffix) * 2;
114307      zNew = (char *)sqlite3_realloc(zBuffer, nAlloc);
114308      if( !zNew ){
114309        rc = SQLITE_NOMEM;
114310        goto finish_scan;
114311      }
114312      zBuffer = zNew;
114313    }
114314    memcpy(&zBuffer[nPrefix], zCsr, nSuffix);
114315    nBuffer = nPrefix + nSuffix;
114316    zCsr += nSuffix;
114317
114318    /* Compare the term we are searching for with the term just loaded from
114319    ** the interior node. If the specified term is greater than or equal
114320    ** to the term from the interior node, then all terms on the sub-tree
114321    ** headed by node iChild are smaller than zTerm. No need to search
114322    ** iChild.
114323    **
114324    ** If the interior node term is larger than the specified term, then
114325    ** the tree headed by iChild may contain the specified term.
114326    */
114327    cmp = memcmp(zTerm, zBuffer, (nBuffer>nTerm ? nTerm : nBuffer));
114328    if( piFirst && (cmp<0 || (cmp==0 && nBuffer>nTerm)) ){
114329      *piFirst = iChild;
114330      piFirst = 0;
114331    }
114332
114333    if( piLast && cmp<0 ){
114334      *piLast = iChild;
114335      piLast = 0;
114336    }
114337
114338    iChild++;
114339  };
114340
114341  if( piFirst ) *piFirst = iChild;
114342  if( piLast ) *piLast = iChild;
114343
114344 finish_scan:
114345  sqlite3_free(zBuffer);
114346  return rc;
114347}
114348
114349
114350/*
114351** The buffer pointed to by argument zNode (size nNode bytes) contains an
114352** interior node of a b-tree segment. The zTerm buffer (size nTerm bytes)
114353** contains a term. This function searches the sub-tree headed by the zNode
114354** node for the range of leaf nodes that may contain the specified term
114355** or terms for which the specified term is a prefix.
114356**
114357** If piLeaf is not NULL, then *piLeaf is set to the blockid of the
114358** left-most leaf node in the tree that may contain the specified term.
114359** If piLeaf2 is not NULL, then *piLeaf2 is set to the blockid of the
114360** right-most leaf node that may contain a term for which the specified
114361** term is a prefix.
114362**
114363** It is possible that the range of returned leaf nodes does not contain
114364** the specified term or any terms for which it is a prefix. However, if the
114365** segment does contain any such terms, they are stored within the identified
114366** range. Because this function only inspects interior segment nodes (and
114367** never loads leaf nodes into memory), it is not possible to be sure.
114368**
114369** If an error occurs, an error code other than SQLITE_OK is returned.
114370*/
114371static int fts3SelectLeaf(
114372  Fts3Table *p,                   /* Virtual table handle */
114373  const char *zTerm,              /* Term to select leaves for */
114374  int nTerm,                      /* Size of term zTerm in bytes */
114375  const char *zNode,              /* Buffer containing segment interior node */
114376  int nNode,                      /* Size of buffer at zNode */
114377  sqlite3_int64 *piLeaf,          /* Selected leaf node */
114378  sqlite3_int64 *piLeaf2          /* Selected leaf node */
114379){
114380  int rc;                         /* Return code */
114381  int iHeight;                    /* Height of this node in tree */
114382
114383  assert( piLeaf || piLeaf2 );
114384
114385  sqlite3Fts3GetVarint32(zNode, &iHeight);
114386  rc = fts3ScanInteriorNode(zTerm, nTerm, zNode, nNode, piLeaf, piLeaf2);
114387  assert( !piLeaf2 || !piLeaf || rc!=SQLITE_OK || (*piLeaf<=*piLeaf2) );
114388
114389  if( rc==SQLITE_OK && iHeight>1 ){
114390    char *zBlob = 0;              /* Blob read from %_segments table */
114391    int nBlob;                    /* Size of zBlob in bytes */
114392
114393    if( piLeaf && piLeaf2 && (*piLeaf!=*piLeaf2) ){
114394      rc = sqlite3Fts3ReadBlock(p, *piLeaf, &zBlob, &nBlob);
114395      if( rc==SQLITE_OK ){
114396        rc = fts3SelectLeaf(p, zTerm, nTerm, zBlob, nBlob, piLeaf, 0);
114397      }
114398      sqlite3_free(zBlob);
114399      piLeaf = 0;
114400      zBlob = 0;
114401    }
114402
114403    if( rc==SQLITE_OK ){
114404      rc = sqlite3Fts3ReadBlock(p, piLeaf ? *piLeaf : *piLeaf2, &zBlob, &nBlob);
114405    }
114406    if( rc==SQLITE_OK ){
114407      rc = fts3SelectLeaf(p, zTerm, nTerm, zBlob, nBlob, piLeaf, piLeaf2);
114408    }
114409    sqlite3_free(zBlob);
114410  }
114411
114412  return rc;
114413}
114414
114415/*
114416** This function is used to create delta-encoded serialized lists of FTS3
114417** varints. Each call to this function appends a single varint to a list.
114418*/
114419static void fts3PutDeltaVarint(
114420  char **pp,                      /* IN/OUT: Output pointer */
114421  sqlite3_int64 *piPrev,          /* IN/OUT: Previous value written to list */
114422  sqlite3_int64 iVal              /* Write this value to the list */
114423){
114424  assert( iVal-*piPrev > 0 || (*piPrev==0 && iVal==0) );
114425  *pp += sqlite3Fts3PutVarint(*pp, iVal-*piPrev);
114426  *piPrev = iVal;
114427}
114428
114429/*
114430** When this function is called, *ppPoslist is assumed to point to the
114431** start of a position-list. After it returns, *ppPoslist points to the
114432** first byte after the position-list.
114433**
114434** A position list is list of positions (delta encoded) and columns for
114435** a single document record of a doclist.  So, in other words, this
114436** routine advances *ppPoslist so that it points to the next docid in
114437** the doclist, or to the first byte past the end of the doclist.
114438**
114439** If pp is not NULL, then the contents of the position list are copied
114440** to *pp. *pp is set to point to the first byte past the last byte copied
114441** before this function returns.
114442*/
114443static void fts3PoslistCopy(char **pp, char **ppPoslist){
114444  char *pEnd = *ppPoslist;
114445  char c = 0;
114446
114447  /* The end of a position list is marked by a zero encoded as an FTS3
114448  ** varint. A single POS_END (0) byte. Except, if the 0 byte is preceded by
114449  ** a byte with the 0x80 bit set, then it is not a varint 0, but the tail
114450  ** of some other, multi-byte, value.
114451  **
114452  ** The following while-loop moves pEnd to point to the first byte that is not
114453  ** immediately preceded by a byte with the 0x80 bit set. Then increments
114454  ** pEnd once more so that it points to the byte immediately following the
114455  ** last byte in the position-list.
114456  */
114457  while( *pEnd | c ){
114458    c = *pEnd++ & 0x80;
114459    testcase( c!=0 && (*pEnd)==0 );
114460  }
114461  pEnd++;  /* Advance past the POS_END terminator byte */
114462
114463  if( pp ){
114464    int n = (int)(pEnd - *ppPoslist);
114465    char *p = *pp;
114466    memcpy(p, *ppPoslist, n);
114467    p += n;
114468    *pp = p;
114469  }
114470  *ppPoslist = pEnd;
114471}
114472
114473/*
114474** When this function is called, *ppPoslist is assumed to point to the
114475** start of a column-list. After it returns, *ppPoslist points to the
114476** to the terminator (POS_COLUMN or POS_END) byte of the column-list.
114477**
114478** A column-list is list of delta-encoded positions for a single column
114479** within a single document within a doclist.
114480**
114481** The column-list is terminated either by a POS_COLUMN varint (1) or
114482** a POS_END varint (0).  This routine leaves *ppPoslist pointing to
114483** the POS_COLUMN or POS_END that terminates the column-list.
114484**
114485** If pp is not NULL, then the contents of the column-list are copied
114486** to *pp. *pp is set to point to the first byte past the last byte copied
114487** before this function returns.  The POS_COLUMN or POS_END terminator
114488** is not copied into *pp.
114489*/
114490static void fts3ColumnlistCopy(char **pp, char **ppPoslist){
114491  char *pEnd = *ppPoslist;
114492  char c = 0;
114493
114494  /* A column-list is terminated by either a 0x01 or 0x00 byte that is
114495  ** not part of a multi-byte varint.
114496  */
114497  while( 0xFE & (*pEnd | c) ){
114498    c = *pEnd++ & 0x80;
114499    testcase( c!=0 && ((*pEnd)&0xfe)==0 );
114500  }
114501  if( pp ){
114502    int n = (int)(pEnd - *ppPoslist);
114503    char *p = *pp;
114504    memcpy(p, *ppPoslist, n);
114505    p += n;
114506    *pp = p;
114507  }
114508  *ppPoslist = pEnd;
114509}
114510
114511/*
114512** Value used to signify the end of an position-list. This is safe because
114513** it is not possible to have a document with 2^31 terms.
114514*/
114515#define POSITION_LIST_END 0x7fffffff
114516
114517/*
114518** This function is used to help parse position-lists. When this function is
114519** called, *pp may point to the start of the next varint in the position-list
114520** being parsed, or it may point to 1 byte past the end of the position-list
114521** (in which case **pp will be a terminator bytes POS_END (0) or
114522** (1)).
114523**
114524** If *pp points past the end of the current position-list, set *pi to
114525** POSITION_LIST_END and return. Otherwise, read the next varint from *pp,
114526** increment the current value of *pi by the value read, and set *pp to
114527** point to the next value before returning.
114528**
114529** Before calling this routine *pi must be initialized to the value of
114530** the previous position, or zero if we are reading the first position
114531** in the position-list.  Because positions are delta-encoded, the value
114532** of the previous position is needed in order to compute the value of
114533** the next position.
114534*/
114535static void fts3ReadNextPos(
114536  char **pp,                    /* IN/OUT: Pointer into position-list buffer */
114537  sqlite3_int64 *pi             /* IN/OUT: Value read from position-list */
114538){
114539  if( (**pp)&0xFE ){
114540    fts3GetDeltaVarint(pp, pi);
114541    *pi -= 2;
114542  }else{
114543    *pi = POSITION_LIST_END;
114544  }
114545}
114546
114547/*
114548** If parameter iCol is not 0, write an POS_COLUMN (1) byte followed by
114549** the value of iCol encoded as a varint to *pp.   This will start a new
114550** column list.
114551**
114552** Set *pp to point to the byte just after the last byte written before
114553** returning (do not modify it if iCol==0). Return the total number of bytes
114554** written (0 if iCol==0).
114555*/
114556static int fts3PutColNumber(char **pp, int iCol){
114557  int n = 0;                      /* Number of bytes written */
114558  if( iCol ){
114559    char *p = *pp;                /* Output pointer */
114560    n = 1 + sqlite3Fts3PutVarint(&p[1], iCol);
114561    *p = 0x01;
114562    *pp = &p[n];
114563  }
114564  return n;
114565}
114566
114567/*
114568** Compute the union of two position lists.  The output written
114569** into *pp contains all positions of both *pp1 and *pp2 in sorted
114570** order and with any duplicates removed.  All pointers are
114571** updated appropriately.   The caller is responsible for insuring
114572** that there is enough space in *pp to hold the complete output.
114573*/
114574static void fts3PoslistMerge(
114575  char **pp,                      /* Output buffer */
114576  char **pp1,                     /* Left input list */
114577  char **pp2                      /* Right input list */
114578){
114579  char *p = *pp;
114580  char *p1 = *pp1;
114581  char *p2 = *pp2;
114582
114583  while( *p1 || *p2 ){
114584    int iCol1;         /* The current column index in pp1 */
114585    int iCol2;         /* The current column index in pp2 */
114586
114587    if( *p1==POS_COLUMN ) sqlite3Fts3GetVarint32(&p1[1], &iCol1);
114588    else if( *p1==POS_END ) iCol1 = POSITION_LIST_END;
114589    else iCol1 = 0;
114590
114591    if( *p2==POS_COLUMN ) sqlite3Fts3GetVarint32(&p2[1], &iCol2);
114592    else if( *p2==POS_END ) iCol2 = POSITION_LIST_END;
114593    else iCol2 = 0;
114594
114595    if( iCol1==iCol2 ){
114596      sqlite3_int64 i1 = 0;       /* Last position from pp1 */
114597      sqlite3_int64 i2 = 0;       /* Last position from pp2 */
114598      sqlite3_int64 iPrev = 0;
114599      int n = fts3PutColNumber(&p, iCol1);
114600      p1 += n;
114601      p2 += n;
114602
114603      /* At this point, both p1 and p2 point to the start of column-lists
114604      ** for the same column (the column with index iCol1 and iCol2).
114605      ** A column-list is a list of non-negative delta-encoded varints, each
114606      ** incremented by 2 before being stored. Each list is terminated by a
114607      ** POS_END (0) or POS_COLUMN (1). The following block merges the two lists
114608      ** and writes the results to buffer p. p is left pointing to the byte
114609      ** after the list written. No terminator (POS_END or POS_COLUMN) is
114610      ** written to the output.
114611      */
114612      fts3GetDeltaVarint(&p1, &i1);
114613      fts3GetDeltaVarint(&p2, &i2);
114614      do {
114615        fts3PutDeltaVarint(&p, &iPrev, (i1<i2) ? i1 : i2);
114616        iPrev -= 2;
114617        if( i1==i2 ){
114618          fts3ReadNextPos(&p1, &i1);
114619          fts3ReadNextPos(&p2, &i2);
114620        }else if( i1<i2 ){
114621          fts3ReadNextPos(&p1, &i1);
114622        }else{
114623          fts3ReadNextPos(&p2, &i2);
114624        }
114625      }while( i1!=POSITION_LIST_END || i2!=POSITION_LIST_END );
114626    }else if( iCol1<iCol2 ){
114627      p1 += fts3PutColNumber(&p, iCol1);
114628      fts3ColumnlistCopy(&p, &p1);
114629    }else{
114630      p2 += fts3PutColNumber(&p, iCol2);
114631      fts3ColumnlistCopy(&p, &p2);
114632    }
114633  }
114634
114635  *p++ = POS_END;
114636  *pp = p;
114637  *pp1 = p1 + 1;
114638  *pp2 = p2 + 1;
114639}
114640
114641/*
114642** nToken==1 searches for adjacent positions.
114643**
114644** This function is used to merge two position lists into one. When it is
114645** called, *pp1 and *pp2 must both point to position lists. A position-list is
114646** the part of a doclist that follows each document id. For example, if a row
114647** contains:
114648**
114649**     'a b c'|'x y z'|'a b b a'
114650**
114651** Then the position list for this row for token 'b' would consist of:
114652**
114653**     0x02 0x01 0x02 0x03 0x03 0x00
114654**
114655** When this function returns, both *pp1 and *pp2 are left pointing to the
114656** byte following the 0x00 terminator of their respective position lists.
114657**
114658** If isSaveLeft is 0, an entry is added to the output position list for
114659** each position in *pp2 for which there exists one or more positions in
114660** *pp1 so that (pos(*pp2)>pos(*pp1) && pos(*pp2)-pos(*pp1)<=nToken). i.e.
114661** when the *pp1 token appears before the *pp2 token, but not more than nToken
114662** slots before it.
114663*/
114664static int fts3PoslistPhraseMerge(
114665  char **pp,                      /* IN/OUT: Preallocated output buffer */
114666  int nToken,                     /* Maximum difference in token positions */
114667  int isSaveLeft,                 /* Save the left position */
114668  int isExact,                    /* If *pp1 is exactly nTokens before *pp2 */
114669  char **pp1,                     /* IN/OUT: Left input list */
114670  char **pp2                      /* IN/OUT: Right input list */
114671){
114672  char *p = (pp ? *pp : 0);
114673  char *p1 = *pp1;
114674  char *p2 = *pp2;
114675  int iCol1 = 0;
114676  int iCol2 = 0;
114677
114678  /* Never set both isSaveLeft and isExact for the same invocation. */
114679  assert( isSaveLeft==0 || isExact==0 );
114680
114681  assert( *p1!=0 && *p2!=0 );
114682  if( *p1==POS_COLUMN ){
114683    p1++;
114684    p1 += sqlite3Fts3GetVarint32(p1, &iCol1);
114685  }
114686  if( *p2==POS_COLUMN ){
114687    p2++;
114688    p2 += sqlite3Fts3GetVarint32(p2, &iCol2);
114689  }
114690
114691  while( 1 ){
114692    if( iCol1==iCol2 ){
114693      char *pSave = p;
114694      sqlite3_int64 iPrev = 0;
114695      sqlite3_int64 iPos1 = 0;
114696      sqlite3_int64 iPos2 = 0;
114697
114698      if( pp && iCol1 ){
114699        *p++ = POS_COLUMN;
114700        p += sqlite3Fts3PutVarint(p, iCol1);
114701      }
114702
114703      assert( *p1!=POS_END && *p1!=POS_COLUMN );
114704      assert( *p2!=POS_END && *p2!=POS_COLUMN );
114705      fts3GetDeltaVarint(&p1, &iPos1); iPos1 -= 2;
114706      fts3GetDeltaVarint(&p2, &iPos2); iPos2 -= 2;
114707
114708      while( 1 ){
114709        if( iPos2==iPos1+nToken
114710         || (isExact==0 && iPos2>iPos1 && iPos2<=iPos1+nToken)
114711        ){
114712          sqlite3_int64 iSave;
114713          if( !pp ){
114714            fts3PoslistCopy(0, &p2);
114715            fts3PoslistCopy(0, &p1);
114716            *pp1 = p1;
114717            *pp2 = p2;
114718            return 1;
114719          }
114720          iSave = isSaveLeft ? iPos1 : iPos2;
114721          fts3PutDeltaVarint(&p, &iPrev, iSave+2); iPrev -= 2;
114722          pSave = 0;
114723        }
114724        if( (!isSaveLeft && iPos2<=(iPos1+nToken)) || iPos2<=iPos1 ){
114725          if( (*p2&0xFE)==0 ) break;
114726          fts3GetDeltaVarint(&p2, &iPos2); iPos2 -= 2;
114727        }else{
114728          if( (*p1&0xFE)==0 ) break;
114729          fts3GetDeltaVarint(&p1, &iPos1); iPos1 -= 2;
114730        }
114731      }
114732
114733      if( pSave ){
114734        assert( pp && p );
114735        p = pSave;
114736      }
114737
114738      fts3ColumnlistCopy(0, &p1);
114739      fts3ColumnlistCopy(0, &p2);
114740      assert( (*p1&0xFE)==0 && (*p2&0xFE)==0 );
114741      if( 0==*p1 || 0==*p2 ) break;
114742
114743      p1++;
114744      p1 += sqlite3Fts3GetVarint32(p1, &iCol1);
114745      p2++;
114746      p2 += sqlite3Fts3GetVarint32(p2, &iCol2);
114747    }
114748
114749    /* Advance pointer p1 or p2 (whichever corresponds to the smaller of
114750    ** iCol1 and iCol2) so that it points to either the 0x00 that marks the
114751    ** end of the position list, or the 0x01 that precedes the next
114752    ** column-number in the position list.
114753    */
114754    else if( iCol1<iCol2 ){
114755      fts3ColumnlistCopy(0, &p1);
114756      if( 0==*p1 ) break;
114757      p1++;
114758      p1 += sqlite3Fts3GetVarint32(p1, &iCol1);
114759    }else{
114760      fts3ColumnlistCopy(0, &p2);
114761      if( 0==*p2 ) break;
114762      p2++;
114763      p2 += sqlite3Fts3GetVarint32(p2, &iCol2);
114764    }
114765  }
114766
114767  fts3PoslistCopy(0, &p2);
114768  fts3PoslistCopy(0, &p1);
114769  *pp1 = p1;
114770  *pp2 = p2;
114771  if( !pp || *pp==p ){
114772    return 0;
114773  }
114774  *p++ = 0x00;
114775  *pp = p;
114776  return 1;
114777}
114778
114779/*
114780** Merge two position-lists as required by the NEAR operator.
114781*/
114782static int fts3PoslistNearMerge(
114783  char **pp,                      /* Output buffer */
114784  char *aTmp,                     /* Temporary buffer space */
114785  int nRight,                     /* Maximum difference in token positions */
114786  int nLeft,                      /* Maximum difference in token positions */
114787  char **pp1,                     /* IN/OUT: Left input list */
114788  char **pp2                      /* IN/OUT: Right input list */
114789){
114790  char *p1 = *pp1;
114791  char *p2 = *pp2;
114792
114793  if( !pp ){
114794    if( fts3PoslistPhraseMerge(0, nRight, 0, 0, pp1, pp2) ) return 1;
114795    *pp1 = p1;
114796    *pp2 = p2;
114797    return fts3PoslistPhraseMerge(0, nLeft, 0, 0, pp2, pp1);
114798  }else{
114799    char *pTmp1 = aTmp;
114800    char *pTmp2;
114801    char *aTmp2;
114802    int res = 1;
114803
114804    fts3PoslistPhraseMerge(&pTmp1, nRight, 0, 0, pp1, pp2);
114805    aTmp2 = pTmp2 = pTmp1;
114806    *pp1 = p1;
114807    *pp2 = p2;
114808    fts3PoslistPhraseMerge(&pTmp2, nLeft, 1, 0, pp2, pp1);
114809    if( pTmp1!=aTmp && pTmp2!=aTmp2 ){
114810      fts3PoslistMerge(pp, &aTmp, &aTmp2);
114811    }else if( pTmp1!=aTmp ){
114812      fts3PoslistCopy(pp, &aTmp);
114813    }else if( pTmp2!=aTmp2 ){
114814      fts3PoslistCopy(pp, &aTmp2);
114815    }else{
114816      res = 0;
114817    }
114818
114819    return res;
114820  }
114821}
114822
114823/*
114824** Values that may be used as the first parameter to fts3DoclistMerge().
114825*/
114826#define MERGE_NOT        2        /* D + D -> D */
114827#define MERGE_AND        3        /* D + D -> D */
114828#define MERGE_OR         4        /* D + D -> D */
114829#define MERGE_POS_OR     5        /* P + P -> P */
114830#define MERGE_PHRASE     6        /* P + P -> D */
114831#define MERGE_POS_PHRASE 7        /* P + P -> P */
114832#define MERGE_NEAR       8        /* P + P -> D */
114833#define MERGE_POS_NEAR   9        /* P + P -> P */
114834
114835/*
114836** Merge the two doclists passed in buffer a1 (size n1 bytes) and a2
114837** (size n2 bytes). The output is written to pre-allocated buffer aBuffer,
114838** which is guaranteed to be large enough to hold the results. The number
114839** of bytes written to aBuffer is stored in *pnBuffer before returning.
114840**
114841** If successful, SQLITE_OK is returned. Otherwise, if a malloc error
114842** occurs while allocating a temporary buffer as part of the merge operation,
114843** SQLITE_NOMEM is returned.
114844*/
114845static int fts3DoclistMerge(
114846  int mergetype,                  /* One of the MERGE_XXX constants */
114847  int nParam1,                    /* Used by MERGE_NEAR and MERGE_POS_NEAR */
114848  int nParam2,                    /* Used by MERGE_NEAR and MERGE_POS_NEAR */
114849  char *aBuffer,                  /* Pre-allocated output buffer */
114850  int *pnBuffer,                  /* OUT: Bytes written to aBuffer */
114851  char *a1,                       /* Buffer containing first doclist */
114852  int n1,                         /* Size of buffer a1 */
114853  char *a2,                       /* Buffer containing second doclist */
114854  int n2,                         /* Size of buffer a2 */
114855  int *pnDoc                      /* OUT: Number of docids in output */
114856){
114857  sqlite3_int64 i1 = 0;
114858  sqlite3_int64 i2 = 0;
114859  sqlite3_int64 iPrev = 0;
114860
114861  char *p = aBuffer;
114862  char *p1 = a1;
114863  char *p2 = a2;
114864  char *pEnd1 = &a1[n1];
114865  char *pEnd2 = &a2[n2];
114866  int nDoc = 0;
114867
114868  assert( mergetype==MERGE_OR     || mergetype==MERGE_POS_OR
114869       || mergetype==MERGE_AND    || mergetype==MERGE_NOT
114870       || mergetype==MERGE_PHRASE || mergetype==MERGE_POS_PHRASE
114871       || mergetype==MERGE_NEAR   || mergetype==MERGE_POS_NEAR
114872  );
114873
114874  if( !aBuffer ){
114875    *pnBuffer = 0;
114876    return SQLITE_NOMEM;
114877  }
114878
114879  /* Read the first docid from each doclist */
114880  fts3GetDeltaVarint2(&p1, pEnd1, &i1);
114881  fts3GetDeltaVarint2(&p2, pEnd2, &i2);
114882
114883  switch( mergetype ){
114884    case MERGE_OR:
114885    case MERGE_POS_OR:
114886      while( p1 || p2 ){
114887        if( p2 && p1 && i1==i2 ){
114888          fts3PutDeltaVarint(&p, &iPrev, i1);
114889          if( mergetype==MERGE_POS_OR ) fts3PoslistMerge(&p, &p1, &p2);
114890          fts3GetDeltaVarint2(&p1, pEnd1, &i1);
114891          fts3GetDeltaVarint2(&p2, pEnd2, &i2);
114892        }else if( !p2 || (p1 && i1<i2) ){
114893          fts3PutDeltaVarint(&p, &iPrev, i1);
114894          if( mergetype==MERGE_POS_OR ) fts3PoslistCopy(&p, &p1);
114895          fts3GetDeltaVarint2(&p1, pEnd1, &i1);
114896        }else{
114897          fts3PutDeltaVarint(&p, &iPrev, i2);
114898          if( mergetype==MERGE_POS_OR ) fts3PoslistCopy(&p, &p2);
114899          fts3GetDeltaVarint2(&p2, pEnd2, &i2);
114900        }
114901      }
114902      break;
114903
114904    case MERGE_AND:
114905      while( p1 && p2 ){
114906        if( i1==i2 ){
114907          fts3PutDeltaVarint(&p, &iPrev, i1);
114908          fts3GetDeltaVarint2(&p1, pEnd1, &i1);
114909          fts3GetDeltaVarint2(&p2, pEnd2, &i2);
114910          nDoc++;
114911        }else if( i1<i2 ){
114912          fts3GetDeltaVarint2(&p1, pEnd1, &i1);
114913        }else{
114914          fts3GetDeltaVarint2(&p2, pEnd2, &i2);
114915        }
114916      }
114917      break;
114918
114919    case MERGE_NOT:
114920      while( p1 ){
114921        if( p2 && i1==i2 ){
114922          fts3GetDeltaVarint2(&p1, pEnd1, &i1);
114923          fts3GetDeltaVarint2(&p2, pEnd2, &i2);
114924        }else if( !p2 || i1<i2 ){
114925          fts3PutDeltaVarint(&p, &iPrev, i1);
114926          fts3GetDeltaVarint2(&p1, pEnd1, &i1);
114927        }else{
114928          fts3GetDeltaVarint2(&p2, pEnd2, &i2);
114929        }
114930      }
114931      break;
114932
114933    case MERGE_POS_PHRASE:
114934    case MERGE_PHRASE: {
114935      char **ppPos = (mergetype==MERGE_PHRASE ? 0 : &p);
114936      while( p1 && p2 ){
114937        if( i1==i2 ){
114938          char *pSave = p;
114939          sqlite3_int64 iPrevSave = iPrev;
114940          fts3PutDeltaVarint(&p, &iPrev, i1);
114941          if( 0==fts3PoslistPhraseMerge(ppPos, nParam1, 0, 1, &p1, &p2) ){
114942            p = pSave;
114943            iPrev = iPrevSave;
114944          }else{
114945            nDoc++;
114946          }
114947          fts3GetDeltaVarint2(&p1, pEnd1, &i1);
114948          fts3GetDeltaVarint2(&p2, pEnd2, &i2);
114949        }else if( i1<i2 ){
114950          fts3PoslistCopy(0, &p1);
114951          fts3GetDeltaVarint2(&p1, pEnd1, &i1);
114952        }else{
114953          fts3PoslistCopy(0, &p2);
114954          fts3GetDeltaVarint2(&p2, pEnd2, &i2);
114955        }
114956      }
114957      break;
114958    }
114959
114960    default: assert( mergetype==MERGE_POS_NEAR || mergetype==MERGE_NEAR ); {
114961      char *aTmp = 0;
114962      char **ppPos = 0;
114963
114964      if( mergetype==MERGE_POS_NEAR ){
114965        ppPos = &p;
114966        aTmp = sqlite3_malloc(2*(n1+n2+1));
114967        if( !aTmp ){
114968          return SQLITE_NOMEM;
114969        }
114970      }
114971
114972      while( p1 && p2 ){
114973        if( i1==i2 ){
114974          char *pSave = p;
114975          sqlite3_int64 iPrevSave = iPrev;
114976          fts3PutDeltaVarint(&p, &iPrev, i1);
114977
114978          if( !fts3PoslistNearMerge(ppPos, aTmp, nParam1, nParam2, &p1, &p2) ){
114979            iPrev = iPrevSave;
114980            p = pSave;
114981          }
114982
114983          fts3GetDeltaVarint2(&p1, pEnd1, &i1);
114984          fts3GetDeltaVarint2(&p2, pEnd2, &i2);
114985        }else if( i1<i2 ){
114986          fts3PoslistCopy(0, &p1);
114987          fts3GetDeltaVarint2(&p1, pEnd1, &i1);
114988        }else{
114989          fts3PoslistCopy(0, &p2);
114990          fts3GetDeltaVarint2(&p2, pEnd2, &i2);
114991        }
114992      }
114993      sqlite3_free(aTmp);
114994      break;
114995    }
114996  }
114997
114998  if( pnDoc ) *pnDoc = nDoc;
114999  *pnBuffer = (int)(p-aBuffer);
115000  return SQLITE_OK;
115001}
115002
115003/*
115004** A pointer to an instance of this structure is used as the context
115005** argument to sqlite3Fts3SegReaderIterate()
115006*/
115007typedef struct TermSelect TermSelect;
115008struct TermSelect {
115009  int isReqPos;
115010  char *aaOutput[16];             /* Malloc'd output buffer */
115011  int anOutput[16];               /* Size of output in bytes */
115012};
115013
115014/*
115015** Merge all doclists in the TermSelect.aaOutput[] array into a single
115016** doclist stored in TermSelect.aaOutput[0]. If successful, delete all
115017** other doclists (except the aaOutput[0] one) and return SQLITE_OK.
115018**
115019** If an OOM error occurs, return SQLITE_NOMEM. In this case it is
115020** the responsibility of the caller to free any doclists left in the
115021** TermSelect.aaOutput[] array.
115022*/
115023static int fts3TermSelectMerge(TermSelect *pTS){
115024  int mergetype = (pTS->isReqPos ? MERGE_POS_OR : MERGE_OR);
115025  char *aOut = 0;
115026  int nOut = 0;
115027  int i;
115028
115029  /* Loop through the doclists in the aaOutput[] array. Merge them all
115030  ** into a single doclist.
115031  */
115032  for(i=0; i<SizeofArray(pTS->aaOutput); i++){
115033    if( pTS->aaOutput[i] ){
115034      if( !aOut ){
115035        aOut = pTS->aaOutput[i];
115036        nOut = pTS->anOutput[i];
115037        pTS->aaOutput[i] = 0;
115038      }else{
115039        int nNew = nOut + pTS->anOutput[i];
115040        char *aNew = sqlite3_malloc(nNew);
115041        if( !aNew ){
115042          sqlite3_free(aOut);
115043          return SQLITE_NOMEM;
115044        }
115045        fts3DoclistMerge(mergetype, 0, 0,
115046            aNew, &nNew, pTS->aaOutput[i], pTS->anOutput[i], aOut, nOut, 0
115047        );
115048        sqlite3_free(pTS->aaOutput[i]);
115049        sqlite3_free(aOut);
115050        pTS->aaOutput[i] = 0;
115051        aOut = aNew;
115052        nOut = nNew;
115053      }
115054    }
115055  }
115056
115057  pTS->aaOutput[0] = aOut;
115058  pTS->anOutput[0] = nOut;
115059  return SQLITE_OK;
115060}
115061
115062/*
115063** This function is used as the sqlite3Fts3SegReaderIterate() callback when
115064** querying the full-text index for a doclist associated with a term or
115065** term-prefix.
115066*/
115067static int fts3TermSelectCb(
115068  Fts3Table *p,                   /* Virtual table object */
115069  void *pContext,                 /* Pointer to TermSelect structure */
115070  char *zTerm,
115071  int nTerm,
115072  char *aDoclist,
115073  int nDoclist
115074){
115075  TermSelect *pTS = (TermSelect *)pContext;
115076
115077  UNUSED_PARAMETER(p);
115078  UNUSED_PARAMETER(zTerm);
115079  UNUSED_PARAMETER(nTerm);
115080
115081  if( pTS->aaOutput[0]==0 ){
115082    /* If this is the first term selected, copy the doclist to the output
115083    ** buffer using memcpy(). TODO: Add a way to transfer control of the
115084    ** aDoclist buffer from the caller so as to avoid the memcpy().
115085    */
115086    pTS->aaOutput[0] = sqlite3_malloc(nDoclist);
115087    pTS->anOutput[0] = nDoclist;
115088    if( pTS->aaOutput[0] ){
115089      memcpy(pTS->aaOutput[0], aDoclist, nDoclist);
115090    }else{
115091      return SQLITE_NOMEM;
115092    }
115093  }else{
115094    int mergetype = (pTS->isReqPos ? MERGE_POS_OR : MERGE_OR);
115095    char *aMerge = aDoclist;
115096    int nMerge = nDoclist;
115097    int iOut;
115098
115099    for(iOut=0; iOut<SizeofArray(pTS->aaOutput); iOut++){
115100      char *aNew;
115101      int nNew;
115102      if( pTS->aaOutput[iOut]==0 ){
115103        assert( iOut>0 );
115104        pTS->aaOutput[iOut] = aMerge;
115105        pTS->anOutput[iOut] = nMerge;
115106        break;
115107      }
115108
115109      nNew = nMerge + pTS->anOutput[iOut];
115110      aNew = sqlite3_malloc(nNew);
115111      if( !aNew ){
115112        if( aMerge!=aDoclist ){
115113          sqlite3_free(aMerge);
115114        }
115115        return SQLITE_NOMEM;
115116      }
115117      fts3DoclistMerge(mergetype, 0, 0, aNew, &nNew,
115118          pTS->aaOutput[iOut], pTS->anOutput[iOut], aMerge, nMerge, 0
115119      );
115120
115121      if( iOut>0 ) sqlite3_free(aMerge);
115122      sqlite3_free(pTS->aaOutput[iOut]);
115123      pTS->aaOutput[iOut] = 0;
115124
115125      aMerge = aNew;
115126      nMerge = nNew;
115127      if( (iOut+1)==SizeofArray(pTS->aaOutput) ){
115128        pTS->aaOutput[iOut] = aMerge;
115129        pTS->anOutput[iOut] = nMerge;
115130      }
115131    }
115132  }
115133  return SQLITE_OK;
115134}
115135
115136static int fts3DeferredTermSelect(
115137  Fts3DeferredToken *pToken,      /* Phrase token */
115138  int isTermPos,                  /* True to include positions */
115139  int *pnOut,                     /* OUT: Size of list */
115140  char **ppOut                    /* OUT: Body of list */
115141){
115142  char *aSource;
115143  int nSource;
115144
115145  aSource = sqlite3Fts3DeferredDoclist(pToken, &nSource);
115146  if( !aSource ){
115147    *pnOut = 0;
115148    *ppOut = 0;
115149  }else if( isTermPos ){
115150    *ppOut = sqlite3_malloc(nSource);
115151    if( !*ppOut ) return SQLITE_NOMEM;
115152    memcpy(*ppOut, aSource, nSource);
115153    *pnOut = nSource;
115154  }else{
115155    sqlite3_int64 docid;
115156    *pnOut = sqlite3Fts3GetVarint(aSource, &docid);
115157    *ppOut = sqlite3_malloc(*pnOut);
115158    if( !*ppOut ) return SQLITE_NOMEM;
115159    sqlite3Fts3PutVarint(*ppOut, docid);
115160  }
115161
115162  return SQLITE_OK;
115163}
115164
115165SQLITE_PRIVATE int sqlite3Fts3SegReaderCursor(
115166  Fts3Table *p,                   /* FTS3 table handle */
115167  int iLevel,                     /* Level of segments to scan */
115168  const char *zTerm,              /* Term to query for */
115169  int nTerm,                      /* Size of zTerm in bytes */
115170  int isPrefix,                   /* True for a prefix search */
115171  int isScan,                     /* True to scan from zTerm to EOF */
115172  Fts3SegReaderCursor *pCsr       /* Cursor object to populate */
115173){
115174  int rc = SQLITE_OK;
115175  int rc2;
115176  int iAge = 0;
115177  sqlite3_stmt *pStmt = 0;
115178  Fts3SegReader *pPending = 0;
115179
115180  assert( iLevel==FTS3_SEGCURSOR_ALL
115181      ||  iLevel==FTS3_SEGCURSOR_PENDING
115182      ||  iLevel>=0
115183  );
115184  assert( FTS3_SEGCURSOR_PENDING<0 );
115185  assert( FTS3_SEGCURSOR_ALL<0 );
115186  assert( iLevel==FTS3_SEGCURSOR_ALL || (zTerm==0 && isPrefix==1) );
115187  assert( isPrefix==0 || isScan==0 );
115188
115189
115190  memset(pCsr, 0, sizeof(Fts3SegReaderCursor));
115191
115192  /* If iLevel is less than 0, include a seg-reader for the pending-terms. */
115193  assert( isScan==0 || fts3HashCount(&p->pendingTerms)==0 );
115194  if( iLevel<0 && isScan==0 ){
115195    rc = sqlite3Fts3SegReaderPending(p, zTerm, nTerm, isPrefix, &pPending);
115196    if( rc==SQLITE_OK && pPending ){
115197      int nByte = (sizeof(Fts3SegReader *) * 16);
115198      pCsr->apSegment = (Fts3SegReader **)sqlite3_malloc(nByte);
115199      if( pCsr->apSegment==0 ){
115200        rc = SQLITE_NOMEM;
115201      }else{
115202        pCsr->apSegment[0] = pPending;
115203        pCsr->nSegment = 1;
115204        pPending = 0;
115205      }
115206    }
115207  }
115208
115209  if( iLevel!=FTS3_SEGCURSOR_PENDING ){
115210    if( rc==SQLITE_OK ){
115211      rc = sqlite3Fts3AllSegdirs(p, iLevel, &pStmt);
115212    }
115213    while( rc==SQLITE_OK && SQLITE_ROW==(rc = sqlite3_step(pStmt)) ){
115214
115215      /* Read the values returned by the SELECT into local variables. */
115216      sqlite3_int64 iStartBlock = sqlite3_column_int64(pStmt, 1);
115217      sqlite3_int64 iLeavesEndBlock = sqlite3_column_int64(pStmt, 2);
115218      sqlite3_int64 iEndBlock = sqlite3_column_int64(pStmt, 3);
115219      int nRoot = sqlite3_column_bytes(pStmt, 4);
115220      char const *zRoot = sqlite3_column_blob(pStmt, 4);
115221
115222      /* If nSegment is a multiple of 16 the array needs to be extended. */
115223      if( (pCsr->nSegment%16)==0 ){
115224        Fts3SegReader **apNew;
115225        int nByte = (pCsr->nSegment + 16)*sizeof(Fts3SegReader*);
115226        apNew = (Fts3SegReader **)sqlite3_realloc(pCsr->apSegment, nByte);
115227        if( !apNew ){
115228          rc = SQLITE_NOMEM;
115229          goto finished;
115230        }
115231        pCsr->apSegment = apNew;
115232      }
115233
115234      /* If zTerm is not NULL, and this segment is not stored entirely on its
115235      ** root node, the range of leaves scanned can be reduced. Do this. */
115236      if( iStartBlock && zTerm ){
115237        sqlite3_int64 *pi = (isPrefix ? &iLeavesEndBlock : 0);
115238        rc = fts3SelectLeaf(p, zTerm, nTerm, zRoot, nRoot, &iStartBlock, pi);
115239        if( rc!=SQLITE_OK ) goto finished;
115240        if( isPrefix==0 && isScan==0 ) iLeavesEndBlock = iStartBlock;
115241      }
115242
115243      rc = sqlite3Fts3SegReaderNew(iAge, iStartBlock, iLeavesEndBlock,
115244          iEndBlock, zRoot, nRoot, &pCsr->apSegment[pCsr->nSegment]
115245      );
115246      if( rc!=SQLITE_OK ) goto finished;
115247      pCsr->nSegment++;
115248      iAge++;
115249    }
115250  }
115251
115252 finished:
115253  rc2 = sqlite3_reset(pStmt);
115254  if( rc==SQLITE_DONE ) rc = rc2;
115255  sqlite3Fts3SegReaderFree(pPending);
115256
115257  return rc;
115258}
115259
115260
115261static int fts3TermSegReaderCursor(
115262  Fts3Cursor *pCsr,               /* Virtual table cursor handle */
115263  const char *zTerm,              /* Term to query for */
115264  int nTerm,                      /* Size of zTerm in bytes */
115265  int isPrefix,                   /* True for a prefix search */
115266  Fts3SegReaderCursor **ppSegcsr  /* OUT: Allocated seg-reader cursor */
115267){
115268  Fts3SegReaderCursor *pSegcsr;   /* Object to allocate and return */
115269  int rc = SQLITE_NOMEM;          /* Return code */
115270
115271  pSegcsr = sqlite3_malloc(sizeof(Fts3SegReaderCursor));
115272  if( pSegcsr ){
115273    Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
115274    int i;
115275    int nCost = 0;
115276    rc = sqlite3Fts3SegReaderCursor(
115277        p, FTS3_SEGCURSOR_ALL, zTerm, nTerm, isPrefix, 0, pSegcsr);
115278
115279    for(i=0; rc==SQLITE_OK && i<pSegcsr->nSegment; i++){
115280      rc = sqlite3Fts3SegReaderCost(pCsr, pSegcsr->apSegment[i], &nCost);
115281    }
115282    pSegcsr->nCost = nCost;
115283  }
115284
115285  *ppSegcsr = pSegcsr;
115286  return rc;
115287}
115288
115289static void fts3SegReaderCursorFree(Fts3SegReaderCursor *pSegcsr){
115290  sqlite3Fts3SegReaderFinish(pSegcsr);
115291  sqlite3_free(pSegcsr);
115292}
115293
115294/*
115295** This function retreives the doclist for the specified term (or term
115296** prefix) from the database.
115297**
115298** The returned doclist may be in one of two formats, depending on the
115299** value of parameter isReqPos. If isReqPos is zero, then the doclist is
115300** a sorted list of delta-compressed docids (a bare doclist). If isReqPos
115301** is non-zero, then the returned list is in the same format as is stored
115302** in the database without the found length specifier at the start of on-disk
115303** doclists.
115304*/
115305static int fts3TermSelect(
115306  Fts3Table *p,                   /* Virtual table handle */
115307  Fts3PhraseToken *pTok,          /* Token to query for */
115308  int iColumn,                    /* Column to query (or -ve for all columns) */
115309  int isReqPos,                   /* True to include position lists in output */
115310  int *pnOut,                     /* OUT: Size of buffer at *ppOut */
115311  char **ppOut                    /* OUT: Malloced result buffer */
115312){
115313  int rc;                         /* Return code */
115314  Fts3SegReaderCursor *pSegcsr;   /* Seg-reader cursor for this term */
115315  TermSelect tsc;                 /* Context object for fts3TermSelectCb() */
115316  Fts3SegFilter filter;           /* Segment term filter configuration */
115317
115318  pSegcsr = pTok->pSegcsr;
115319  memset(&tsc, 0, sizeof(TermSelect));
115320  tsc.isReqPos = isReqPos;
115321
115322  filter.flags = FTS3_SEGMENT_IGNORE_EMPTY
115323        | (pTok->isPrefix ? FTS3_SEGMENT_PREFIX : 0)
115324        | (isReqPos ? FTS3_SEGMENT_REQUIRE_POS : 0)
115325        | (iColumn<p->nColumn ? FTS3_SEGMENT_COLUMN_FILTER : 0);
115326  filter.iCol = iColumn;
115327  filter.zTerm = pTok->z;
115328  filter.nTerm = pTok->n;
115329
115330  rc = sqlite3Fts3SegReaderStart(p, pSegcsr, &filter);
115331  while( SQLITE_OK==rc
115332      && SQLITE_ROW==(rc = sqlite3Fts3SegReaderStep(p, pSegcsr))
115333  ){
115334    rc = fts3TermSelectCb(p, (void *)&tsc,
115335        pSegcsr->zTerm, pSegcsr->nTerm, pSegcsr->aDoclist, pSegcsr->nDoclist
115336    );
115337  }
115338
115339  if( rc==SQLITE_OK ){
115340    rc = fts3TermSelectMerge(&tsc);
115341  }
115342  if( rc==SQLITE_OK ){
115343    *ppOut = tsc.aaOutput[0];
115344    *pnOut = tsc.anOutput[0];
115345  }else{
115346    int i;
115347    for(i=0; i<SizeofArray(tsc.aaOutput); i++){
115348      sqlite3_free(tsc.aaOutput[i]);
115349    }
115350  }
115351
115352  fts3SegReaderCursorFree(pSegcsr);
115353  pTok->pSegcsr = 0;
115354  return rc;
115355}
115356
115357/*
115358** This function counts the total number of docids in the doclist stored
115359** in buffer aList[], size nList bytes.
115360**
115361** If the isPoslist argument is true, then it is assumed that the doclist
115362** contains a position-list following each docid. Otherwise, it is assumed
115363** that the doclist is simply a list of docids stored as delta encoded
115364** varints.
115365*/
115366static int fts3DoclistCountDocids(int isPoslist, char *aList, int nList){
115367  int nDoc = 0;                   /* Return value */
115368  if( aList ){
115369    char *aEnd = &aList[nList];   /* Pointer to one byte after EOF */
115370    char *p = aList;              /* Cursor */
115371    if( !isPoslist ){
115372      /* The number of docids in the list is the same as the number of
115373      ** varints. In FTS3 a varint consists of a single byte with the 0x80
115374      ** bit cleared and zero or more bytes with the 0x80 bit set. So to
115375      ** count the varints in the buffer, just count the number of bytes
115376      ** with the 0x80 bit clear.  */
115377      while( p<aEnd ) nDoc += (((*p++)&0x80)==0);
115378    }else{
115379      while( p<aEnd ){
115380        nDoc++;
115381        while( (*p++)&0x80 );     /* Skip docid varint */
115382        fts3PoslistCopy(0, &p);   /* Skip over position list */
115383      }
115384    }
115385  }
115386
115387  return nDoc;
115388}
115389
115390/*
115391** Call sqlite3Fts3DeferToken() for each token in the expression pExpr.
115392*/
115393static int fts3DeferExpression(Fts3Cursor *pCsr, Fts3Expr *pExpr){
115394  int rc = SQLITE_OK;
115395  if( pExpr ){
115396    rc = fts3DeferExpression(pCsr, pExpr->pLeft);
115397    if( rc==SQLITE_OK ){
115398      rc = fts3DeferExpression(pCsr, pExpr->pRight);
115399    }
115400    if( pExpr->eType==FTSQUERY_PHRASE ){
115401      int iCol = pExpr->pPhrase->iColumn;
115402      int i;
115403      for(i=0; rc==SQLITE_OK && i<pExpr->pPhrase->nToken; i++){
115404        Fts3PhraseToken *pToken = &pExpr->pPhrase->aToken[i];
115405        if( pToken->pDeferred==0 ){
115406          rc = sqlite3Fts3DeferToken(pCsr, pToken, iCol);
115407        }
115408      }
115409    }
115410  }
115411  return rc;
115412}
115413
115414/*
115415** This function removes the position information from a doclist. When
115416** called, buffer aList (size *pnList bytes) contains a doclist that includes
115417** position information. This function removes the position information so
115418** that aList contains only docids, and adjusts *pnList to reflect the new
115419** (possibly reduced) size of the doclist.
115420*/
115421static void fts3DoclistStripPositions(
115422  char *aList,                    /* IN/OUT: Buffer containing doclist */
115423  int *pnList                     /* IN/OUT: Size of doclist in bytes */
115424){
115425  if( aList ){
115426    char *aEnd = &aList[*pnList]; /* Pointer to one byte after EOF */
115427    char *p = aList;              /* Input cursor */
115428    char *pOut = aList;           /* Output cursor */
115429
115430    while( p<aEnd ){
115431      sqlite3_int64 delta;
115432      p += sqlite3Fts3GetVarint(p, &delta);
115433      fts3PoslistCopy(0, &p);
115434      pOut += sqlite3Fts3PutVarint(pOut, delta);
115435    }
115436
115437    *pnList = (int)(pOut - aList);
115438  }
115439}
115440
115441/*
115442** Return a DocList corresponding to the phrase *pPhrase.
115443**
115444** If this function returns SQLITE_OK, but *pnOut is set to a negative value,
115445** then no tokens in the phrase were looked up in the full-text index. This
115446** is only possible when this function is called from within xFilter(). The
115447** caller should assume that all documents match the phrase. The actual
115448** filtering will take place in xNext().
115449*/
115450static int fts3PhraseSelect(
115451  Fts3Cursor *pCsr,               /* Virtual table cursor handle */
115452  Fts3Phrase *pPhrase,            /* Phrase to return a doclist for */
115453  int isReqPos,                   /* True if output should contain positions */
115454  char **paOut,                   /* OUT: Pointer to malloc'd result buffer */
115455  int *pnOut                      /* OUT: Size of buffer at *paOut */
115456){
115457  char *pOut = 0;
115458  int nOut = 0;
115459  int rc = SQLITE_OK;
115460  int ii;
115461  int iCol = pPhrase->iColumn;
115462  int isTermPos = (pPhrase->nToken>1 || isReqPos);
115463  Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
115464  int isFirst = 1;
115465
115466  int iPrevTok = 0;
115467  int nDoc = 0;
115468
115469  /* If this is an xFilter() evaluation, create a segment-reader for each
115470  ** phrase token. Or, if this is an xNext() or snippet/offsets/matchinfo
115471  ** evaluation, only create segment-readers if there are no Fts3DeferredToken
115472  ** objects attached to the phrase-tokens.
115473  */
115474  for(ii=0; ii<pPhrase->nToken; ii++){
115475    Fts3PhraseToken *pTok = &pPhrase->aToken[ii];
115476    if( pTok->pSegcsr==0 ){
115477      if( (pCsr->eEvalmode==FTS3_EVAL_FILTER)
115478       || (pCsr->eEvalmode==FTS3_EVAL_NEXT && pCsr->pDeferred==0)
115479       || (pCsr->eEvalmode==FTS3_EVAL_MATCHINFO && pTok->bFulltext)
115480      ){
115481        rc = fts3TermSegReaderCursor(
115482            pCsr, pTok->z, pTok->n, pTok->isPrefix, &pTok->pSegcsr
115483        );
115484        if( rc!=SQLITE_OK ) return rc;
115485      }
115486    }
115487  }
115488
115489  for(ii=0; ii<pPhrase->nToken; ii++){
115490    Fts3PhraseToken *pTok;        /* Token to find doclist for */
115491    int iTok = 0;                 /* The token being queried this iteration */
115492    char *pList = 0;              /* Pointer to token doclist */
115493    int nList = 0;                /* Size of buffer at pList */
115494
115495    /* Select a token to process. If this is an xFilter() call, then tokens
115496    ** are processed in order from least to most costly. Otherwise, tokens
115497    ** are processed in the order in which they occur in the phrase.
115498    */
115499    if( pCsr->eEvalmode==FTS3_EVAL_MATCHINFO ){
115500      assert( isReqPos );
115501      iTok = ii;
115502      pTok = &pPhrase->aToken[iTok];
115503      if( pTok->bFulltext==0 ) continue;
115504    }else if( pCsr->eEvalmode==FTS3_EVAL_NEXT || isReqPos ){
115505      iTok = ii;
115506      pTok = &pPhrase->aToken[iTok];
115507    }else{
115508      int nMinCost = 0x7FFFFFFF;
115509      int jj;
115510
115511      /* Find the remaining token with the lowest cost. */
115512      for(jj=0; jj<pPhrase->nToken; jj++){
115513        Fts3SegReaderCursor *pSegcsr = pPhrase->aToken[jj].pSegcsr;
115514        if( pSegcsr && pSegcsr->nCost<nMinCost ){
115515          iTok = jj;
115516          nMinCost = pSegcsr->nCost;
115517        }
115518      }
115519      pTok = &pPhrase->aToken[iTok];
115520
115521      /* This branch is taken if it is determined that loading the doclist
115522      ** for the next token would require more IO than loading all documents
115523      ** currently identified by doclist pOut/nOut. No further doclists will
115524      ** be loaded from the full-text index for this phrase.
115525      */
115526      if( nMinCost>nDoc && ii>0 ){
115527        rc = fts3DeferExpression(pCsr, pCsr->pExpr);
115528        break;
115529      }
115530    }
115531
115532    if( pCsr->eEvalmode==FTS3_EVAL_NEXT && pTok->pDeferred ){
115533      rc = fts3DeferredTermSelect(pTok->pDeferred, isTermPos, &nList, &pList);
115534    }else{
115535      if( pTok->pSegcsr ){
115536        rc = fts3TermSelect(p, pTok, iCol, isTermPos, &nList, &pList);
115537      }
115538      pTok->bFulltext = 1;
115539    }
115540    assert( rc!=SQLITE_OK || pCsr->eEvalmode || pTok->pSegcsr==0 );
115541    if( rc!=SQLITE_OK ) break;
115542
115543    if( isFirst ){
115544      pOut = pList;
115545      nOut = nList;
115546      if( pCsr->eEvalmode==FTS3_EVAL_FILTER && pPhrase->nToken>1 ){
115547        nDoc = fts3DoclistCountDocids(1, pOut, nOut);
115548      }
115549      isFirst = 0;
115550      iPrevTok = iTok;
115551    }else{
115552      /* Merge the new term list and the current output. */
115553      char *aLeft, *aRight;
115554      int nLeft, nRight;
115555      int nDist;
115556      int mt;
115557
115558      /* If this is the final token of the phrase, and positions were not
115559      ** requested by the caller, use MERGE_PHRASE instead of POS_PHRASE.
115560      ** This drops the position information from the output list.
115561      */
115562      mt = MERGE_POS_PHRASE;
115563      if( ii==pPhrase->nToken-1 && !isReqPos ) mt = MERGE_PHRASE;
115564
115565      assert( iPrevTok!=iTok );
115566      if( iPrevTok<iTok ){
115567        aLeft = pOut;
115568        nLeft = nOut;
115569        aRight = pList;
115570        nRight = nList;
115571        nDist = iTok-iPrevTok;
115572        iPrevTok = iTok;
115573      }else{
115574        aRight = pOut;
115575        nRight = nOut;
115576        aLeft = pList;
115577        nLeft = nList;
115578        nDist = iPrevTok-iTok;
115579      }
115580      pOut = aRight;
115581      fts3DoclistMerge(
115582          mt, nDist, 0, pOut, &nOut, aLeft, nLeft, aRight, nRight, &nDoc
115583      );
115584      sqlite3_free(aLeft);
115585    }
115586    assert( nOut==0 || pOut!=0 );
115587  }
115588
115589  if( rc==SQLITE_OK ){
115590    if( ii!=pPhrase->nToken ){
115591      assert( pCsr->eEvalmode==FTS3_EVAL_FILTER && isReqPos==0 );
115592      fts3DoclistStripPositions(pOut, &nOut);
115593    }
115594    *paOut = pOut;
115595    *pnOut = nOut;
115596  }else{
115597    sqlite3_free(pOut);
115598  }
115599  return rc;
115600}
115601
115602/*
115603** This function merges two doclists according to the requirements of a
115604** NEAR operator.
115605**
115606** Both input doclists must include position information. The output doclist
115607** includes position information if the first argument to this function
115608** is MERGE_POS_NEAR, or does not if it is MERGE_NEAR.
115609*/
115610static int fts3NearMerge(
115611  int mergetype,                  /* MERGE_POS_NEAR or MERGE_NEAR */
115612  int nNear,                      /* Parameter to NEAR operator */
115613  int nTokenLeft,                 /* Number of tokens in LHS phrase arg */
115614  char *aLeft,                    /* Doclist for LHS (incl. positions) */
115615  int nLeft,                      /* Size of LHS doclist in bytes */
115616  int nTokenRight,                /* As nTokenLeft */
115617  char *aRight,                   /* As aLeft */
115618  int nRight,                     /* As nRight */
115619  char **paOut,                   /* OUT: Results of merge (malloced) */
115620  int *pnOut                      /* OUT: Sized of output buffer */
115621){
115622  char *aOut;                     /* Buffer to write output doclist to */
115623  int rc;                         /* Return code */
115624
115625  assert( mergetype==MERGE_POS_NEAR || MERGE_NEAR );
115626
115627  aOut = sqlite3_malloc(nLeft+nRight+1);
115628  if( aOut==0 ){
115629    rc = SQLITE_NOMEM;
115630  }else{
115631    rc = fts3DoclistMerge(mergetype, nNear+nTokenRight, nNear+nTokenLeft,
115632      aOut, pnOut, aLeft, nLeft, aRight, nRight, 0
115633    );
115634    if( rc!=SQLITE_OK ){
115635      sqlite3_free(aOut);
115636      aOut = 0;
115637    }
115638  }
115639
115640  *paOut = aOut;
115641  return rc;
115642}
115643
115644/*
115645** This function is used as part of the processing for the snippet() and
115646** offsets() functions.
115647**
115648** Both pLeft and pRight are expression nodes of type FTSQUERY_PHRASE. Both
115649** have their respective doclists (including position information) loaded
115650** in Fts3Expr.aDoclist/nDoclist. This function removes all entries from
115651** each doclist that are not within nNear tokens of a corresponding entry
115652** in the other doclist.
115653*/
115654SQLITE_PRIVATE int sqlite3Fts3ExprNearTrim(Fts3Expr *pLeft, Fts3Expr *pRight, int nNear){
115655  int rc;                         /* Return code */
115656
115657  assert( pLeft->eType==FTSQUERY_PHRASE );
115658  assert( pRight->eType==FTSQUERY_PHRASE );
115659  assert( pLeft->isLoaded && pRight->isLoaded );
115660
115661  if( pLeft->aDoclist==0 || pRight->aDoclist==0 ){
115662    sqlite3_free(pLeft->aDoclist);
115663    sqlite3_free(pRight->aDoclist);
115664    pRight->aDoclist = 0;
115665    pLeft->aDoclist = 0;
115666    rc = SQLITE_OK;
115667  }else{
115668    char *aOut;                   /* Buffer in which to assemble new doclist */
115669    int nOut;                     /* Size of buffer aOut in bytes */
115670
115671    rc = fts3NearMerge(MERGE_POS_NEAR, nNear,
115672        pLeft->pPhrase->nToken, pLeft->aDoclist, pLeft->nDoclist,
115673        pRight->pPhrase->nToken, pRight->aDoclist, pRight->nDoclist,
115674        &aOut, &nOut
115675    );
115676    if( rc!=SQLITE_OK ) return rc;
115677    sqlite3_free(pRight->aDoclist);
115678    pRight->aDoclist = aOut;
115679    pRight->nDoclist = nOut;
115680
115681    rc = fts3NearMerge(MERGE_POS_NEAR, nNear,
115682        pRight->pPhrase->nToken, pRight->aDoclist, pRight->nDoclist,
115683        pLeft->pPhrase->nToken, pLeft->aDoclist, pLeft->nDoclist,
115684        &aOut, &nOut
115685    );
115686    sqlite3_free(pLeft->aDoclist);
115687    pLeft->aDoclist = aOut;
115688    pLeft->nDoclist = nOut;
115689  }
115690  return rc;
115691}
115692
115693
115694/*
115695** Allocate an Fts3SegReaderArray for each token in the expression pExpr.
115696** The allocated objects are stored in the Fts3PhraseToken.pArray member
115697** variables of each token structure.
115698*/
115699static int fts3ExprAllocateSegReaders(
115700  Fts3Cursor *pCsr,               /* FTS3 table */
115701  Fts3Expr *pExpr,                /* Expression to create seg-readers for */
115702  int *pnExpr                     /* OUT: Number of AND'd expressions */
115703){
115704  int rc = SQLITE_OK;             /* Return code */
115705
115706  assert( pCsr->eEvalmode==FTS3_EVAL_FILTER );
115707  if( pnExpr && pExpr->eType!=FTSQUERY_AND ){
115708    (*pnExpr)++;
115709    pnExpr = 0;
115710  }
115711
115712  if( pExpr->eType==FTSQUERY_PHRASE ){
115713    Fts3Phrase *pPhrase = pExpr->pPhrase;
115714    int ii;
115715
115716    for(ii=0; rc==SQLITE_OK && ii<pPhrase->nToken; ii++){
115717      Fts3PhraseToken *pTok = &pPhrase->aToken[ii];
115718      if( pTok->pSegcsr==0 ){
115719        rc = fts3TermSegReaderCursor(
115720            pCsr, pTok->z, pTok->n, pTok->isPrefix, &pTok->pSegcsr
115721        );
115722      }
115723    }
115724  }else{
115725    rc = fts3ExprAllocateSegReaders(pCsr, pExpr->pLeft, pnExpr);
115726    if( rc==SQLITE_OK ){
115727      rc = fts3ExprAllocateSegReaders(pCsr, pExpr->pRight, pnExpr);
115728    }
115729  }
115730  return rc;
115731}
115732
115733/*
115734** Free the Fts3SegReaderArray objects associated with each token in the
115735** expression pExpr. In other words, this function frees the resources
115736** allocated by fts3ExprAllocateSegReaders().
115737*/
115738static void fts3ExprFreeSegReaders(Fts3Expr *pExpr){
115739  if( pExpr ){
115740    Fts3Phrase *pPhrase = pExpr->pPhrase;
115741    if( pPhrase ){
115742      int kk;
115743      for(kk=0; kk<pPhrase->nToken; kk++){
115744        fts3SegReaderCursorFree(pPhrase->aToken[kk].pSegcsr);
115745        pPhrase->aToken[kk].pSegcsr = 0;
115746      }
115747    }
115748    fts3ExprFreeSegReaders(pExpr->pLeft);
115749    fts3ExprFreeSegReaders(pExpr->pRight);
115750  }
115751}
115752
115753/*
115754** Return the sum of the costs of all tokens in the expression pExpr. This
115755** function must be called after Fts3SegReaderArrays have been allocated
115756** for all tokens using fts3ExprAllocateSegReaders().
115757*/
115758static int fts3ExprCost(Fts3Expr *pExpr){
115759  int nCost;                      /* Return value */
115760  if( pExpr->eType==FTSQUERY_PHRASE ){
115761    Fts3Phrase *pPhrase = pExpr->pPhrase;
115762    int ii;
115763    nCost = 0;
115764    for(ii=0; ii<pPhrase->nToken; ii++){
115765      Fts3SegReaderCursor *pSegcsr = pPhrase->aToken[ii].pSegcsr;
115766      if( pSegcsr ) nCost += pSegcsr->nCost;
115767    }
115768  }else{
115769    nCost = fts3ExprCost(pExpr->pLeft) + fts3ExprCost(pExpr->pRight);
115770  }
115771  return nCost;
115772}
115773
115774/*
115775** The following is a helper function (and type) for fts3EvalExpr(). It
115776** must be called after Fts3SegReaders have been allocated for every token
115777** in the expression. See the context it is called from in fts3EvalExpr()
115778** for further explanation.
115779*/
115780typedef struct ExprAndCost ExprAndCost;
115781struct ExprAndCost {
115782  Fts3Expr *pExpr;
115783  int nCost;
115784};
115785static void fts3ExprAssignCosts(
115786  Fts3Expr *pExpr,                /* Expression to create seg-readers for */
115787  ExprAndCost **ppExprCost        /* OUT: Write to *ppExprCost */
115788){
115789  if( pExpr->eType==FTSQUERY_AND ){
115790    fts3ExprAssignCosts(pExpr->pLeft, ppExprCost);
115791    fts3ExprAssignCosts(pExpr->pRight, ppExprCost);
115792  }else{
115793    (*ppExprCost)->pExpr = pExpr;
115794    (*ppExprCost)->nCost = fts3ExprCost(pExpr);
115795    (*ppExprCost)++;
115796  }
115797}
115798
115799/*
115800** Evaluate the full-text expression pExpr against FTS3 table pTab. Store
115801** the resulting doclist in *paOut and *pnOut. This routine mallocs for
115802** the space needed to store the output. The caller is responsible for
115803** freeing the space when it has finished.
115804**
115805** This function is called in two distinct contexts:
115806**
115807**   * From within the virtual table xFilter() method. In this case, the
115808**     output doclist contains entries for all rows in the table, based on
115809**     data read from the full-text index.
115810**
115811**     In this case, if the query expression contains one or more tokens that
115812**     are very common, then the returned doclist may contain a superset of
115813**     the documents that actually match the expression.
115814**
115815**   * From within the virtual table xNext() method. This call is only made
115816**     if the call from within xFilter() found that there were very common
115817**     tokens in the query expression and did return a superset of the
115818**     matching documents. In this case the returned doclist contains only
115819**     entries that correspond to the current row of the table. Instead of
115820**     reading the data for each token from the full-text index, the data is
115821**     already available in-memory in the Fts3PhraseToken.pDeferred structures.
115822**     See fts3EvalDeferred() for how it gets there.
115823**
115824** In the first case above, Fts3Cursor.doDeferred==0. In the second (if it is
115825** required) Fts3Cursor.doDeferred==1.
115826**
115827** If the SQLite invokes the snippet(), offsets() or matchinfo() function
115828** as part of a SELECT on an FTS3 table, this function is called on each
115829** individual phrase expression in the query. If there were very common tokens
115830** found in the xFilter() call, then this function is called once for phrase
115831** for each row visited, and the returned doclist contains entries for the
115832** current row only. Otherwise, if there were no very common tokens, then this
115833** function is called once only for each phrase in the query and the returned
115834** doclist contains entries for all rows of the table.
115835**
115836** Fts3Cursor.doDeferred==1 when this function is called on phrases as a
115837** result of a snippet(), offsets() or matchinfo() invocation.
115838*/
115839static int fts3EvalExpr(
115840  Fts3Cursor *p,                  /* Virtual table cursor handle */
115841  Fts3Expr *pExpr,                /* Parsed fts3 expression */
115842  char **paOut,                   /* OUT: Pointer to malloc'd result buffer */
115843  int *pnOut,                     /* OUT: Size of buffer at *paOut */
115844  int isReqPos                    /* Require positions in output buffer */
115845){
115846  int rc = SQLITE_OK;             /* Return code */
115847
115848  /* Zero the output parameters. */
115849  *paOut = 0;
115850  *pnOut = 0;
115851
115852  if( pExpr ){
115853    assert( pExpr->eType==FTSQUERY_NEAR   || pExpr->eType==FTSQUERY_OR
115854         || pExpr->eType==FTSQUERY_AND    || pExpr->eType==FTSQUERY_NOT
115855         || pExpr->eType==FTSQUERY_PHRASE
115856    );
115857    assert( pExpr->eType==FTSQUERY_PHRASE || isReqPos==0 );
115858
115859    if( pExpr->eType==FTSQUERY_PHRASE ){
115860      rc = fts3PhraseSelect(p, pExpr->pPhrase,
115861          isReqPos || (pExpr->pParent && pExpr->pParent->eType==FTSQUERY_NEAR),
115862          paOut, pnOut
115863      );
115864      fts3ExprFreeSegReaders(pExpr);
115865    }else if( p->eEvalmode==FTS3_EVAL_FILTER && pExpr->eType==FTSQUERY_AND ){
115866      ExprAndCost *aExpr = 0;     /* Array of AND'd expressions and costs */
115867      int nExpr = 0;              /* Size of aExpr[] */
115868      char *aRet = 0;             /* Doclist to return to caller */
115869      int nRet = 0;               /* Length of aRet[] in bytes */
115870      int nDoc = 0x7FFFFFFF;
115871
115872      assert( !isReqPos );
115873
115874      rc = fts3ExprAllocateSegReaders(p, pExpr, &nExpr);
115875      if( rc==SQLITE_OK ){
115876        assert( nExpr>1 );
115877        aExpr = sqlite3_malloc(sizeof(ExprAndCost) * nExpr);
115878        if( !aExpr ) rc = SQLITE_NOMEM;
115879      }
115880      if( rc==SQLITE_OK ){
115881        int ii;                   /* Used to iterate through expressions */
115882
115883        fts3ExprAssignCosts(pExpr, &aExpr);
115884        aExpr -= nExpr;
115885        for(ii=0; ii<nExpr; ii++){
115886          char *aNew;
115887          int nNew;
115888          int jj;
115889          ExprAndCost *pBest = 0;
115890
115891          for(jj=0; jj<nExpr; jj++){
115892            ExprAndCost *pCand = &aExpr[jj];
115893            if( pCand->pExpr && (pBest==0 || pCand->nCost<pBest->nCost) ){
115894              pBest = pCand;
115895            }
115896          }
115897
115898          if( pBest->nCost>nDoc ){
115899            rc = fts3DeferExpression(p, p->pExpr);
115900            break;
115901          }else{
115902            rc = fts3EvalExpr(p, pBest->pExpr, &aNew, &nNew, 0);
115903            if( rc!=SQLITE_OK ) break;
115904            pBest->pExpr = 0;
115905            if( ii==0 ){
115906              aRet = aNew;
115907              nRet = nNew;
115908              nDoc = fts3DoclistCountDocids(0, aRet, nRet);
115909            }else{
115910              fts3DoclistMerge(
115911                  MERGE_AND, 0, 0, aRet, &nRet, aRet, nRet, aNew, nNew, &nDoc
115912              );
115913              sqlite3_free(aNew);
115914            }
115915          }
115916        }
115917      }
115918
115919      if( rc==SQLITE_OK ){
115920        *paOut = aRet;
115921        *pnOut = nRet;
115922      }else{
115923        assert( *paOut==0 );
115924        sqlite3_free(aRet);
115925      }
115926      sqlite3_free(aExpr);
115927      fts3ExprFreeSegReaders(pExpr);
115928
115929    }else{
115930      char *aLeft;
115931      char *aRight;
115932      int nLeft;
115933      int nRight;
115934
115935      assert( pExpr->eType==FTSQUERY_NEAR
115936           || pExpr->eType==FTSQUERY_OR
115937           || pExpr->eType==FTSQUERY_NOT
115938           || (pExpr->eType==FTSQUERY_AND && p->eEvalmode==FTS3_EVAL_NEXT)
115939      );
115940
115941      if( 0==(rc = fts3EvalExpr(p, pExpr->pRight, &aRight, &nRight, isReqPos))
115942       && 0==(rc = fts3EvalExpr(p, pExpr->pLeft, &aLeft, &nLeft, isReqPos))
115943      ){
115944        switch( pExpr->eType ){
115945          case FTSQUERY_NEAR: {
115946            Fts3Expr *pLeft;
115947            Fts3Expr *pRight;
115948            int mergetype = MERGE_NEAR;
115949            if( pExpr->pParent && pExpr->pParent->eType==FTSQUERY_NEAR ){
115950              mergetype = MERGE_POS_NEAR;
115951            }
115952            pLeft = pExpr->pLeft;
115953            while( pLeft->eType==FTSQUERY_NEAR ){
115954              pLeft=pLeft->pRight;
115955            }
115956            pRight = pExpr->pRight;
115957            assert( pRight->eType==FTSQUERY_PHRASE );
115958            assert( pLeft->eType==FTSQUERY_PHRASE );
115959
115960            rc = fts3NearMerge(mergetype, pExpr->nNear,
115961                pLeft->pPhrase->nToken, aLeft, nLeft,
115962                pRight->pPhrase->nToken, aRight, nRight,
115963                paOut, pnOut
115964            );
115965            sqlite3_free(aLeft);
115966            break;
115967          }
115968
115969          case FTSQUERY_OR: {
115970            /* Allocate a buffer for the output. The maximum size is the
115971            ** sum of the sizes of the two input buffers. The +1 term is
115972            ** so that a buffer of zero bytes is never allocated - this can
115973            ** cause fts3DoclistMerge() to incorrectly return SQLITE_NOMEM.
115974            */
115975            char *aBuffer = sqlite3_malloc(nRight+nLeft+1);
115976            rc = fts3DoclistMerge(MERGE_OR, 0, 0, aBuffer, pnOut,
115977                aLeft, nLeft, aRight, nRight, 0
115978            );
115979            *paOut = aBuffer;
115980            sqlite3_free(aLeft);
115981            break;
115982          }
115983
115984          default: {
115985            assert( FTSQUERY_NOT==MERGE_NOT && FTSQUERY_AND==MERGE_AND );
115986            fts3DoclistMerge(pExpr->eType, 0, 0, aLeft, pnOut,
115987                aLeft, nLeft, aRight, nRight, 0
115988            );
115989            *paOut = aLeft;
115990            break;
115991          }
115992        }
115993      }
115994      sqlite3_free(aRight);
115995    }
115996  }
115997
115998  assert( rc==SQLITE_OK || *paOut==0 );
115999  return rc;
116000}
116001
116002/*
116003** This function is called from within xNext() for each row visited by
116004** an FTS3 query. If evaluating the FTS3 query expression within xFilter()
116005** was able to determine the exact set of matching rows, this function sets
116006** *pbRes to true and returns SQLITE_IO immediately.
116007**
116008** Otherwise, if evaluating the query expression within xFilter() returned a
116009** superset of the matching documents instead of an exact set (this happens
116010** when the query includes very common tokens and it is deemed too expensive to
116011** load their doclists from disk), this function tests if the current row
116012** really does match the FTS3 query.
116013**
116014** If an error occurs, an SQLite error code is returned. Otherwise, SQLITE_OK
116015** is returned and *pbRes is set to true if the current row matches the
116016** FTS3 query (and should be included in the results returned to SQLite), or
116017** false otherwise.
116018*/
116019static int fts3EvalDeferred(
116020  Fts3Cursor *pCsr,               /* FTS3 cursor pointing at row to test */
116021  int *pbRes                      /* OUT: Set to true if row is a match */
116022){
116023  int rc = SQLITE_OK;
116024  if( pCsr->pDeferred==0 ){
116025    *pbRes = 1;
116026  }else{
116027    rc = fts3CursorSeek(0, pCsr);
116028    if( rc==SQLITE_OK ){
116029      sqlite3Fts3FreeDeferredDoclists(pCsr);
116030      rc = sqlite3Fts3CacheDeferredDoclists(pCsr);
116031    }
116032    if( rc==SQLITE_OK ){
116033      char *a = 0;
116034      int n = 0;
116035      rc = fts3EvalExpr(pCsr, pCsr->pExpr, &a, &n, 0);
116036      assert( n>=0 );
116037      *pbRes = (n>0);
116038      sqlite3_free(a);
116039    }
116040  }
116041  return rc;
116042}
116043
116044/*
116045** Advance the cursor to the next row in the %_content table that
116046** matches the search criteria.  For a MATCH search, this will be
116047** the next row that matches. For a full-table scan, this will be
116048** simply the next row in the %_content table.  For a docid lookup,
116049** this routine simply sets the EOF flag.
116050**
116051** Return SQLITE_OK if nothing goes wrong.  SQLITE_OK is returned
116052** even if we reach end-of-file.  The fts3EofMethod() will be called
116053** subsequently to determine whether or not an EOF was hit.
116054*/
116055static int fts3NextMethod(sqlite3_vtab_cursor *pCursor){
116056  int res;
116057  int rc = SQLITE_OK;             /* Return code */
116058  Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
116059
116060  pCsr->eEvalmode = FTS3_EVAL_NEXT;
116061  do {
116062    if( pCsr->aDoclist==0 ){
116063      if( SQLITE_ROW!=sqlite3_step(pCsr->pStmt) ){
116064        pCsr->isEof = 1;
116065        rc = sqlite3_reset(pCsr->pStmt);
116066        break;
116067      }
116068      pCsr->iPrevId = sqlite3_column_int64(pCsr->pStmt, 0);
116069    }else{
116070      if( pCsr->pNextId>=&pCsr->aDoclist[pCsr->nDoclist] ){
116071        pCsr->isEof = 1;
116072        break;
116073      }
116074      sqlite3_reset(pCsr->pStmt);
116075      fts3GetDeltaVarint(&pCsr->pNextId, &pCsr->iPrevId);
116076      pCsr->isRequireSeek = 1;
116077      pCsr->isMatchinfoNeeded = 1;
116078    }
116079  }while( SQLITE_OK==(rc = fts3EvalDeferred(pCsr, &res)) && res==0 );
116080
116081  return rc;
116082}
116083
116084/*
116085** This is the xFilter interface for the virtual table.  See
116086** the virtual table xFilter method documentation for additional
116087** information.
116088**
116089** If idxNum==FTS3_FULLSCAN_SEARCH then do a full table scan against
116090** the %_content table.
116091**
116092** If idxNum==FTS3_DOCID_SEARCH then do a docid lookup for a single entry
116093** in the %_content table.
116094**
116095** If idxNum>=FTS3_FULLTEXT_SEARCH then use the full text index.  The
116096** column on the left-hand side of the MATCH operator is column
116097** number idxNum-FTS3_FULLTEXT_SEARCH, 0 indexed.  argv[0] is the right-hand
116098** side of the MATCH operator.
116099*/
116100static int fts3FilterMethod(
116101  sqlite3_vtab_cursor *pCursor,   /* The cursor used for this query */
116102  int idxNum,                     /* Strategy index */
116103  const char *idxStr,             /* Unused */
116104  int nVal,                       /* Number of elements in apVal */
116105  sqlite3_value **apVal           /* Arguments for the indexing scheme */
116106){
116107  const char *azSql[] = {
116108    "SELECT %s FROM %Q.'%q_content' AS x WHERE docid = ?", /* non-full-scan */
116109    "SELECT %s FROM %Q.'%q_content' AS x ",                /* full-scan */
116110  };
116111  int rc;                         /* Return code */
116112  char *zSql;                     /* SQL statement used to access %_content */
116113  Fts3Table *p = (Fts3Table *)pCursor->pVtab;
116114  Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
116115
116116  UNUSED_PARAMETER(idxStr);
116117  UNUSED_PARAMETER(nVal);
116118
116119  assert( idxNum>=0 && idxNum<=(FTS3_FULLTEXT_SEARCH+p->nColumn) );
116120  assert( nVal==0 || nVal==1 );
116121  assert( (nVal==0)==(idxNum==FTS3_FULLSCAN_SEARCH) );
116122  assert( p->pSegments==0 );
116123
116124  /* In case the cursor has been used before, clear it now. */
116125  sqlite3_finalize(pCsr->pStmt);
116126  sqlite3_free(pCsr->aDoclist);
116127  sqlite3Fts3ExprFree(pCsr->pExpr);
116128  memset(&pCursor[1], 0, sizeof(Fts3Cursor)-sizeof(sqlite3_vtab_cursor));
116129
116130  if( idxNum!=FTS3_DOCID_SEARCH && idxNum!=FTS3_FULLSCAN_SEARCH ){
116131    int iCol = idxNum-FTS3_FULLTEXT_SEARCH;
116132    const char *zQuery = (const char *)sqlite3_value_text(apVal[0]);
116133
116134    if( zQuery==0 && sqlite3_value_type(apVal[0])!=SQLITE_NULL ){
116135      return SQLITE_NOMEM;
116136    }
116137
116138    rc = sqlite3Fts3ExprParse(p->pTokenizer, p->azColumn, p->nColumn,
116139        iCol, zQuery, -1, &pCsr->pExpr
116140    );
116141    if( rc!=SQLITE_OK ){
116142      if( rc==SQLITE_ERROR ){
116143        p->base.zErrMsg = sqlite3_mprintf("malformed MATCH expression: [%s]",
116144                                          zQuery);
116145      }
116146      return rc;
116147    }
116148
116149    rc = sqlite3Fts3ReadLock(p);
116150    if( rc!=SQLITE_OK ) return rc;
116151
116152    rc = fts3EvalExpr(pCsr, pCsr->pExpr, &pCsr->aDoclist, &pCsr->nDoclist, 0);
116153    sqlite3Fts3SegmentsClose(p);
116154    if( rc!=SQLITE_OK ) return rc;
116155    pCsr->pNextId = pCsr->aDoclist;
116156    pCsr->iPrevId = 0;
116157  }
116158
116159  /* Compile a SELECT statement for this cursor. For a full-table-scan, the
116160  ** statement loops through all rows of the %_content table. For a
116161  ** full-text query or docid lookup, the statement retrieves a single
116162  ** row by docid.
116163  */
116164  zSql = (char *)azSql[idxNum==FTS3_FULLSCAN_SEARCH];
116165  zSql = sqlite3_mprintf(zSql, p->zReadExprlist, p->zDb, p->zName);
116166  if( !zSql ){
116167    rc = SQLITE_NOMEM;
116168  }else{
116169    rc = sqlite3_prepare_v2(p->db, zSql, -1, &pCsr->pStmt, 0);
116170    sqlite3_free(zSql);
116171  }
116172  if( rc==SQLITE_OK && idxNum==FTS3_DOCID_SEARCH ){
116173    rc = sqlite3_bind_value(pCsr->pStmt, 1, apVal[0]);
116174  }
116175  pCsr->eSearch = (i16)idxNum;
116176
116177  if( rc!=SQLITE_OK ) return rc;
116178  return fts3NextMethod(pCursor);
116179}
116180
116181/*
116182** This is the xEof method of the virtual table. SQLite calls this
116183** routine to find out if it has reached the end of a result set.
116184*/
116185static int fts3EofMethod(sqlite3_vtab_cursor *pCursor){
116186  return ((Fts3Cursor *)pCursor)->isEof;
116187}
116188
116189/*
116190** This is the xRowid method. The SQLite core calls this routine to
116191** retrieve the rowid for the current row of the result set. fts3
116192** exposes %_content.docid as the rowid for the virtual table. The
116193** rowid should be written to *pRowid.
116194*/
116195static int fts3RowidMethod(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){
116196  Fts3Cursor *pCsr = (Fts3Cursor *) pCursor;
116197  if( pCsr->aDoclist ){
116198    *pRowid = pCsr->iPrevId;
116199  }else{
116200    /* This branch runs if the query is implemented using a full-table scan
116201    ** (not using the full-text index). In this case grab the rowid from the
116202    ** SELECT statement.
116203    */
116204    assert( pCsr->isRequireSeek==0 );
116205    *pRowid = sqlite3_column_int64(pCsr->pStmt, 0);
116206  }
116207  return SQLITE_OK;
116208}
116209
116210/*
116211** This is the xColumn method, called by SQLite to request a value from
116212** the row that the supplied cursor currently points to.
116213*/
116214static int fts3ColumnMethod(
116215  sqlite3_vtab_cursor *pCursor,   /* Cursor to retrieve value from */
116216  sqlite3_context *pContext,      /* Context for sqlite3_result_xxx() calls */
116217  int iCol                        /* Index of column to read value from */
116218){
116219  int rc;                         /* Return Code */
116220  Fts3Cursor *pCsr = (Fts3Cursor *) pCursor;
116221  Fts3Table *p = (Fts3Table *)pCursor->pVtab;
116222
116223  /* The column value supplied by SQLite must be in range. */
116224  assert( iCol>=0 && iCol<=p->nColumn+1 );
116225
116226  if( iCol==p->nColumn+1 ){
116227    /* This call is a request for the "docid" column. Since "docid" is an
116228    ** alias for "rowid", use the xRowid() method to obtain the value.
116229    */
116230    sqlite3_int64 iRowid;
116231    rc = fts3RowidMethod(pCursor, &iRowid);
116232    sqlite3_result_int64(pContext, iRowid);
116233  }else if( iCol==p->nColumn ){
116234    /* The extra column whose name is the same as the table.
116235    ** Return a blob which is a pointer to the cursor.
116236    */
116237    sqlite3_result_blob(pContext, &pCsr, sizeof(pCsr), SQLITE_TRANSIENT);
116238    rc = SQLITE_OK;
116239  }else{
116240    rc = fts3CursorSeek(0, pCsr);
116241    if( rc==SQLITE_OK ){
116242      sqlite3_result_value(pContext, sqlite3_column_value(pCsr->pStmt, iCol+1));
116243    }
116244  }
116245  return rc;
116246}
116247
116248/*
116249** This function is the implementation of the xUpdate callback used by
116250** FTS3 virtual tables. It is invoked by SQLite each time a row is to be
116251** inserted, updated or deleted.
116252*/
116253static int fts3UpdateMethod(
116254  sqlite3_vtab *pVtab,            /* Virtual table handle */
116255  int nArg,                       /* Size of argument array */
116256  sqlite3_value **apVal,          /* Array of arguments */
116257  sqlite_int64 *pRowid            /* OUT: The affected (or effected) rowid */
116258){
116259  return sqlite3Fts3UpdateMethod(pVtab, nArg, apVal, pRowid);
116260}
116261
116262/*
116263** Implementation of xSync() method. Flush the contents of the pending-terms
116264** hash-table to the database.
116265*/
116266static int fts3SyncMethod(sqlite3_vtab *pVtab){
116267  int rc = sqlite3Fts3PendingTermsFlush((Fts3Table *)pVtab);
116268  sqlite3Fts3SegmentsClose((Fts3Table *)pVtab);
116269  return rc;
116270}
116271
116272/*
116273** Implementation of xBegin() method. This is a no-op.
116274*/
116275static int fts3BeginMethod(sqlite3_vtab *pVtab){
116276  UNUSED_PARAMETER(pVtab);
116277  assert( ((Fts3Table *)pVtab)->nPendingData==0 );
116278  return SQLITE_OK;
116279}
116280
116281/*
116282** Implementation of xCommit() method. This is a no-op. The contents of
116283** the pending-terms hash-table have already been flushed into the database
116284** by fts3SyncMethod().
116285*/
116286static int fts3CommitMethod(sqlite3_vtab *pVtab){
116287  UNUSED_PARAMETER(pVtab);
116288  assert( ((Fts3Table *)pVtab)->nPendingData==0 );
116289  return SQLITE_OK;
116290}
116291
116292/*
116293** Implementation of xRollback(). Discard the contents of the pending-terms
116294** hash-table. Any changes made to the database are reverted by SQLite.
116295*/
116296static int fts3RollbackMethod(sqlite3_vtab *pVtab){
116297  sqlite3Fts3PendingTermsClear((Fts3Table *)pVtab);
116298  return SQLITE_OK;
116299}
116300
116301/*
116302** Load the doclist associated with expression pExpr to pExpr->aDoclist.
116303** The loaded doclist contains positions as well as the document ids.
116304** This is used by the matchinfo(), snippet() and offsets() auxillary
116305** functions.
116306*/
116307SQLITE_PRIVATE int sqlite3Fts3ExprLoadDoclist(Fts3Cursor *pCsr, Fts3Expr *pExpr){
116308  int rc;
116309  assert( pExpr->eType==FTSQUERY_PHRASE && pExpr->pPhrase );
116310  assert( pCsr->eEvalmode==FTS3_EVAL_NEXT );
116311  rc = fts3EvalExpr(pCsr, pExpr, &pExpr->aDoclist, &pExpr->nDoclist, 1);
116312  return rc;
116313}
116314
116315SQLITE_PRIVATE int sqlite3Fts3ExprLoadFtDoclist(
116316  Fts3Cursor *pCsr,
116317  Fts3Expr *pExpr,
116318  char **paDoclist,
116319  int *pnDoclist
116320){
116321  int rc;
116322  assert( pCsr->eEvalmode==FTS3_EVAL_NEXT );
116323  assert( pExpr->eType==FTSQUERY_PHRASE && pExpr->pPhrase );
116324  pCsr->eEvalmode = FTS3_EVAL_MATCHINFO;
116325  rc = fts3EvalExpr(pCsr, pExpr, paDoclist, pnDoclist, 1);
116326  pCsr->eEvalmode = FTS3_EVAL_NEXT;
116327  return rc;
116328}
116329
116330/*
116331** After ExprLoadDoclist() (see above) has been called, this function is
116332** used to iterate/search through the position lists that make up the doclist
116333** stored in pExpr->aDoclist.
116334*/
116335SQLITE_PRIVATE char *sqlite3Fts3FindPositions(
116336  Fts3Expr *pExpr,                /* Access this expressions doclist */
116337  sqlite3_int64 iDocid,           /* Docid associated with requested pos-list */
116338  int iCol                        /* Column of requested pos-list */
116339){
116340  assert( pExpr->isLoaded );
116341  if( pExpr->aDoclist ){
116342    char *pEnd = &pExpr->aDoclist[pExpr->nDoclist];
116343    char *pCsr;
116344
116345    if( pExpr->pCurrent==0 ){
116346      pExpr->pCurrent = pExpr->aDoclist;
116347      pExpr->iCurrent = 0;
116348      pExpr->pCurrent += sqlite3Fts3GetVarint(pExpr->pCurrent,&pExpr->iCurrent);
116349    }
116350    pCsr = pExpr->pCurrent;
116351    assert( pCsr );
116352
116353    while( pCsr<pEnd ){
116354      if( pExpr->iCurrent<iDocid ){
116355        fts3PoslistCopy(0, &pCsr);
116356        if( pCsr<pEnd ){
116357          fts3GetDeltaVarint(&pCsr, &pExpr->iCurrent);
116358        }
116359        pExpr->pCurrent = pCsr;
116360      }else{
116361        if( pExpr->iCurrent==iDocid ){
116362          int iThis = 0;
116363          if( iCol<0 ){
116364            /* If iCol is negative, return a pointer to the start of the
116365            ** position-list (instead of a pointer to the start of a list
116366            ** of offsets associated with a specific column).
116367            */
116368            return pCsr;
116369          }
116370          while( iThis<iCol ){
116371            fts3ColumnlistCopy(0, &pCsr);
116372            if( *pCsr==0x00 ) return 0;
116373            pCsr++;
116374            pCsr += sqlite3Fts3GetVarint32(pCsr, &iThis);
116375          }
116376          if( iCol==iThis && (*pCsr&0xFE) ) return pCsr;
116377        }
116378        return 0;
116379      }
116380    }
116381  }
116382
116383  return 0;
116384}
116385
116386/*
116387** Helper function used by the implementation of the overloaded snippet(),
116388** offsets() and optimize() SQL functions.
116389**
116390** If the value passed as the third argument is a blob of size
116391** sizeof(Fts3Cursor*), then the blob contents are copied to the
116392** output variable *ppCsr and SQLITE_OK is returned. Otherwise, an error
116393** message is written to context pContext and SQLITE_ERROR returned. The
116394** string passed via zFunc is used as part of the error message.
116395*/
116396static int fts3FunctionArg(
116397  sqlite3_context *pContext,      /* SQL function call context */
116398  const char *zFunc,              /* Function name */
116399  sqlite3_value *pVal,            /* argv[0] passed to function */
116400  Fts3Cursor **ppCsr              /* OUT: Store cursor handle here */
116401){
116402  Fts3Cursor *pRet;
116403  if( sqlite3_value_type(pVal)!=SQLITE_BLOB
116404   || sqlite3_value_bytes(pVal)!=sizeof(Fts3Cursor *)
116405  ){
116406    char *zErr = sqlite3_mprintf("illegal first argument to %s", zFunc);
116407    sqlite3_result_error(pContext, zErr, -1);
116408    sqlite3_free(zErr);
116409    return SQLITE_ERROR;
116410  }
116411  memcpy(&pRet, sqlite3_value_blob(pVal), sizeof(Fts3Cursor *));
116412  *ppCsr = pRet;
116413  return SQLITE_OK;
116414}
116415
116416/*
116417** Implementation of the snippet() function for FTS3
116418*/
116419static void fts3SnippetFunc(
116420  sqlite3_context *pContext,      /* SQLite function call context */
116421  int nVal,                       /* Size of apVal[] array */
116422  sqlite3_value **apVal           /* Array of arguments */
116423){
116424  Fts3Cursor *pCsr;               /* Cursor handle passed through apVal[0] */
116425  const char *zStart = "<b>";
116426  const char *zEnd = "</b>";
116427  const char *zEllipsis = "<b>...</b>";
116428  int iCol = -1;
116429  int nToken = 15;                /* Default number of tokens in snippet */
116430
116431  /* There must be at least one argument passed to this function (otherwise
116432  ** the non-overloaded version would have been called instead of this one).
116433  */
116434  assert( nVal>=1 );
116435
116436  if( nVal>6 ){
116437    sqlite3_result_error(pContext,
116438        "wrong number of arguments to function snippet()", -1);
116439    return;
116440  }
116441  if( fts3FunctionArg(pContext, "snippet", apVal[0], &pCsr) ) return;
116442
116443  switch( nVal ){
116444    case 6: nToken = sqlite3_value_int(apVal[5]);
116445    case 5: iCol = sqlite3_value_int(apVal[4]);
116446    case 4: zEllipsis = (const char*)sqlite3_value_text(apVal[3]);
116447    case 3: zEnd = (const char*)sqlite3_value_text(apVal[2]);
116448    case 2: zStart = (const char*)sqlite3_value_text(apVal[1]);
116449  }
116450  if( !zEllipsis || !zEnd || !zStart ){
116451    sqlite3_result_error_nomem(pContext);
116452  }else if( SQLITE_OK==fts3CursorSeek(pContext, pCsr) ){
116453    sqlite3Fts3Snippet(pContext, pCsr, zStart, zEnd, zEllipsis, iCol, nToken);
116454  }
116455}
116456
116457/*
116458** Implementation of the offsets() function for FTS3
116459*/
116460static void fts3OffsetsFunc(
116461  sqlite3_context *pContext,      /* SQLite function call context */
116462  int nVal,                       /* Size of argument array */
116463  sqlite3_value **apVal           /* Array of arguments */
116464){
116465  Fts3Cursor *pCsr;               /* Cursor handle passed through apVal[0] */
116466
116467  UNUSED_PARAMETER(nVal);
116468
116469  assert( nVal==1 );
116470  if( fts3FunctionArg(pContext, "offsets", apVal[0], &pCsr) ) return;
116471  assert( pCsr );
116472  if( SQLITE_OK==fts3CursorSeek(pContext, pCsr) ){
116473    sqlite3Fts3Offsets(pContext, pCsr);
116474  }
116475}
116476
116477/*
116478** Implementation of the special optimize() function for FTS3. This
116479** function merges all segments in the database to a single segment.
116480** Example usage is:
116481**
116482**   SELECT optimize(t) FROM t LIMIT 1;
116483**
116484** where 't' is the name of an FTS3 table.
116485*/
116486static void fts3OptimizeFunc(
116487  sqlite3_context *pContext,      /* SQLite function call context */
116488  int nVal,                       /* Size of argument array */
116489  sqlite3_value **apVal           /* Array of arguments */
116490){
116491  int rc;                         /* Return code */
116492  Fts3Table *p;                   /* Virtual table handle */
116493  Fts3Cursor *pCursor;            /* Cursor handle passed through apVal[0] */
116494
116495  UNUSED_PARAMETER(nVal);
116496
116497  assert( nVal==1 );
116498  if( fts3FunctionArg(pContext, "optimize", apVal[0], &pCursor) ) return;
116499  p = (Fts3Table *)pCursor->base.pVtab;
116500  assert( p );
116501
116502  rc = sqlite3Fts3Optimize(p);
116503
116504  switch( rc ){
116505    case SQLITE_OK:
116506      sqlite3_result_text(pContext, "Index optimized", -1, SQLITE_STATIC);
116507      break;
116508    case SQLITE_DONE:
116509      sqlite3_result_text(pContext, "Index already optimal", -1, SQLITE_STATIC);
116510      break;
116511    default:
116512      sqlite3_result_error_code(pContext, rc);
116513      break;
116514  }
116515}
116516
116517/*
116518** Implementation of the matchinfo() function for FTS3
116519*/
116520static void fts3MatchinfoFunc(
116521  sqlite3_context *pContext,      /* SQLite function call context */
116522  int nVal,                       /* Size of argument array */
116523  sqlite3_value **apVal           /* Array of arguments */
116524){
116525  Fts3Cursor *pCsr;               /* Cursor handle passed through apVal[0] */
116526  assert( nVal==1 || nVal==2 );
116527  if( SQLITE_OK==fts3FunctionArg(pContext, "matchinfo", apVal[0], &pCsr) ){
116528    const char *zArg = 0;
116529    if( nVal>1 ){
116530      zArg = (const char *)sqlite3_value_text(apVal[1]);
116531    }
116532    sqlite3Fts3Matchinfo(pContext, pCsr, zArg);
116533  }
116534}
116535
116536/*
116537** This routine implements the xFindFunction method for the FTS3
116538** virtual table.
116539*/
116540static int fts3FindFunctionMethod(
116541  sqlite3_vtab *pVtab,            /* Virtual table handle */
116542  int nArg,                       /* Number of SQL function arguments */
116543  const char *zName,              /* Name of SQL function */
116544  void (**pxFunc)(sqlite3_context*,int,sqlite3_value**), /* OUT: Result */
116545  void **ppArg                    /* Unused */
116546){
116547  struct Overloaded {
116548    const char *zName;
116549    void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
116550  } aOverload[] = {
116551    { "snippet", fts3SnippetFunc },
116552    { "offsets", fts3OffsetsFunc },
116553    { "optimize", fts3OptimizeFunc },
116554    { "matchinfo", fts3MatchinfoFunc },
116555  };
116556  int i;                          /* Iterator variable */
116557
116558  UNUSED_PARAMETER(pVtab);
116559  UNUSED_PARAMETER(nArg);
116560  UNUSED_PARAMETER(ppArg);
116561
116562  for(i=0; i<SizeofArray(aOverload); i++){
116563    if( strcmp(zName, aOverload[i].zName)==0 ){
116564      *pxFunc = aOverload[i].xFunc;
116565      return 1;
116566    }
116567  }
116568
116569  /* No function of the specified name was found. Return 0. */
116570  return 0;
116571}
116572
116573/*
116574** Implementation of FTS3 xRename method. Rename an fts3 table.
116575*/
116576static int fts3RenameMethod(
116577  sqlite3_vtab *pVtab,            /* Virtual table handle */
116578  const char *zName               /* New name of table */
116579){
116580  Fts3Table *p = (Fts3Table *)pVtab;
116581  sqlite3 *db = p->db;            /* Database connection */
116582  int rc;                         /* Return Code */
116583
116584  rc = sqlite3Fts3PendingTermsFlush(p);
116585  if( rc!=SQLITE_OK ){
116586    return rc;
116587  }
116588
116589  fts3DbExec(&rc, db,
116590    "ALTER TABLE %Q.'%q_content'  RENAME TO '%q_content';",
116591    p->zDb, p->zName, zName
116592  );
116593  if( p->bHasDocsize ){
116594    fts3DbExec(&rc, db,
116595      "ALTER TABLE %Q.'%q_docsize'  RENAME TO '%q_docsize';",
116596      p->zDb, p->zName, zName
116597    );
116598  }
116599  if( p->bHasStat ){
116600    fts3DbExec(&rc, db,
116601      "ALTER TABLE %Q.'%q_stat'  RENAME TO '%q_stat';",
116602      p->zDb, p->zName, zName
116603    );
116604  }
116605  fts3DbExec(&rc, db,
116606    "ALTER TABLE %Q.'%q_segments' RENAME TO '%q_segments';",
116607    p->zDb, p->zName, zName
116608  );
116609  fts3DbExec(&rc, db,
116610    "ALTER TABLE %Q.'%q_segdir'   RENAME TO '%q_segdir';",
116611    p->zDb, p->zName, zName
116612  );
116613  return rc;
116614}
116615
116616static const sqlite3_module fts3Module = {
116617  /* iVersion      */ 0,
116618  /* xCreate       */ fts3CreateMethod,
116619  /* xConnect      */ fts3ConnectMethod,
116620  /* xBestIndex    */ fts3BestIndexMethod,
116621  /* xDisconnect   */ fts3DisconnectMethod,
116622  /* xDestroy      */ fts3DestroyMethod,
116623  /* xOpen         */ fts3OpenMethod,
116624  /* xClose        */ fts3CloseMethod,
116625  /* xFilter       */ fts3FilterMethod,
116626  /* xNext         */ fts3NextMethod,
116627  /* xEof          */ fts3EofMethod,
116628  /* xColumn       */ fts3ColumnMethod,
116629  /* xRowid        */ fts3RowidMethod,
116630  /* xUpdate       */ fts3UpdateMethod,
116631  /* xBegin        */ fts3BeginMethod,
116632  /* xSync         */ fts3SyncMethod,
116633  /* xCommit       */ fts3CommitMethod,
116634  /* xRollback     */ fts3RollbackMethod,
116635  /* xFindFunction */ fts3FindFunctionMethod,
116636  /* xRename */       fts3RenameMethod,
116637};
116638
116639/*
116640** This function is registered as the module destructor (called when an
116641** FTS3 enabled database connection is closed). It frees the memory
116642** allocated for the tokenizer hash table.
116643*/
116644static void hashDestroy(void *p){
116645  Fts3Hash *pHash = (Fts3Hash *)p;
116646  sqlite3Fts3HashClear(pHash);
116647  sqlite3_free(pHash);
116648}
116649
116650/*
116651** The fts3 built-in tokenizers - "simple", "porter" and "icu"- are
116652** implemented in files fts3_tokenizer1.c, fts3_porter.c and fts3_icu.c
116653** respectively. The following three forward declarations are for functions
116654** declared in these files used to retrieve the respective implementations.
116655**
116656** Calling sqlite3Fts3SimpleTokenizerModule() sets the value pointed
116657** to by the argument to point to the "simple" tokenizer implementation.
116658** And so on.
116659*/
116660SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule);
116661SQLITE_PRIVATE void sqlite3Fts3PorterTokenizerModule(sqlite3_tokenizer_module const**ppModule);
116662#ifdef SQLITE_ENABLE_ICU
116663SQLITE_PRIVATE void sqlite3Fts3IcuTokenizerModule(sqlite3_tokenizer_module const**ppModule);
116664#endif
116665
116666/*
116667** Initialise the fts3 extension. If this extension is built as part
116668** of the sqlite library, then this function is called directly by
116669** SQLite. If fts3 is built as a dynamically loadable extension, this
116670** function is called by the sqlite3_extension_init() entry point.
116671*/
116672SQLITE_PRIVATE int sqlite3Fts3Init(sqlite3 *db){
116673  int rc = SQLITE_OK;
116674  Fts3Hash *pHash = 0;
116675  const sqlite3_tokenizer_module *pSimple = 0;
116676  const sqlite3_tokenizer_module *pPorter = 0;
116677
116678#ifdef SQLITE_ENABLE_ICU
116679  const sqlite3_tokenizer_module *pIcu = 0;
116680  sqlite3Fts3IcuTokenizerModule(&pIcu);
116681#endif
116682
116683  rc = sqlite3Fts3InitAux(db);
116684  if( rc!=SQLITE_OK ) return rc;
116685
116686  sqlite3Fts3SimpleTokenizerModule(&pSimple);
116687  sqlite3Fts3PorterTokenizerModule(&pPorter);
116688
116689  /* Allocate and initialise the hash-table used to store tokenizers. */
116690  pHash = sqlite3_malloc(sizeof(Fts3Hash));
116691  if( !pHash ){
116692    rc = SQLITE_NOMEM;
116693  }else{
116694    sqlite3Fts3HashInit(pHash, FTS3_HASH_STRING, 1);
116695  }
116696
116697  /* Load the built-in tokenizers into the hash table */
116698  if( rc==SQLITE_OK ){
116699    if( sqlite3Fts3HashInsert(pHash, "simple", 7, (void *)pSimple)
116700     || sqlite3Fts3HashInsert(pHash, "porter", 7, (void *)pPorter)
116701#ifdef SQLITE_ENABLE_ICU
116702     || (pIcu && sqlite3Fts3HashInsert(pHash, "icu", 4, (void *)pIcu))
116703#endif
116704    ){
116705      rc = SQLITE_NOMEM;
116706    }
116707  }
116708
116709#ifdef SQLITE_TEST
116710  if( rc==SQLITE_OK ){
116711    rc = sqlite3Fts3ExprInitTestInterface(db);
116712  }
116713#endif
116714
116715  /* Create the virtual table wrapper around the hash-table and overload
116716  ** the two scalar functions. If this is successful, register the
116717  ** module with sqlite.
116718  */
116719  if( SQLITE_OK==rc
116720#if CHROMIUM_FTS3_CHANGES && !SQLITE_TEST
116721      /* fts3_tokenizer() disabled for security reasons. */
116722#else
116723   && SQLITE_OK==(rc = sqlite3Fts3InitHashTable(db, pHash, "fts3_tokenizer"))
116724#endif
116725   && SQLITE_OK==(rc = sqlite3_overload_function(db, "snippet", -1))
116726   && SQLITE_OK==(rc = sqlite3_overload_function(db, "offsets", 1))
116727   && SQLITE_OK==(rc = sqlite3_overload_function(db, "matchinfo", 1))
116728   && SQLITE_OK==(rc = sqlite3_overload_function(db, "matchinfo", 2))
116729   && SQLITE_OK==(rc = sqlite3_overload_function(db, "optimize", 1))
116730  ){
116731    rc = sqlite3_create_module_v2(
116732        db, "fts3", &fts3Module, (void *)pHash, hashDestroy
116733    );
116734#if CHROMIUM_FTS3_CHANGES && !SQLITE_TEST
116735    /* Disable fts4 pending review. */
116736#else
116737    if( rc==SQLITE_OK ){
116738      rc = sqlite3_create_module_v2(
116739          db, "fts4", &fts3Module, (void *)pHash, 0
116740      );
116741    }
116742#endif
116743    return rc;
116744  }
116745
116746  /* An error has occurred. Delete the hash table and return the error code. */
116747  assert( rc!=SQLITE_OK );
116748  if( pHash ){
116749    sqlite3Fts3HashClear(pHash);
116750    sqlite3_free(pHash);
116751  }
116752  return rc;
116753}
116754
116755#if !SQLITE_CORE
116756SQLITE_API int sqlite3_extension_init(
116757  sqlite3 *db,
116758  char **pzErrMsg,
116759  const sqlite3_api_routines *pApi
116760){
116761  SQLITE_EXTENSION_INIT2(pApi)
116762  return sqlite3Fts3Init(db);
116763}
116764#endif
116765
116766#endif
116767
116768/************** End of fts3.c ************************************************/
116769/************** Begin file fts3_aux.c ****************************************/
116770/*
116771** 2011 Jan 27
116772**
116773** The author disclaims copyright to this source code.  In place of
116774** a legal notice, here is a blessing:
116775**
116776**    May you do good and not evil.
116777**    May you find forgiveness for yourself and forgive others.
116778**    May you share freely, never taking more than you give.
116779**
116780******************************************************************************
116781**
116782*/
116783
116784#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
116785
116786
116787typedef struct Fts3auxTable Fts3auxTable;
116788typedef struct Fts3auxCursor Fts3auxCursor;
116789
116790struct Fts3auxTable {
116791  sqlite3_vtab base;              /* Base class used by SQLite core */
116792  Fts3Table *pFts3Tab;
116793};
116794
116795struct Fts3auxCursor {
116796  sqlite3_vtab_cursor base;       /* Base class used by SQLite core */
116797  Fts3SegReaderCursor csr;        /* Must be right after "base" */
116798  Fts3SegFilter filter;
116799  char *zStop;
116800  int nStop;                      /* Byte-length of string zStop */
116801  int isEof;                      /* True if cursor is at EOF */
116802  sqlite3_int64 iRowid;           /* Current rowid */
116803
116804  int iCol;                       /* Current value of 'col' column */
116805  int nStat;                      /* Size of aStat[] array */
116806  struct Fts3auxColstats {
116807    sqlite3_int64 nDoc;           /* 'documents' values for current csr row */
116808    sqlite3_int64 nOcc;           /* 'occurrences' values for current csr row */
116809  } *aStat;
116810};
116811
116812/*
116813** Schema of the terms table.
116814*/
116815#define FTS3_TERMS_SCHEMA "CREATE TABLE x(term, col, documents, occurrences)"
116816
116817/*
116818** This function does all the work for both the xConnect and xCreate methods.
116819** These tables have no persistent representation of their own, so xConnect
116820** and xCreate are identical operations.
116821*/
116822static int fts3auxConnectMethod(
116823  sqlite3 *db,                    /* Database connection */
116824  void *pUnused,                  /* Unused */
116825  int argc,                       /* Number of elements in argv array */
116826  const char * const *argv,       /* xCreate/xConnect argument array */
116827  sqlite3_vtab **ppVtab,          /* OUT: New sqlite3_vtab object */
116828  char **pzErr                    /* OUT: sqlite3_malloc'd error message */
116829){
116830  char const *zDb;                /* Name of database (e.g. "main") */
116831  char const *zFts3;              /* Name of fts3 table */
116832  int nDb;                        /* Result of strlen(zDb) */
116833  int nFts3;                      /* Result of strlen(zFts3) */
116834  int nByte;                      /* Bytes of space to allocate here */
116835  int rc;                         /* value returned by declare_vtab() */
116836  Fts3auxTable *p;                /* Virtual table object to return */
116837
116838  UNUSED_PARAMETER(pUnused);
116839
116840  /* The user should specify a single argument - the name of an fts3 table. */
116841  if( argc!=4 ){
116842    *pzErr = sqlite3_mprintf(
116843        "wrong number of arguments to fts4aux constructor"
116844    );
116845    return SQLITE_ERROR;
116846  }
116847
116848  zDb = argv[1];
116849  nDb = strlen(zDb);
116850  zFts3 = argv[3];
116851  nFts3 = strlen(zFts3);
116852
116853  rc = sqlite3_declare_vtab(db, FTS3_TERMS_SCHEMA);
116854  if( rc!=SQLITE_OK ) return rc;
116855
116856  nByte = sizeof(Fts3auxTable) + sizeof(Fts3Table) + nDb + nFts3 + 2;
116857  p = (Fts3auxTable *)sqlite3_malloc(nByte);
116858  if( !p ) return SQLITE_NOMEM;
116859  memset(p, 0, nByte);
116860
116861  p->pFts3Tab = (Fts3Table *)&p[1];
116862  p->pFts3Tab->zDb = (char *)&p->pFts3Tab[1];
116863  p->pFts3Tab->zName = &p->pFts3Tab->zDb[nDb+1];
116864  p->pFts3Tab->db = db;
116865
116866  memcpy((char *)p->pFts3Tab->zDb, zDb, nDb);
116867  memcpy((char *)p->pFts3Tab->zName, zFts3, nFts3);
116868  sqlite3Fts3Dequote((char *)p->pFts3Tab->zName);
116869
116870  *ppVtab = (sqlite3_vtab *)p;
116871  return SQLITE_OK;
116872}
116873
116874/*
116875** This function does the work for both the xDisconnect and xDestroy methods.
116876** These tables have no persistent representation of their own, so xDisconnect
116877** and xDestroy are identical operations.
116878*/
116879static int fts3auxDisconnectMethod(sqlite3_vtab *pVtab){
116880  Fts3auxTable *p = (Fts3auxTable *)pVtab;
116881  Fts3Table *pFts3 = p->pFts3Tab;
116882  int i;
116883
116884  /* Free any prepared statements held */
116885  for(i=0; i<SizeofArray(pFts3->aStmt); i++){
116886    sqlite3_finalize(pFts3->aStmt[i]);
116887  }
116888  sqlite3_free(pFts3->zSegmentsTbl);
116889  sqlite3_free(p);
116890  return SQLITE_OK;
116891}
116892
116893#define FTS4AUX_EQ_CONSTRAINT 1
116894#define FTS4AUX_GE_CONSTRAINT 2
116895#define FTS4AUX_LE_CONSTRAINT 4
116896
116897/*
116898** xBestIndex - Analyze a WHERE and ORDER BY clause.
116899*/
116900static int fts3auxBestIndexMethod(
116901  sqlite3_vtab *pVTab,
116902  sqlite3_index_info *pInfo
116903){
116904  int i;
116905  int iEq = -1;
116906  int iGe = -1;
116907  int iLe = -1;
116908
116909  UNUSED_PARAMETER(pVTab);
116910
116911  /* This vtab delivers always results in "ORDER BY term ASC" order. */
116912  if( pInfo->nOrderBy==1
116913   && pInfo->aOrderBy[0].iColumn==0
116914   && pInfo->aOrderBy[0].desc==0
116915  ){
116916    pInfo->orderByConsumed = 1;
116917  }
116918
116919  /* Search for equality and range constraints on the "term" column. */
116920  for(i=0; i<pInfo->nConstraint; i++){
116921    if( pInfo->aConstraint[i].usable && pInfo->aConstraint[i].iColumn==0 ){
116922      int op = pInfo->aConstraint[i].op;
116923      if( op==SQLITE_INDEX_CONSTRAINT_EQ ) iEq = i;
116924      if( op==SQLITE_INDEX_CONSTRAINT_LT ) iLe = i;
116925      if( op==SQLITE_INDEX_CONSTRAINT_LE ) iLe = i;
116926      if( op==SQLITE_INDEX_CONSTRAINT_GT ) iGe = i;
116927      if( op==SQLITE_INDEX_CONSTRAINT_GE ) iGe = i;
116928    }
116929  }
116930
116931  if( iEq>=0 ){
116932    pInfo->idxNum = FTS4AUX_EQ_CONSTRAINT;
116933    pInfo->aConstraintUsage[iEq].argvIndex = 1;
116934    pInfo->estimatedCost = 5;
116935  }else{
116936    pInfo->idxNum = 0;
116937    pInfo->estimatedCost = 20000;
116938    if( iGe>=0 ){
116939      pInfo->idxNum += FTS4AUX_GE_CONSTRAINT;
116940      pInfo->aConstraintUsage[iGe].argvIndex = 1;
116941      pInfo->estimatedCost /= 2;
116942    }
116943    if( iLe>=0 ){
116944      pInfo->idxNum += FTS4AUX_LE_CONSTRAINT;
116945      pInfo->aConstraintUsage[iLe].argvIndex = 1 + (iGe>=0);
116946      pInfo->estimatedCost /= 2;
116947    }
116948  }
116949
116950  return SQLITE_OK;
116951}
116952
116953/*
116954** xOpen - Open a cursor.
116955*/
116956static int fts3auxOpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
116957  Fts3auxCursor *pCsr;            /* Pointer to cursor object to return */
116958
116959  UNUSED_PARAMETER(pVTab);
116960
116961  pCsr = (Fts3auxCursor *)sqlite3_malloc(sizeof(Fts3auxCursor));
116962  if( !pCsr ) return SQLITE_NOMEM;
116963  memset(pCsr, 0, sizeof(Fts3auxCursor));
116964
116965  *ppCsr = (sqlite3_vtab_cursor *)pCsr;
116966  return SQLITE_OK;
116967}
116968
116969/*
116970** xClose - Close a cursor.
116971*/
116972static int fts3auxCloseMethod(sqlite3_vtab_cursor *pCursor){
116973  Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;
116974  Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
116975
116976  sqlite3Fts3SegmentsClose(pFts3);
116977  sqlite3Fts3SegReaderFinish(&pCsr->csr);
116978  sqlite3_free((void *)pCsr->filter.zTerm);
116979  sqlite3_free(pCsr->zStop);
116980  sqlite3_free(pCsr->aStat);
116981  sqlite3_free(pCsr);
116982  return SQLITE_OK;
116983}
116984
116985static int fts3auxGrowStatArray(Fts3auxCursor *pCsr, int nSize){
116986  if( nSize>pCsr->nStat ){
116987    struct Fts3auxColstats *aNew;
116988    aNew = (struct Fts3auxColstats *)sqlite3_realloc(pCsr->aStat,
116989        sizeof(struct Fts3auxColstats) * nSize
116990    );
116991    if( aNew==0 ) return SQLITE_NOMEM;
116992    memset(&aNew[pCsr->nStat], 0,
116993        sizeof(struct Fts3auxColstats) * (nSize - pCsr->nStat)
116994    );
116995    pCsr->aStat = aNew;
116996    pCsr->nStat = nSize;
116997  }
116998  return SQLITE_OK;
116999}
117000
117001/*
117002** xNext - Advance the cursor to the next row, if any.
117003*/
117004static int fts3auxNextMethod(sqlite3_vtab_cursor *pCursor){
117005  Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
117006  Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;
117007  int rc;
117008
117009  /* Increment our pretend rowid value. */
117010  pCsr->iRowid++;
117011
117012  for(pCsr->iCol++; pCsr->iCol<pCsr->nStat; pCsr->iCol++){
117013    if( pCsr->aStat[pCsr->iCol].nDoc>0 ) return SQLITE_OK;
117014  }
117015
117016  rc = sqlite3Fts3SegReaderStep(pFts3, &pCsr->csr);
117017  if( rc==SQLITE_ROW ){
117018    int i = 0;
117019    int nDoclist = pCsr->csr.nDoclist;
117020    char *aDoclist = pCsr->csr.aDoclist;
117021    int iCol;
117022
117023    int eState = 0;
117024
117025    if( pCsr->zStop ){
117026      int n = (pCsr->nStop<pCsr->csr.nTerm) ? pCsr->nStop : pCsr->csr.nTerm;
117027      int mc = memcmp(pCsr->zStop, pCsr->csr.zTerm, n);
117028      if( mc<0 || (mc==0 && pCsr->csr.nTerm>pCsr->nStop) ){
117029        pCsr->isEof = 1;
117030        return SQLITE_OK;
117031      }
117032    }
117033
117034    if( fts3auxGrowStatArray(pCsr, 2) ) return SQLITE_NOMEM;
117035    memset(pCsr->aStat, 0, sizeof(struct Fts3auxColstats) * pCsr->nStat);
117036    iCol = 0;
117037
117038    while( i<nDoclist ){
117039      sqlite3_int64 v = 0;
117040
117041      i += sqlite3Fts3GetVarint(&aDoclist[i], &v);
117042      switch( eState ){
117043        /* State 0. In this state the integer just read was a docid. */
117044        case 0:
117045          pCsr->aStat[0].nDoc++;
117046          eState = 1;
117047          iCol = 0;
117048          break;
117049
117050        /* State 1. In this state we are expecting either a 1, indicating
117051        ** that the following integer will be a column number, or the
117052        ** start of a position list for column 0.
117053        **
117054        ** The only difference between state 1 and state 2 is that if the
117055        ** integer encountered in state 1 is not 0 or 1, then we need to
117056        ** increment the column 0 "nDoc" count for this term.
117057        */
117058        case 1:
117059          assert( iCol==0 );
117060          if( v>1 ){
117061            pCsr->aStat[1].nDoc++;
117062          }
117063          eState = 2;
117064          /* fall through */
117065
117066        case 2:
117067          if( v==0 ){       /* 0x00. Next integer will be a docid. */
117068            eState = 0;
117069          }else if( v==1 ){ /* 0x01. Next integer will be a column number. */
117070            eState = 3;
117071          }else{            /* 2 or greater. A position. */
117072            pCsr->aStat[iCol+1].nOcc++;
117073            pCsr->aStat[0].nOcc++;
117074          }
117075          break;
117076
117077        /* State 3. The integer just read is a column number. */
117078        default: assert( eState==3 );
117079          iCol = (int)v;
117080          if( fts3auxGrowStatArray(pCsr, iCol+2) ) return SQLITE_NOMEM;
117081          pCsr->aStat[iCol+1].nDoc++;
117082          eState = 2;
117083          break;
117084      }
117085    }
117086
117087    pCsr->iCol = 0;
117088    rc = SQLITE_OK;
117089  }else{
117090    pCsr->isEof = 1;
117091  }
117092  return rc;
117093}
117094
117095/*
117096** xFilter - Initialize a cursor to point at the start of its data.
117097*/
117098static int fts3auxFilterMethod(
117099  sqlite3_vtab_cursor *pCursor,   /* The cursor used for this query */
117100  int idxNum,                     /* Strategy index */
117101  const char *idxStr,             /* Unused */
117102  int nVal,                       /* Number of elements in apVal */
117103  sqlite3_value **apVal           /* Arguments for the indexing scheme */
117104){
117105  Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
117106  Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;
117107  int rc;
117108  int isScan;
117109
117110  UNUSED_PARAMETER(nVal);
117111
117112  assert( idxStr==0 );
117113  assert( idxNum==FTS4AUX_EQ_CONSTRAINT || idxNum==0
117114       || idxNum==FTS4AUX_LE_CONSTRAINT || idxNum==FTS4AUX_GE_CONSTRAINT
117115       || idxNum==(FTS4AUX_LE_CONSTRAINT|FTS4AUX_GE_CONSTRAINT)
117116  );
117117  isScan = (idxNum!=FTS4AUX_EQ_CONSTRAINT);
117118
117119  /* In case this cursor is being reused, close and zero it. */
117120  testcase(pCsr->filter.zTerm);
117121  sqlite3Fts3SegReaderFinish(&pCsr->csr);
117122  sqlite3_free((void *)pCsr->filter.zTerm);
117123  sqlite3_free(pCsr->aStat);
117124  memset(&pCsr->csr, 0, ((u8*)&pCsr[1]) - (u8*)&pCsr->csr);
117125
117126  pCsr->filter.flags = FTS3_SEGMENT_REQUIRE_POS|FTS3_SEGMENT_IGNORE_EMPTY;
117127  if( isScan ) pCsr->filter.flags |= FTS3_SEGMENT_SCAN;
117128
117129  if( idxNum&(FTS4AUX_EQ_CONSTRAINT|FTS4AUX_GE_CONSTRAINT) ){
117130    const unsigned char *zStr = sqlite3_value_text(apVal[0]);
117131    if( zStr ){
117132      pCsr->filter.zTerm = sqlite3_mprintf("%s", zStr);
117133      pCsr->filter.nTerm = sqlite3_value_bytes(apVal[0]);
117134      if( pCsr->filter.zTerm==0 ) return SQLITE_NOMEM;
117135    }
117136  }
117137  if( idxNum&FTS4AUX_LE_CONSTRAINT ){
117138    int iIdx = (idxNum&FTS4AUX_GE_CONSTRAINT) ? 1 : 0;
117139    pCsr->zStop = sqlite3_mprintf("%s", sqlite3_value_text(apVal[iIdx]));
117140    pCsr->nStop = sqlite3_value_bytes(apVal[iIdx]);
117141    if( pCsr->zStop==0 ) return SQLITE_NOMEM;
117142  }
117143
117144  rc = sqlite3Fts3SegReaderCursor(pFts3, FTS3_SEGCURSOR_ALL,
117145      pCsr->filter.zTerm, pCsr->filter.nTerm, 0, isScan, &pCsr->csr
117146  );
117147  if( rc==SQLITE_OK ){
117148    rc = sqlite3Fts3SegReaderStart(pFts3, &pCsr->csr, &pCsr->filter);
117149  }
117150
117151  if( rc==SQLITE_OK ) rc = fts3auxNextMethod(pCursor);
117152  return rc;
117153}
117154
117155/*
117156** xEof - Return true if the cursor is at EOF, or false otherwise.
117157*/
117158static int fts3auxEofMethod(sqlite3_vtab_cursor *pCursor){
117159  Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
117160  return pCsr->isEof;
117161}
117162
117163/*
117164** xColumn - Return a column value.
117165*/
117166static int fts3auxColumnMethod(
117167  sqlite3_vtab_cursor *pCursor,   /* Cursor to retrieve value from */
117168  sqlite3_context *pContext,      /* Context for sqlite3_result_xxx() calls */
117169  int iCol                        /* Index of column to read value from */
117170){
117171  Fts3auxCursor *p = (Fts3auxCursor *)pCursor;
117172
117173  assert( p->isEof==0 );
117174  if( iCol==0 ){        /* Column "term" */
117175    sqlite3_result_text(pContext, p->csr.zTerm, p->csr.nTerm, SQLITE_TRANSIENT);
117176  }else if( iCol==1 ){  /* Column "col" */
117177    if( p->iCol ){
117178      sqlite3_result_int(pContext, p->iCol-1);
117179    }else{
117180      sqlite3_result_text(pContext, "*", -1, SQLITE_STATIC);
117181    }
117182  }else if( iCol==2 ){  /* Column "documents" */
117183    sqlite3_result_int64(pContext, p->aStat[p->iCol].nDoc);
117184  }else{                /* Column "occurrences" */
117185    sqlite3_result_int64(pContext, p->aStat[p->iCol].nOcc);
117186  }
117187
117188  return SQLITE_OK;
117189}
117190
117191/*
117192** xRowid - Return the current rowid for the cursor.
117193*/
117194static int fts3auxRowidMethod(
117195  sqlite3_vtab_cursor *pCursor,   /* Cursor to retrieve value from */
117196  sqlite_int64 *pRowid            /* OUT: Rowid value */
117197){
117198  Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
117199  *pRowid = pCsr->iRowid;
117200  return SQLITE_OK;
117201}
117202
117203/*
117204** Register the fts3aux module with database connection db. Return SQLITE_OK
117205** if successful or an error code if sqlite3_create_module() fails.
117206*/
117207SQLITE_PRIVATE int sqlite3Fts3InitAux(sqlite3 *db){
117208  static const sqlite3_module fts3aux_module = {
117209     0,                           /* iVersion      */
117210     fts3auxConnectMethod,        /* xCreate       */
117211     fts3auxConnectMethod,        /* xConnect      */
117212     fts3auxBestIndexMethod,      /* xBestIndex    */
117213     fts3auxDisconnectMethod,     /* xDisconnect   */
117214     fts3auxDisconnectMethod,     /* xDestroy      */
117215     fts3auxOpenMethod,           /* xOpen         */
117216     fts3auxCloseMethod,          /* xClose        */
117217     fts3auxFilterMethod,         /* xFilter       */
117218     fts3auxNextMethod,           /* xNext         */
117219     fts3auxEofMethod,            /* xEof          */
117220     fts3auxColumnMethod,         /* xColumn       */
117221     fts3auxRowidMethod,          /* xRowid        */
117222     0,                           /* xUpdate       */
117223     0,                           /* xBegin        */
117224     0,                           /* xSync         */
117225     0,                           /* xCommit       */
117226     0,                           /* xRollback     */
117227     0,                           /* xFindFunction */
117228     0                            /* xRename       */
117229  };
117230  int rc;                         /* Return code */
117231
117232  rc = sqlite3_create_module(db, "fts4aux", &fts3aux_module, 0);
117233  return rc;
117234}
117235
117236#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
117237
117238/************** End of fts3_aux.c ********************************************/
117239/************** Begin file fts3_expr.c ***************************************/
117240/*
117241** 2008 Nov 28
117242**
117243** The author disclaims copyright to this source code.  In place of
117244** a legal notice, here is a blessing:
117245**
117246**    May you do good and not evil.
117247**    May you find forgiveness for yourself and forgive others.
117248**    May you share freely, never taking more than you give.
117249**
117250******************************************************************************
117251**
117252** This module contains code that implements a parser for fts3 query strings
117253** (the right-hand argument to the MATCH operator). Because the supported
117254** syntax is relatively simple, the whole tokenizer/parser system is
117255** hand-coded.
117256*/
117257#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
117258
117259/*
117260** By default, this module parses the legacy syntax that has been
117261** traditionally used by fts3. Or, if SQLITE_ENABLE_FTS3_PARENTHESIS
117262** is defined, then it uses the new syntax. The differences between
117263** the new and the old syntaxes are:
117264**
117265**  a) The new syntax supports parenthesis. The old does not.
117266**
117267**  b) The new syntax supports the AND and NOT operators. The old does not.
117268**
117269**  c) The old syntax supports the "-" token qualifier. This is not
117270**     supported by the new syntax (it is replaced by the NOT operator).
117271**
117272**  d) When using the old syntax, the OR operator has a greater precedence
117273**     than an implicit AND. When using the new, both implicity and explicit
117274**     AND operators have a higher precedence than OR.
117275**
117276** If compiled with SQLITE_TEST defined, then this module exports the
117277** symbol "int sqlite3_fts3_enable_parentheses". Setting this variable
117278** to zero causes the module to use the old syntax. If it is set to
117279** non-zero the new syntax is activated. This is so both syntaxes can
117280** be tested using a single build of testfixture.
117281**
117282** The following describes the syntax supported by the fts3 MATCH
117283** operator in a similar format to that used by the lemon parser
117284** generator. This module does not use actually lemon, it uses a
117285** custom parser.
117286**
117287**   query ::= andexpr (OR andexpr)*.
117288**
117289**   andexpr ::= notexpr (AND? notexpr)*.
117290**
117291**   notexpr ::= nearexpr (NOT nearexpr|-TOKEN)*.
117292**   notexpr ::= LP query RP.
117293**
117294**   nearexpr ::= phrase (NEAR distance_opt nearexpr)*.
117295**
117296**   distance_opt ::= .
117297**   distance_opt ::= / INTEGER.
117298**
117299**   phrase ::= TOKEN.
117300**   phrase ::= COLUMN:TOKEN.
117301**   phrase ::= "TOKEN TOKEN TOKEN...".
117302*/
117303
117304#ifdef SQLITE_TEST
117305SQLITE_API int sqlite3_fts3_enable_parentheses = 0;
117306#else
117307# ifdef SQLITE_ENABLE_FTS3_PARENTHESIS
117308#  define sqlite3_fts3_enable_parentheses 1
117309# else
117310#  define sqlite3_fts3_enable_parentheses 0
117311# endif
117312#endif
117313
117314/*
117315** Default span for NEAR operators.
117316*/
117317#define SQLITE_FTS3_DEFAULT_NEAR_PARAM 10
117318
117319
117320typedef struct ParseContext ParseContext;
117321struct ParseContext {
117322  sqlite3_tokenizer *pTokenizer;      /* Tokenizer module */
117323  const char **azCol;                 /* Array of column names for fts3 table */
117324  int nCol;                           /* Number of entries in azCol[] */
117325  int iDefaultCol;                    /* Default column to query */
117326  sqlite3_context *pCtx;              /* Write error message here */
117327  int nNest;                          /* Number of nested brackets */
117328};
117329
117330/*
117331** This function is equivalent to the standard isspace() function.
117332**
117333** The standard isspace() can be awkward to use safely, because although it
117334** is defined to accept an argument of type int, its behaviour when passed
117335** an integer that falls outside of the range of the unsigned char type
117336** is undefined (and sometimes, "undefined" means segfault). This wrapper
117337** is defined to accept an argument of type char, and always returns 0 for
117338** any values that fall outside of the range of the unsigned char type (i.e.
117339** negative values).
117340*/
117341static int fts3isspace(char c){
117342  return c==' ' || c=='\t' || c=='\n' || c=='\r' || c=='\v' || c=='\f';
117343}
117344
117345/*
117346** Allocate nByte bytes of memory using sqlite3_malloc(). If successful,
117347** zero the memory before returning a pointer to it. If unsuccessful,
117348** return NULL.
117349*/
117350static void *fts3MallocZero(int nByte){
117351  void *pRet = sqlite3_malloc(nByte);
117352  if( pRet ) memset(pRet, 0, nByte);
117353  return pRet;
117354}
117355
117356
117357/*
117358** Extract the next token from buffer z (length n) using the tokenizer
117359** and other information (column names etc.) in pParse. Create an Fts3Expr
117360** structure of type FTSQUERY_PHRASE containing a phrase consisting of this
117361** single token and set *ppExpr to point to it. If the end of the buffer is
117362** reached before a token is found, set *ppExpr to zero. It is the
117363** responsibility of the caller to eventually deallocate the allocated
117364** Fts3Expr structure (if any) by passing it to sqlite3_free().
117365**
117366** Return SQLITE_OK if successful, or SQLITE_NOMEM if a memory allocation
117367** fails.
117368*/
117369static int getNextToken(
117370  ParseContext *pParse,                   /* fts3 query parse context */
117371  int iCol,                               /* Value for Fts3Phrase.iColumn */
117372  const char *z, int n,                   /* Input string */
117373  Fts3Expr **ppExpr,                      /* OUT: expression */
117374  int *pnConsumed                         /* OUT: Number of bytes consumed */
117375){
117376  sqlite3_tokenizer *pTokenizer = pParse->pTokenizer;
117377  sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
117378  int rc;
117379  sqlite3_tokenizer_cursor *pCursor;
117380  Fts3Expr *pRet = 0;
117381  int nConsumed = 0;
117382
117383  rc = pModule->xOpen(pTokenizer, z, n, &pCursor);
117384  if( rc==SQLITE_OK ){
117385    const char *zToken;
117386    int nToken, iStart, iEnd, iPosition;
117387    int nByte;                               /* total space to allocate */
117388
117389    pCursor->pTokenizer = pTokenizer;
117390    rc = pModule->xNext(pCursor, &zToken, &nToken, &iStart, &iEnd, &iPosition);
117391
117392    if( rc==SQLITE_OK ){
117393      nByte = sizeof(Fts3Expr) + sizeof(Fts3Phrase) + nToken;
117394      pRet = (Fts3Expr *)fts3MallocZero(nByte);
117395      if( !pRet ){
117396        rc = SQLITE_NOMEM;
117397      }else{
117398        pRet->eType = FTSQUERY_PHRASE;
117399        pRet->pPhrase = (Fts3Phrase *)&pRet[1];
117400        pRet->pPhrase->nToken = 1;
117401        pRet->pPhrase->iColumn = iCol;
117402        pRet->pPhrase->aToken[0].n = nToken;
117403        pRet->pPhrase->aToken[0].z = (char *)&pRet->pPhrase[1];
117404        memcpy(pRet->pPhrase->aToken[0].z, zToken, nToken);
117405
117406        if( iEnd<n && z[iEnd]=='*' ){
117407          pRet->pPhrase->aToken[0].isPrefix = 1;
117408          iEnd++;
117409        }
117410        if( !sqlite3_fts3_enable_parentheses && iStart>0 && z[iStart-1]=='-' ){
117411          pRet->pPhrase->isNot = 1;
117412        }
117413      }
117414      nConsumed = iEnd;
117415    }
117416
117417    pModule->xClose(pCursor);
117418  }
117419
117420  *pnConsumed = nConsumed;
117421  *ppExpr = pRet;
117422  return rc;
117423}
117424
117425
117426/*
117427** Enlarge a memory allocation.  If an out-of-memory allocation occurs,
117428** then free the old allocation.
117429*/
117430static void *fts3ReallocOrFree(void *pOrig, int nNew){
117431  void *pRet = sqlite3_realloc(pOrig, nNew);
117432  if( !pRet ){
117433    sqlite3_free(pOrig);
117434  }
117435  return pRet;
117436}
117437
117438/*
117439** Buffer zInput, length nInput, contains the contents of a quoted string
117440** that appeared as part of an fts3 query expression. Neither quote character
117441** is included in the buffer. This function attempts to tokenize the entire
117442** input buffer and create an Fts3Expr structure of type FTSQUERY_PHRASE
117443** containing the results.
117444**
117445** If successful, SQLITE_OK is returned and *ppExpr set to point at the
117446** allocated Fts3Expr structure. Otherwise, either SQLITE_NOMEM (out of memory
117447** error) or SQLITE_ERROR (tokenization error) is returned and *ppExpr set
117448** to 0.
117449*/
117450static int getNextString(
117451  ParseContext *pParse,                   /* fts3 query parse context */
117452  const char *zInput, int nInput,         /* Input string */
117453  Fts3Expr **ppExpr                       /* OUT: expression */
117454){
117455  sqlite3_tokenizer *pTokenizer = pParse->pTokenizer;
117456  sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
117457  int rc;
117458  Fts3Expr *p = 0;
117459  sqlite3_tokenizer_cursor *pCursor = 0;
117460  char *zTemp = 0;
117461  int nTemp = 0;
117462
117463  rc = pModule->xOpen(pTokenizer, zInput, nInput, &pCursor);
117464  if( rc==SQLITE_OK ){
117465    int ii;
117466    pCursor->pTokenizer = pTokenizer;
117467    for(ii=0; rc==SQLITE_OK; ii++){
117468      const char *zToken;
117469      int nToken, iBegin, iEnd, iPos;
117470      rc = pModule->xNext(pCursor, &zToken, &nToken, &iBegin, &iEnd, &iPos);
117471      if( rc==SQLITE_OK ){
117472        int nByte = sizeof(Fts3Expr) + sizeof(Fts3Phrase);
117473        p = fts3ReallocOrFree(p, nByte+ii*sizeof(Fts3PhraseToken));
117474        zTemp = fts3ReallocOrFree(zTemp, nTemp + nToken);
117475        if( !p || !zTemp ){
117476          goto no_mem;
117477        }
117478        if( ii==0 ){
117479          memset(p, 0, nByte);
117480          p->pPhrase = (Fts3Phrase *)&p[1];
117481        }
117482        p->pPhrase = (Fts3Phrase *)&p[1];
117483        memset(&p->pPhrase->aToken[ii], 0, sizeof(Fts3PhraseToken));
117484        p->pPhrase->nToken = ii+1;
117485        p->pPhrase->aToken[ii].n = nToken;
117486        memcpy(&zTemp[nTemp], zToken, nToken);
117487        nTemp += nToken;
117488        if( iEnd<nInput && zInput[iEnd]=='*' ){
117489          p->pPhrase->aToken[ii].isPrefix = 1;
117490        }else{
117491          p->pPhrase->aToken[ii].isPrefix = 0;
117492        }
117493      }
117494    }
117495
117496    pModule->xClose(pCursor);
117497    pCursor = 0;
117498  }
117499
117500  if( rc==SQLITE_DONE ){
117501    int jj;
117502    char *zNew = NULL;
117503    int nNew = 0;
117504    int nByte = sizeof(Fts3Expr) + sizeof(Fts3Phrase);
117505    nByte += (p?(p->pPhrase->nToken-1):0) * sizeof(Fts3PhraseToken);
117506    p = fts3ReallocOrFree(p, nByte + nTemp);
117507    if( !p ){
117508      goto no_mem;
117509    }
117510    if( zTemp ){
117511      zNew = &(((char *)p)[nByte]);
117512      memcpy(zNew, zTemp, nTemp);
117513    }else{
117514      memset(p, 0, nByte+nTemp);
117515    }
117516    p->pPhrase = (Fts3Phrase *)&p[1];
117517    for(jj=0; jj<p->pPhrase->nToken; jj++){
117518      p->pPhrase->aToken[jj].z = &zNew[nNew];
117519      nNew += p->pPhrase->aToken[jj].n;
117520    }
117521    sqlite3_free(zTemp);
117522    p->eType = FTSQUERY_PHRASE;
117523    p->pPhrase->iColumn = pParse->iDefaultCol;
117524    rc = SQLITE_OK;
117525  }
117526
117527  *ppExpr = p;
117528  return rc;
117529no_mem:
117530
117531  if( pCursor ){
117532    pModule->xClose(pCursor);
117533  }
117534  sqlite3_free(zTemp);
117535  sqlite3_free(p);
117536  *ppExpr = 0;
117537  return SQLITE_NOMEM;
117538}
117539
117540/*
117541** Function getNextNode(), which is called by fts3ExprParse(), may itself
117542** call fts3ExprParse(). So this forward declaration is required.
117543*/
117544static int fts3ExprParse(ParseContext *, const char *, int, Fts3Expr **, int *);
117545
117546/*
117547** The output variable *ppExpr is populated with an allocated Fts3Expr
117548** structure, or set to 0 if the end of the input buffer is reached.
117549**
117550** Returns an SQLite error code. SQLITE_OK if everything works, SQLITE_NOMEM
117551** if a malloc failure occurs, or SQLITE_ERROR if a parse error is encountered.
117552** If SQLITE_ERROR is returned, pContext is populated with an error message.
117553*/
117554static int getNextNode(
117555  ParseContext *pParse,                   /* fts3 query parse context */
117556  const char *z, int n,                   /* Input string */
117557  Fts3Expr **ppExpr,                      /* OUT: expression */
117558  int *pnConsumed                         /* OUT: Number of bytes consumed */
117559){
117560  static const struct Fts3Keyword {
117561    char *z;                              /* Keyword text */
117562    unsigned char n;                      /* Length of the keyword */
117563    unsigned char parenOnly;              /* Only valid in paren mode */
117564    unsigned char eType;                  /* Keyword code */
117565  } aKeyword[] = {
117566    { "OR" ,  2, 0, FTSQUERY_OR   },
117567    { "AND",  3, 1, FTSQUERY_AND  },
117568    { "NOT",  3, 1, FTSQUERY_NOT  },
117569    { "NEAR", 4, 0, FTSQUERY_NEAR }
117570  };
117571  int ii;
117572  int iCol;
117573  int iColLen;
117574  int rc;
117575  Fts3Expr *pRet = 0;
117576
117577  const char *zInput = z;
117578  int nInput = n;
117579
117580  /* Skip over any whitespace before checking for a keyword, an open or
117581  ** close bracket, or a quoted string.
117582  */
117583  while( nInput>0 && fts3isspace(*zInput) ){
117584    nInput--;
117585    zInput++;
117586  }
117587  if( nInput==0 ){
117588    return SQLITE_DONE;
117589  }
117590
117591  /* See if we are dealing with a keyword. */
117592  for(ii=0; ii<(int)(sizeof(aKeyword)/sizeof(struct Fts3Keyword)); ii++){
117593    const struct Fts3Keyword *pKey = &aKeyword[ii];
117594
117595    if( (pKey->parenOnly & ~sqlite3_fts3_enable_parentheses)!=0 ){
117596      continue;
117597    }
117598
117599    if( nInput>=pKey->n && 0==memcmp(zInput, pKey->z, pKey->n) ){
117600      int nNear = SQLITE_FTS3_DEFAULT_NEAR_PARAM;
117601      int nKey = pKey->n;
117602      char cNext;
117603
117604      /* If this is a "NEAR" keyword, check for an explicit nearness. */
117605      if( pKey->eType==FTSQUERY_NEAR ){
117606        assert( nKey==4 );
117607        if( zInput[4]=='/' && zInput[5]>='0' && zInput[5]<='9' ){
117608          nNear = 0;
117609          for(nKey=5; zInput[nKey]>='0' && zInput[nKey]<='9'; nKey++){
117610            nNear = nNear * 10 + (zInput[nKey] - '0');
117611          }
117612        }
117613      }
117614
117615      /* At this point this is probably a keyword. But for that to be true,
117616      ** the next byte must contain either whitespace, an open or close
117617      ** parenthesis, a quote character, or EOF.
117618      */
117619      cNext = zInput[nKey];
117620      if( fts3isspace(cNext)
117621       || cNext=='"' || cNext=='(' || cNext==')' || cNext==0
117622      ){
117623        pRet = (Fts3Expr *)fts3MallocZero(sizeof(Fts3Expr));
117624        if( !pRet ){
117625          return SQLITE_NOMEM;
117626        }
117627        pRet->eType = pKey->eType;
117628        pRet->nNear = nNear;
117629        *ppExpr = pRet;
117630        *pnConsumed = (int)((zInput - z) + nKey);
117631        return SQLITE_OK;
117632      }
117633
117634      /* Turns out that wasn't a keyword after all. This happens if the
117635      ** user has supplied a token such as "ORacle". Continue.
117636      */
117637    }
117638  }
117639
117640  /* Check for an open bracket. */
117641  if( sqlite3_fts3_enable_parentheses ){
117642    if( *zInput=='(' ){
117643      int nConsumed;
117644      pParse->nNest++;
117645      rc = fts3ExprParse(pParse, &zInput[1], nInput-1, ppExpr, &nConsumed);
117646      if( rc==SQLITE_OK && !*ppExpr ){
117647        rc = SQLITE_DONE;
117648      }
117649      *pnConsumed = (int)((zInput - z) + 1 + nConsumed);
117650      return rc;
117651    }
117652
117653    /* Check for a close bracket. */
117654    if( *zInput==')' ){
117655      pParse->nNest--;
117656      *pnConsumed = (int)((zInput - z) + 1);
117657      return SQLITE_DONE;
117658    }
117659  }
117660
117661  /* See if we are dealing with a quoted phrase. If this is the case, then
117662  ** search for the closing quote and pass the whole string to getNextString()
117663  ** for processing. This is easy to do, as fts3 has no syntax for escaping
117664  ** a quote character embedded in a string.
117665  */
117666  if( *zInput=='"' ){
117667    for(ii=1; ii<nInput && zInput[ii]!='"'; ii++);
117668    *pnConsumed = (int)((zInput - z) + ii + 1);
117669    if( ii==nInput ){
117670      return SQLITE_ERROR;
117671    }
117672    return getNextString(pParse, &zInput[1], ii-1, ppExpr);
117673  }
117674
117675
117676  /* If control flows to this point, this must be a regular token, or
117677  ** the end of the input. Read a regular token using the sqlite3_tokenizer
117678  ** interface. Before doing so, figure out if there is an explicit
117679  ** column specifier for the token.
117680  **
117681  ** TODO: Strangely, it is not possible to associate a column specifier
117682  ** with a quoted phrase, only with a single token. Not sure if this was
117683  ** an implementation artifact or an intentional decision when fts3 was
117684  ** first implemented. Whichever it was, this module duplicates the
117685  ** limitation.
117686  */
117687  iCol = pParse->iDefaultCol;
117688  iColLen = 0;
117689  for(ii=0; ii<pParse->nCol; ii++){
117690    const char *zStr = pParse->azCol[ii];
117691    int nStr = (int)strlen(zStr);
117692    if( nInput>nStr && zInput[nStr]==':'
117693     && sqlite3_strnicmp(zStr, zInput, nStr)==0
117694    ){
117695      iCol = ii;
117696      iColLen = (int)((zInput - z) + nStr + 1);
117697      break;
117698    }
117699  }
117700  rc = getNextToken(pParse, iCol, &z[iColLen], n-iColLen, ppExpr, pnConsumed);
117701  *pnConsumed += iColLen;
117702  return rc;
117703}
117704
117705/*
117706** The argument is an Fts3Expr structure for a binary operator (any type
117707** except an FTSQUERY_PHRASE). Return an integer value representing the
117708** precedence of the operator. Lower values have a higher precedence (i.e.
117709** group more tightly). For example, in the C language, the == operator
117710** groups more tightly than ||, and would therefore have a higher precedence.
117711**
117712** When using the new fts3 query syntax (when SQLITE_ENABLE_FTS3_PARENTHESIS
117713** is defined), the order of the operators in precedence from highest to
117714** lowest is:
117715**
117716**   NEAR
117717**   NOT
117718**   AND (including implicit ANDs)
117719**   OR
117720**
117721** Note that when using the old query syntax, the OR operator has a higher
117722** precedence than the AND operator.
117723*/
117724static int opPrecedence(Fts3Expr *p){
117725  assert( p->eType!=FTSQUERY_PHRASE );
117726  if( sqlite3_fts3_enable_parentheses ){
117727    return p->eType;
117728  }else if( p->eType==FTSQUERY_NEAR ){
117729    return 1;
117730  }else if( p->eType==FTSQUERY_OR ){
117731    return 2;
117732  }
117733  assert( p->eType==FTSQUERY_AND );
117734  return 3;
117735}
117736
117737/*
117738** Argument ppHead contains a pointer to the current head of a query
117739** expression tree being parsed. pPrev is the expression node most recently
117740** inserted into the tree. This function adds pNew, which is always a binary
117741** operator node, into the expression tree based on the relative precedence
117742** of pNew and the existing nodes of the tree. This may result in the head
117743** of the tree changing, in which case *ppHead is set to the new root node.
117744*/
117745static void insertBinaryOperator(
117746  Fts3Expr **ppHead,       /* Pointer to the root node of a tree */
117747  Fts3Expr *pPrev,         /* Node most recently inserted into the tree */
117748  Fts3Expr *pNew           /* New binary node to insert into expression tree */
117749){
117750  Fts3Expr *pSplit = pPrev;
117751  while( pSplit->pParent && opPrecedence(pSplit->pParent)<=opPrecedence(pNew) ){
117752    pSplit = pSplit->pParent;
117753  }
117754
117755  if( pSplit->pParent ){
117756    assert( pSplit->pParent->pRight==pSplit );
117757    pSplit->pParent->pRight = pNew;
117758    pNew->pParent = pSplit->pParent;
117759  }else{
117760    *ppHead = pNew;
117761  }
117762  pNew->pLeft = pSplit;
117763  pSplit->pParent = pNew;
117764}
117765
117766/*
117767** Parse the fts3 query expression found in buffer z, length n. This function
117768** returns either when the end of the buffer is reached or an unmatched
117769** closing bracket - ')' - is encountered.
117770**
117771** If successful, SQLITE_OK is returned, *ppExpr is set to point to the
117772** parsed form of the expression and *pnConsumed is set to the number of
117773** bytes read from buffer z. Otherwise, *ppExpr is set to 0 and SQLITE_NOMEM
117774** (out of memory error) or SQLITE_ERROR (parse error) is returned.
117775*/
117776static int fts3ExprParse(
117777  ParseContext *pParse,                   /* fts3 query parse context */
117778  const char *z, int n,                   /* Text of MATCH query */
117779  Fts3Expr **ppExpr,                      /* OUT: Parsed query structure */
117780  int *pnConsumed                         /* OUT: Number of bytes consumed */
117781){
117782  Fts3Expr *pRet = 0;
117783  Fts3Expr *pPrev = 0;
117784  Fts3Expr *pNotBranch = 0;               /* Only used in legacy parse mode */
117785  int nIn = n;
117786  const char *zIn = z;
117787  int rc = SQLITE_OK;
117788  int isRequirePhrase = 1;
117789
117790  while( rc==SQLITE_OK ){
117791    Fts3Expr *p = 0;
117792    int nByte = 0;
117793    rc = getNextNode(pParse, zIn, nIn, &p, &nByte);
117794    if( rc==SQLITE_OK ){
117795      int isPhrase;
117796
117797      if( !sqlite3_fts3_enable_parentheses
117798       && p->eType==FTSQUERY_PHRASE && p->pPhrase->isNot
117799      ){
117800        /* Create an implicit NOT operator. */
117801        Fts3Expr *pNot = fts3MallocZero(sizeof(Fts3Expr));
117802        if( !pNot ){
117803          sqlite3Fts3ExprFree(p);
117804          rc = SQLITE_NOMEM;
117805          goto exprparse_out;
117806        }
117807        pNot->eType = FTSQUERY_NOT;
117808        pNot->pRight = p;
117809        if( pNotBranch ){
117810          pNot->pLeft = pNotBranch;
117811        }
117812        pNotBranch = pNot;
117813        p = pPrev;
117814      }else{
117815        int eType = p->eType;
117816        assert( eType!=FTSQUERY_PHRASE || !p->pPhrase->isNot );
117817        isPhrase = (eType==FTSQUERY_PHRASE || p->pLeft);
117818
117819        /* The isRequirePhrase variable is set to true if a phrase or
117820        ** an expression contained in parenthesis is required. If a
117821        ** binary operator (AND, OR, NOT or NEAR) is encounted when
117822        ** isRequirePhrase is set, this is a syntax error.
117823        */
117824        if( !isPhrase && isRequirePhrase ){
117825          sqlite3Fts3ExprFree(p);
117826          rc = SQLITE_ERROR;
117827          goto exprparse_out;
117828        }
117829
117830        if( isPhrase && !isRequirePhrase ){
117831          /* Insert an implicit AND operator. */
117832          Fts3Expr *pAnd;
117833          assert( pRet && pPrev );
117834          pAnd = fts3MallocZero(sizeof(Fts3Expr));
117835          if( !pAnd ){
117836            sqlite3Fts3ExprFree(p);
117837            rc = SQLITE_NOMEM;
117838            goto exprparse_out;
117839          }
117840          pAnd->eType = FTSQUERY_AND;
117841          insertBinaryOperator(&pRet, pPrev, pAnd);
117842          pPrev = pAnd;
117843        }
117844
117845        /* This test catches attempts to make either operand of a NEAR
117846        ** operator something other than a phrase. For example, either of
117847        ** the following:
117848        **
117849        **    (bracketed expression) NEAR phrase
117850        **    phrase NEAR (bracketed expression)
117851        **
117852        ** Return an error in either case.
117853        */
117854        if( pPrev && (
117855            (eType==FTSQUERY_NEAR && !isPhrase && pPrev->eType!=FTSQUERY_PHRASE)
117856         || (eType!=FTSQUERY_PHRASE && isPhrase && pPrev->eType==FTSQUERY_NEAR)
117857        )){
117858          sqlite3Fts3ExprFree(p);
117859          rc = SQLITE_ERROR;
117860          goto exprparse_out;
117861        }
117862
117863        if( isPhrase ){
117864          if( pRet ){
117865            assert( pPrev && pPrev->pLeft && pPrev->pRight==0 );
117866            pPrev->pRight = p;
117867            p->pParent = pPrev;
117868          }else{
117869            pRet = p;
117870          }
117871        }else{
117872          insertBinaryOperator(&pRet, pPrev, p);
117873        }
117874        isRequirePhrase = !isPhrase;
117875      }
117876      assert( nByte>0 );
117877    }
117878    assert( rc!=SQLITE_OK || (nByte>0 && nByte<=nIn) );
117879    nIn -= nByte;
117880    zIn += nByte;
117881    pPrev = p;
117882  }
117883
117884  if( rc==SQLITE_DONE && pRet && isRequirePhrase ){
117885    rc = SQLITE_ERROR;
117886  }
117887
117888  if( rc==SQLITE_DONE ){
117889    rc = SQLITE_OK;
117890    if( !sqlite3_fts3_enable_parentheses && pNotBranch ){
117891      if( !pRet ){
117892        rc = SQLITE_ERROR;
117893      }else{
117894        Fts3Expr *pIter = pNotBranch;
117895        while( pIter->pLeft ){
117896          pIter = pIter->pLeft;
117897        }
117898        pIter->pLeft = pRet;
117899        pRet = pNotBranch;
117900      }
117901    }
117902  }
117903  *pnConsumed = n - nIn;
117904
117905exprparse_out:
117906  if( rc!=SQLITE_OK ){
117907    sqlite3Fts3ExprFree(pRet);
117908    sqlite3Fts3ExprFree(pNotBranch);
117909    pRet = 0;
117910  }
117911  *ppExpr = pRet;
117912  return rc;
117913}
117914
117915/*
117916** Parameters z and n contain a pointer to and length of a buffer containing
117917** an fts3 query expression, respectively. This function attempts to parse the
117918** query expression and create a tree of Fts3Expr structures representing the
117919** parsed expression. If successful, *ppExpr is set to point to the head
117920** of the parsed expression tree and SQLITE_OK is returned. If an error
117921** occurs, either SQLITE_NOMEM (out-of-memory error) or SQLITE_ERROR (parse
117922** error) is returned and *ppExpr is set to 0.
117923**
117924** If parameter n is a negative number, then z is assumed to point to a
117925** nul-terminated string and the length is determined using strlen().
117926**
117927** The first parameter, pTokenizer, is passed the fts3 tokenizer module to
117928** use to normalize query tokens while parsing the expression. The azCol[]
117929** array, which is assumed to contain nCol entries, should contain the names
117930** of each column in the target fts3 table, in order from left to right.
117931** Column names must be nul-terminated strings.
117932**
117933** The iDefaultCol parameter should be passed the index of the table column
117934** that appears on the left-hand-side of the MATCH operator (the default
117935** column to match against for tokens for which a column name is not explicitly
117936** specified as part of the query string), or -1 if tokens may by default
117937** match any table column.
117938*/
117939SQLITE_PRIVATE int sqlite3Fts3ExprParse(
117940  sqlite3_tokenizer *pTokenizer,      /* Tokenizer module */
117941  char **azCol,                       /* Array of column names for fts3 table */
117942  int nCol,                           /* Number of entries in azCol[] */
117943  int iDefaultCol,                    /* Default column to query */
117944  const char *z, int n,               /* Text of MATCH query */
117945  Fts3Expr **ppExpr                   /* OUT: Parsed query structure */
117946){
117947  int nParsed;
117948  int rc;
117949  ParseContext sParse;
117950  sParse.pTokenizer = pTokenizer;
117951  sParse.azCol = (const char **)azCol;
117952  sParse.nCol = nCol;
117953  sParse.iDefaultCol = iDefaultCol;
117954  sParse.nNest = 0;
117955  if( z==0 ){
117956    *ppExpr = 0;
117957    return SQLITE_OK;
117958  }
117959  if( n<0 ){
117960    n = (int)strlen(z);
117961  }
117962  rc = fts3ExprParse(&sParse, z, n, ppExpr, &nParsed);
117963
117964  /* Check for mismatched parenthesis */
117965  if( rc==SQLITE_OK && sParse.nNest ){
117966    rc = SQLITE_ERROR;
117967    sqlite3Fts3ExprFree(*ppExpr);
117968    *ppExpr = 0;
117969  }
117970
117971  return rc;
117972}
117973
117974/*
117975** Free a parsed fts3 query expression allocated by sqlite3Fts3ExprParse().
117976*/
117977SQLITE_PRIVATE void sqlite3Fts3ExprFree(Fts3Expr *p){
117978  if( p ){
117979    sqlite3Fts3ExprFree(p->pLeft);
117980    sqlite3Fts3ExprFree(p->pRight);
117981    sqlite3_free(p->aDoclist);
117982    sqlite3_free(p);
117983  }
117984}
117985
117986/****************************************************************************
117987*****************************************************************************
117988** Everything after this point is just test code.
117989*/
117990
117991#ifdef SQLITE_TEST
117992
117993
117994/*
117995** Function to query the hash-table of tokenizers (see README.tokenizers).
117996*/
117997static int queryTestTokenizer(
117998  sqlite3 *db,
117999  const char *zName,
118000  const sqlite3_tokenizer_module **pp
118001){
118002  int rc;
118003  sqlite3_stmt *pStmt;
118004  const char zSql[] = "SELECT fts3_tokenizer(?)";
118005
118006  *pp = 0;
118007  rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
118008  if( rc!=SQLITE_OK ){
118009    return rc;
118010  }
118011
118012  sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
118013  if( SQLITE_ROW==sqlite3_step(pStmt) ){
118014    if( sqlite3_column_type(pStmt, 0)==SQLITE_BLOB ){
118015      memcpy((void *)pp, sqlite3_column_blob(pStmt, 0), sizeof(*pp));
118016    }
118017  }
118018
118019  return sqlite3_finalize(pStmt);
118020}
118021
118022/*
118023** Return a pointer to a buffer containing a text representation of the
118024** expression passed as the first argument. The buffer is obtained from
118025** sqlite3_malloc(). It is the responsibility of the caller to use
118026** sqlite3_free() to release the memory. If an OOM condition is encountered,
118027** NULL is returned.
118028**
118029** If the second argument is not NULL, then its contents are prepended to
118030** the returned expression text and then freed using sqlite3_free().
118031*/
118032static char *exprToString(Fts3Expr *pExpr, char *zBuf){
118033  switch( pExpr->eType ){
118034    case FTSQUERY_PHRASE: {
118035      Fts3Phrase *pPhrase = pExpr->pPhrase;
118036      int i;
118037      zBuf = sqlite3_mprintf(
118038          "%zPHRASE %d %d", zBuf, pPhrase->iColumn, pPhrase->isNot);
118039      for(i=0; zBuf && i<pPhrase->nToken; i++){
118040        zBuf = sqlite3_mprintf("%z %.*s%s", zBuf,
118041            pPhrase->aToken[i].n, pPhrase->aToken[i].z,
118042            (pPhrase->aToken[i].isPrefix?"+":"")
118043        );
118044      }
118045      return zBuf;
118046    }
118047
118048    case FTSQUERY_NEAR:
118049      zBuf = sqlite3_mprintf("%zNEAR/%d ", zBuf, pExpr->nNear);
118050      break;
118051    case FTSQUERY_NOT:
118052      zBuf = sqlite3_mprintf("%zNOT ", zBuf);
118053      break;
118054    case FTSQUERY_AND:
118055      zBuf = sqlite3_mprintf("%zAND ", zBuf);
118056      break;
118057    case FTSQUERY_OR:
118058      zBuf = sqlite3_mprintf("%zOR ", zBuf);
118059      break;
118060  }
118061
118062  if( zBuf ) zBuf = sqlite3_mprintf("%z{", zBuf);
118063  if( zBuf ) zBuf = exprToString(pExpr->pLeft, zBuf);
118064  if( zBuf ) zBuf = sqlite3_mprintf("%z} {", zBuf);
118065
118066  if( zBuf ) zBuf = exprToString(pExpr->pRight, zBuf);
118067  if( zBuf ) zBuf = sqlite3_mprintf("%z}", zBuf);
118068
118069  return zBuf;
118070}
118071
118072/*
118073** This is the implementation of a scalar SQL function used to test the
118074** expression parser. It should be called as follows:
118075**
118076**   fts3_exprtest(<tokenizer>, <expr>, <column 1>, ...);
118077**
118078** The first argument, <tokenizer>, is the name of the fts3 tokenizer used
118079** to parse the query expression (see README.tokenizers). The second argument
118080** is the query expression to parse. Each subsequent argument is the name
118081** of a column of the fts3 table that the query expression may refer to.
118082** For example:
118083**
118084**   SELECT fts3_exprtest('simple', 'Bill col2:Bloggs', 'col1', 'col2');
118085*/
118086static void fts3ExprTest(
118087  sqlite3_context *context,
118088  int argc,
118089  sqlite3_value **argv
118090){
118091  sqlite3_tokenizer_module const *pModule = 0;
118092  sqlite3_tokenizer *pTokenizer = 0;
118093  int rc;
118094  char **azCol = 0;
118095  const char *zExpr;
118096  int nExpr;
118097  int nCol;
118098  int ii;
118099  Fts3Expr *pExpr;
118100  char *zBuf = 0;
118101  sqlite3 *db = sqlite3_context_db_handle(context);
118102
118103  if( argc<3 ){
118104    sqlite3_result_error(context,
118105        "Usage: fts3_exprtest(tokenizer, expr, col1, ...", -1
118106    );
118107    return;
118108  }
118109
118110  rc = queryTestTokenizer(db,
118111                          (const char *)sqlite3_value_text(argv[0]), &pModule);
118112  if( rc==SQLITE_NOMEM ){
118113    sqlite3_result_error_nomem(context);
118114    goto exprtest_out;
118115  }else if( !pModule ){
118116    sqlite3_result_error(context, "No such tokenizer module", -1);
118117    goto exprtest_out;
118118  }
118119
118120  rc = pModule->xCreate(0, 0, &pTokenizer);
118121  assert( rc==SQLITE_NOMEM || rc==SQLITE_OK );
118122  if( rc==SQLITE_NOMEM ){
118123    sqlite3_result_error_nomem(context);
118124    goto exprtest_out;
118125  }
118126  pTokenizer->pModule = pModule;
118127
118128  zExpr = (const char *)sqlite3_value_text(argv[1]);
118129  nExpr = sqlite3_value_bytes(argv[1]);
118130  nCol = argc-2;
118131  azCol = (char **)sqlite3_malloc(nCol*sizeof(char *));
118132  if( !azCol ){
118133    sqlite3_result_error_nomem(context);
118134    goto exprtest_out;
118135  }
118136  for(ii=0; ii<nCol; ii++){
118137    azCol[ii] = (char *)sqlite3_value_text(argv[ii+2]);
118138  }
118139
118140  rc = sqlite3Fts3ExprParse(
118141      pTokenizer, azCol, nCol, nCol, zExpr, nExpr, &pExpr
118142  );
118143  if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM ){
118144    sqlite3_result_error(context, "Error parsing expression", -1);
118145  }else if( rc==SQLITE_NOMEM || !(zBuf = exprToString(pExpr, 0)) ){
118146    sqlite3_result_error_nomem(context);
118147  }else{
118148    sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
118149    sqlite3_free(zBuf);
118150  }
118151
118152  sqlite3Fts3ExprFree(pExpr);
118153
118154exprtest_out:
118155  if( pModule && pTokenizer ){
118156    rc = pModule->xDestroy(pTokenizer);
118157  }
118158  sqlite3_free(azCol);
118159}
118160
118161/*
118162** Register the query expression parser test function fts3_exprtest()
118163** with database connection db.
118164*/
118165SQLITE_PRIVATE int sqlite3Fts3ExprInitTestInterface(sqlite3* db){
118166  return sqlite3_create_function(
118167      db, "fts3_exprtest", -1, SQLITE_UTF8, 0, fts3ExprTest, 0, 0
118168  );
118169}
118170
118171#endif
118172#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
118173
118174/************** End of fts3_expr.c *******************************************/
118175/************** Begin file fts3_hash.c ***************************************/
118176/*
118177** 2001 September 22
118178**
118179** The author disclaims copyright to this source code.  In place of
118180** a legal notice, here is a blessing:
118181**
118182**    May you do good and not evil.
118183**    May you find forgiveness for yourself and forgive others.
118184**    May you share freely, never taking more than you give.
118185**
118186*************************************************************************
118187** This is the implementation of generic hash-tables used in SQLite.
118188** We've modified it slightly to serve as a standalone hash table
118189** implementation for the full-text indexing module.
118190*/
118191
118192/*
118193** The code in this file is only compiled if:
118194**
118195**     * The FTS3 module is being built as an extension
118196**       (in which case SQLITE_CORE is not defined), or
118197**
118198**     * The FTS3 module is being built into the core of
118199**       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
118200*/
118201#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
118202
118203
118204
118205/*
118206** Malloc and Free functions
118207*/
118208static void *fts3HashMalloc(int n){
118209  void *p = sqlite3_malloc(n);
118210  if( p ){
118211    memset(p, 0, n);
118212  }
118213  return p;
118214}
118215static void fts3HashFree(void *p){
118216  sqlite3_free(p);
118217}
118218
118219/* Turn bulk memory into a hash table object by initializing the
118220** fields of the Hash structure.
118221**
118222** "pNew" is a pointer to the hash table that is to be initialized.
118223** keyClass is one of the constants
118224** FTS3_HASH_BINARY or FTS3_HASH_STRING.  The value of keyClass
118225** determines what kind of key the hash table will use.  "copyKey" is
118226** true if the hash table should make its own private copy of keys and
118227** false if it should just use the supplied pointer.
118228*/
118229SQLITE_PRIVATE void sqlite3Fts3HashInit(Fts3Hash *pNew, char keyClass, char copyKey){
118230  assert( pNew!=0 );
118231  assert( keyClass>=FTS3_HASH_STRING && keyClass<=FTS3_HASH_BINARY );
118232  pNew->keyClass = keyClass;
118233  pNew->copyKey = copyKey;
118234  pNew->first = 0;
118235  pNew->count = 0;
118236  pNew->htsize = 0;
118237  pNew->ht = 0;
118238}
118239
118240/* Remove all entries from a hash table.  Reclaim all memory.
118241** Call this routine to delete a hash table or to reset a hash table
118242** to the empty state.
118243*/
118244SQLITE_PRIVATE void sqlite3Fts3HashClear(Fts3Hash *pH){
118245  Fts3HashElem *elem;         /* For looping over all elements of the table */
118246
118247  assert( pH!=0 );
118248  elem = pH->first;
118249  pH->first = 0;
118250  fts3HashFree(pH->ht);
118251  pH->ht = 0;
118252  pH->htsize = 0;
118253  while( elem ){
118254    Fts3HashElem *next_elem = elem->next;
118255    if( pH->copyKey && elem->pKey ){
118256      fts3HashFree(elem->pKey);
118257    }
118258    fts3HashFree(elem);
118259    elem = next_elem;
118260  }
118261  pH->count = 0;
118262}
118263
118264/*
118265** Hash and comparison functions when the mode is FTS3_HASH_STRING
118266*/
118267static int fts3StrHash(const void *pKey, int nKey){
118268  const char *z = (const char *)pKey;
118269  int h = 0;
118270  if( nKey<=0 ) nKey = (int) strlen(z);
118271  while( nKey > 0  ){
118272    h = (h<<3) ^ h ^ *z++;
118273    nKey--;
118274  }
118275  return h & 0x7fffffff;
118276}
118277static int fts3StrCompare(const void *pKey1, int n1, const void *pKey2, int n2){
118278  if( n1!=n2 ) return 1;
118279  return strncmp((const char*)pKey1,(const char*)pKey2,n1);
118280}
118281
118282/*
118283** Hash and comparison functions when the mode is FTS3_HASH_BINARY
118284*/
118285static int fts3BinHash(const void *pKey, int nKey){
118286  int h = 0;
118287  const char *z = (const char *)pKey;
118288  while( nKey-- > 0 ){
118289    h = (h<<3) ^ h ^ *(z++);
118290  }
118291  return h & 0x7fffffff;
118292}
118293static int fts3BinCompare(const void *pKey1, int n1, const void *pKey2, int n2){
118294  if( n1!=n2 ) return 1;
118295  return memcmp(pKey1,pKey2,n1);
118296}
118297
118298/*
118299** Return a pointer to the appropriate hash function given the key class.
118300**
118301** The C syntax in this function definition may be unfamilar to some
118302** programmers, so we provide the following additional explanation:
118303**
118304** The name of the function is "ftsHashFunction".  The function takes a
118305** single parameter "keyClass".  The return value of ftsHashFunction()
118306** is a pointer to another function.  Specifically, the return value
118307** of ftsHashFunction() is a pointer to a function that takes two parameters
118308** with types "const void*" and "int" and returns an "int".
118309*/
118310static int (*ftsHashFunction(int keyClass))(const void*,int){
118311  if( keyClass==FTS3_HASH_STRING ){
118312    return &fts3StrHash;
118313  }else{
118314    assert( keyClass==FTS3_HASH_BINARY );
118315    return &fts3BinHash;
118316  }
118317}
118318
118319/*
118320** Return a pointer to the appropriate hash function given the key class.
118321**
118322** For help in interpreted the obscure C code in the function definition,
118323** see the header comment on the previous function.
118324*/
118325static int (*ftsCompareFunction(int keyClass))(const void*,int,const void*,int){
118326  if( keyClass==FTS3_HASH_STRING ){
118327    return &fts3StrCompare;
118328  }else{
118329    assert( keyClass==FTS3_HASH_BINARY );
118330    return &fts3BinCompare;
118331  }
118332}
118333
118334/* Link an element into the hash table
118335*/
118336static void fts3HashInsertElement(
118337  Fts3Hash *pH,            /* The complete hash table */
118338  struct _fts3ht *pEntry,  /* The entry into which pNew is inserted */
118339  Fts3HashElem *pNew       /* The element to be inserted */
118340){
118341  Fts3HashElem *pHead;     /* First element already in pEntry */
118342  pHead = pEntry->chain;
118343  if( pHead ){
118344    pNew->next = pHead;
118345    pNew->prev = pHead->prev;
118346    if( pHead->prev ){ pHead->prev->next = pNew; }
118347    else             { pH->first = pNew; }
118348    pHead->prev = pNew;
118349  }else{
118350    pNew->next = pH->first;
118351    if( pH->first ){ pH->first->prev = pNew; }
118352    pNew->prev = 0;
118353    pH->first = pNew;
118354  }
118355  pEntry->count++;
118356  pEntry->chain = pNew;
118357}
118358
118359
118360/* Resize the hash table so that it cantains "new_size" buckets.
118361** "new_size" must be a power of 2.  The hash table might fail
118362** to resize if sqliteMalloc() fails.
118363**
118364** Return non-zero if a memory allocation error occurs.
118365*/
118366static int fts3Rehash(Fts3Hash *pH, int new_size){
118367  struct _fts3ht *new_ht;          /* The new hash table */
118368  Fts3HashElem *elem, *next_elem;  /* For looping over existing elements */
118369  int (*xHash)(const void*,int);   /* The hash function */
118370
118371  assert( (new_size & (new_size-1))==0 );
118372  new_ht = (struct _fts3ht *)fts3HashMalloc( new_size*sizeof(struct _fts3ht) );
118373  if( new_ht==0 ) return 1;
118374  fts3HashFree(pH->ht);
118375  pH->ht = new_ht;
118376  pH->htsize = new_size;
118377  xHash = ftsHashFunction(pH->keyClass);
118378  for(elem=pH->first, pH->first=0; elem; elem = next_elem){
118379    int h = (*xHash)(elem->pKey, elem->nKey) & (new_size-1);
118380    next_elem = elem->next;
118381    fts3HashInsertElement(pH, &new_ht[h], elem);
118382  }
118383  return 0;
118384}
118385
118386/* This function (for internal use only) locates an element in an
118387** hash table that matches the given key.  The hash for this key has
118388** already been computed and is passed as the 4th parameter.
118389*/
118390static Fts3HashElem *fts3FindElementByHash(
118391  const Fts3Hash *pH, /* The pH to be searched */
118392  const void *pKey,   /* The key we are searching for */
118393  int nKey,
118394  int h               /* The hash for this key. */
118395){
118396  Fts3HashElem *elem;            /* Used to loop thru the element list */
118397  int count;                     /* Number of elements left to test */
118398  int (*xCompare)(const void*,int,const void*,int);  /* comparison function */
118399
118400  if( pH->ht ){
118401    struct _fts3ht *pEntry = &pH->ht[h];
118402    elem = pEntry->chain;
118403    count = pEntry->count;
118404    xCompare = ftsCompareFunction(pH->keyClass);
118405    while( count-- && elem ){
118406      if( (*xCompare)(elem->pKey,elem->nKey,pKey,nKey)==0 ){
118407        return elem;
118408      }
118409      elem = elem->next;
118410    }
118411  }
118412  return 0;
118413}
118414
118415/* Remove a single entry from the hash table given a pointer to that
118416** element and a hash on the element's key.
118417*/
118418static void fts3RemoveElementByHash(
118419  Fts3Hash *pH,         /* The pH containing "elem" */
118420  Fts3HashElem* elem,   /* The element to be removed from the pH */
118421  int h                 /* Hash value for the element */
118422){
118423  struct _fts3ht *pEntry;
118424  if( elem->prev ){
118425    elem->prev->next = elem->next;
118426  }else{
118427    pH->first = elem->next;
118428  }
118429  if( elem->next ){
118430    elem->next->prev = elem->prev;
118431  }
118432  pEntry = &pH->ht[h];
118433  if( pEntry->chain==elem ){
118434    pEntry->chain = elem->next;
118435  }
118436  pEntry->count--;
118437  if( pEntry->count<=0 ){
118438    pEntry->chain = 0;
118439  }
118440  if( pH->copyKey && elem->pKey ){
118441    fts3HashFree(elem->pKey);
118442  }
118443  fts3HashFree( elem );
118444  pH->count--;
118445  if( pH->count<=0 ){
118446    assert( pH->first==0 );
118447    assert( pH->count==0 );
118448    fts3HashClear(pH);
118449  }
118450}
118451
118452SQLITE_PRIVATE Fts3HashElem *sqlite3Fts3HashFindElem(
118453  const Fts3Hash *pH,
118454  const void *pKey,
118455  int nKey
118456){
118457  int h;                          /* A hash on key */
118458  int (*xHash)(const void*,int);  /* The hash function */
118459
118460  if( pH==0 || pH->ht==0 ) return 0;
118461  xHash = ftsHashFunction(pH->keyClass);
118462  assert( xHash!=0 );
118463  h = (*xHash)(pKey,nKey);
118464  assert( (pH->htsize & (pH->htsize-1))==0 );
118465  return fts3FindElementByHash(pH,pKey,nKey, h & (pH->htsize-1));
118466}
118467
118468/*
118469** Attempt to locate an element of the hash table pH with a key
118470** that matches pKey,nKey.  Return the data for this element if it is
118471** found, or NULL if there is no match.
118472*/
118473SQLITE_PRIVATE void *sqlite3Fts3HashFind(const Fts3Hash *pH, const void *pKey, int nKey){
118474  Fts3HashElem *pElem;            /* The element that matches key (if any) */
118475
118476  pElem = sqlite3Fts3HashFindElem(pH, pKey, nKey);
118477  return pElem ? pElem->data : 0;
118478}
118479
118480/* Insert an element into the hash table pH.  The key is pKey,nKey
118481** and the data is "data".
118482**
118483** If no element exists with a matching key, then a new
118484** element is created.  A copy of the key is made if the copyKey
118485** flag is set.  NULL is returned.
118486**
118487** If another element already exists with the same key, then the
118488** new data replaces the old data and the old data is returned.
118489** The key is not copied in this instance.  If a malloc fails, then
118490** the new data is returned and the hash table is unchanged.
118491**
118492** If the "data" parameter to this function is NULL, then the
118493** element corresponding to "key" is removed from the hash table.
118494*/
118495SQLITE_PRIVATE void *sqlite3Fts3HashInsert(
118496  Fts3Hash *pH,        /* The hash table to insert into */
118497  const void *pKey,    /* The key */
118498  int nKey,            /* Number of bytes in the key */
118499  void *data           /* The data */
118500){
118501  int hraw;                 /* Raw hash value of the key */
118502  int h;                    /* the hash of the key modulo hash table size */
118503  Fts3HashElem *elem;       /* Used to loop thru the element list */
118504  Fts3HashElem *new_elem;   /* New element added to the pH */
118505  int (*xHash)(const void*,int);  /* The hash function */
118506
118507  assert( pH!=0 );
118508  xHash = ftsHashFunction(pH->keyClass);
118509  assert( xHash!=0 );
118510  hraw = (*xHash)(pKey, nKey);
118511  assert( (pH->htsize & (pH->htsize-1))==0 );
118512  h = hraw & (pH->htsize-1);
118513  elem = fts3FindElementByHash(pH,pKey,nKey,h);
118514  if( elem ){
118515    void *old_data = elem->data;
118516    if( data==0 ){
118517      fts3RemoveElementByHash(pH,elem,h);
118518    }else{
118519      elem->data = data;
118520    }
118521    return old_data;
118522  }
118523  if( data==0 ) return 0;
118524  if( (pH->htsize==0 && fts3Rehash(pH,8))
118525   || (pH->count>=pH->htsize && fts3Rehash(pH, pH->htsize*2))
118526  ){
118527    pH->count = 0;
118528    return data;
118529  }
118530  assert( pH->htsize>0 );
118531  new_elem = (Fts3HashElem*)fts3HashMalloc( sizeof(Fts3HashElem) );
118532  if( new_elem==0 ) return data;
118533  if( pH->copyKey && pKey!=0 ){
118534    new_elem->pKey = fts3HashMalloc( nKey );
118535    if( new_elem->pKey==0 ){
118536      fts3HashFree(new_elem);
118537      return data;
118538    }
118539    memcpy((void*)new_elem->pKey, pKey, nKey);
118540  }else{
118541    new_elem->pKey = (void*)pKey;
118542  }
118543  new_elem->nKey = nKey;
118544  pH->count++;
118545  assert( pH->htsize>0 );
118546  assert( (pH->htsize & (pH->htsize-1))==0 );
118547  h = hraw & (pH->htsize-1);
118548  fts3HashInsertElement(pH, &pH->ht[h], new_elem);
118549  new_elem->data = data;
118550  return 0;
118551}
118552
118553#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
118554
118555/************** End of fts3_hash.c *******************************************/
118556/************** Begin file fts3_porter.c *************************************/
118557/*
118558** 2006 September 30
118559**
118560** The author disclaims copyright to this source code.  In place of
118561** a legal notice, here is a blessing:
118562**
118563**    May you do good and not evil.
118564**    May you find forgiveness for yourself and forgive others.
118565**    May you share freely, never taking more than you give.
118566**
118567*************************************************************************
118568** Implementation of the full-text-search tokenizer that implements
118569** a Porter stemmer.
118570*/
118571
118572/*
118573** The code in this file is only compiled if:
118574**
118575**     * The FTS3 module is being built as an extension
118576**       (in which case SQLITE_CORE is not defined), or
118577**
118578**     * The FTS3 module is being built into the core of
118579**       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
118580*/
118581#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
118582
118583
118584
118585
118586/*
118587** Class derived from sqlite3_tokenizer
118588*/
118589typedef struct porter_tokenizer {
118590  sqlite3_tokenizer base;      /* Base class */
118591} porter_tokenizer;
118592
118593/*
118594** Class derived from sqlit3_tokenizer_cursor
118595*/
118596typedef struct porter_tokenizer_cursor {
118597  sqlite3_tokenizer_cursor base;
118598  const char *zInput;          /* input we are tokenizing */
118599  int nInput;                  /* size of the input */
118600  int iOffset;                 /* current position in zInput */
118601  int iToken;                  /* index of next token to be returned */
118602  char *zToken;                /* storage for current token */
118603  int nAllocated;              /* space allocated to zToken buffer */
118604} porter_tokenizer_cursor;
118605
118606
118607/*
118608** Create a new tokenizer instance.
118609*/
118610static int porterCreate(
118611  int argc, const char * const *argv,
118612  sqlite3_tokenizer **ppTokenizer
118613){
118614  porter_tokenizer *t;
118615
118616  UNUSED_PARAMETER(argc);
118617  UNUSED_PARAMETER(argv);
118618
118619  t = (porter_tokenizer *) sqlite3_malloc(sizeof(*t));
118620  if( t==NULL ) return SQLITE_NOMEM;
118621  memset(t, 0, sizeof(*t));
118622  *ppTokenizer = &t->base;
118623  return SQLITE_OK;
118624}
118625
118626/*
118627** Destroy a tokenizer
118628*/
118629static int porterDestroy(sqlite3_tokenizer *pTokenizer){
118630  sqlite3_free(pTokenizer);
118631  return SQLITE_OK;
118632}
118633
118634/*
118635** Prepare to begin tokenizing a particular string.  The input
118636** string to be tokenized is zInput[0..nInput-1].  A cursor
118637** used to incrementally tokenize this string is returned in
118638** *ppCursor.
118639*/
118640static int porterOpen(
118641  sqlite3_tokenizer *pTokenizer,         /* The tokenizer */
118642  const char *zInput, int nInput,        /* String to be tokenized */
118643  sqlite3_tokenizer_cursor **ppCursor    /* OUT: Tokenization cursor */
118644){
118645  porter_tokenizer_cursor *c;
118646
118647  UNUSED_PARAMETER(pTokenizer);
118648
118649  c = (porter_tokenizer_cursor *) sqlite3_malloc(sizeof(*c));
118650  if( c==NULL ) return SQLITE_NOMEM;
118651
118652  c->zInput = zInput;
118653  if( zInput==0 ){
118654    c->nInput = 0;
118655  }else if( nInput<0 ){
118656    c->nInput = (int)strlen(zInput);
118657  }else{
118658    c->nInput = nInput;
118659  }
118660  c->iOffset = 0;                 /* start tokenizing at the beginning */
118661  c->iToken = 0;
118662  c->zToken = NULL;               /* no space allocated, yet. */
118663  c->nAllocated = 0;
118664
118665  *ppCursor = &c->base;
118666  return SQLITE_OK;
118667}
118668
118669/*
118670** Close a tokenization cursor previously opened by a call to
118671** porterOpen() above.
118672*/
118673static int porterClose(sqlite3_tokenizer_cursor *pCursor){
118674  porter_tokenizer_cursor *c = (porter_tokenizer_cursor *) pCursor;
118675  sqlite3_free(c->zToken);
118676  sqlite3_free(c);
118677  return SQLITE_OK;
118678}
118679/*
118680** Vowel or consonant
118681*/
118682static const char vOrCType[] = {
118683   0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0,
118684   1, 1, 1, 2, 1
118685};
118686
118687/*
118688** isConsonant() and isVowel() determine if their first character in
118689** the string they point to is a consonant or a vowel, according
118690** to Porter ruls.
118691**
118692** A consonate is any letter other than 'a', 'e', 'i', 'o', or 'u'.
118693** 'Y' is a consonant unless it follows another consonant,
118694** in which case it is a vowel.
118695**
118696** In these routine, the letters are in reverse order.  So the 'y' rule
118697** is that 'y' is a consonant unless it is followed by another
118698** consonent.
118699*/
118700static int isVowel(const char*);
118701static int isConsonant(const char *z){
118702  int j;
118703  char x = *z;
118704  if( x==0 ) return 0;
118705  assert( x>='a' && x<='z' );
118706  j = vOrCType[x-'a'];
118707  if( j<2 ) return j;
118708  return z[1]==0 || isVowel(z + 1);
118709}
118710static int isVowel(const char *z){
118711  int j;
118712  char x = *z;
118713  if( x==0 ) return 0;
118714  assert( x>='a' && x<='z' );
118715  j = vOrCType[x-'a'];
118716  if( j<2 ) return 1-j;
118717  return isConsonant(z + 1);
118718}
118719
118720/*
118721** Let any sequence of one or more vowels be represented by V and let
118722** C be sequence of one or more consonants.  Then every word can be
118723** represented as:
118724**
118725**           [C] (VC){m} [V]
118726**
118727** In prose:  A word is an optional consonant followed by zero or
118728** vowel-consonant pairs followed by an optional vowel.  "m" is the
118729** number of vowel consonant pairs.  This routine computes the value
118730** of m for the first i bytes of a word.
118731**
118732** Return true if the m-value for z is 1 or more.  In other words,
118733** return true if z contains at least one vowel that is followed
118734** by a consonant.
118735**
118736** In this routine z[] is in reverse order.  So we are really looking
118737** for an instance of of a consonant followed by a vowel.
118738*/
118739static int m_gt_0(const char *z){
118740  while( isVowel(z) ){ z++; }
118741  if( *z==0 ) return 0;
118742  while( isConsonant(z) ){ z++; }
118743  return *z!=0;
118744}
118745
118746/* Like mgt0 above except we are looking for a value of m which is
118747** exactly 1
118748*/
118749static int m_eq_1(const char *z){
118750  while( isVowel(z) ){ z++; }
118751  if( *z==0 ) return 0;
118752  while( isConsonant(z) ){ z++; }
118753  if( *z==0 ) return 0;
118754  while( isVowel(z) ){ z++; }
118755  if( *z==0 ) return 1;
118756  while( isConsonant(z) ){ z++; }
118757  return *z==0;
118758}
118759
118760/* Like mgt0 above except we are looking for a value of m>1 instead
118761** or m>0
118762*/
118763static int m_gt_1(const char *z){
118764  while( isVowel(z) ){ z++; }
118765  if( *z==0 ) return 0;
118766  while( isConsonant(z) ){ z++; }
118767  if( *z==0 ) return 0;
118768  while( isVowel(z) ){ z++; }
118769  if( *z==0 ) return 0;
118770  while( isConsonant(z) ){ z++; }
118771  return *z!=0;
118772}
118773
118774/*
118775** Return TRUE if there is a vowel anywhere within z[0..n-1]
118776*/
118777static int hasVowel(const char *z){
118778  while( isConsonant(z) ){ z++; }
118779  return *z!=0;
118780}
118781
118782/*
118783** Return TRUE if the word ends in a double consonant.
118784**
118785** The text is reversed here. So we are really looking at
118786** the first two characters of z[].
118787*/
118788static int doubleConsonant(const char *z){
118789  return isConsonant(z) && z[0]==z[1];
118790}
118791
118792/*
118793** Return TRUE if the word ends with three letters which
118794** are consonant-vowel-consonent and where the final consonant
118795** is not 'w', 'x', or 'y'.
118796**
118797** The word is reversed here.  So we are really checking the
118798** first three letters and the first one cannot be in [wxy].
118799*/
118800static int star_oh(const char *z){
118801  return
118802    isConsonant(z) &&
118803    z[0]!='w' && z[0]!='x' && z[0]!='y' &&
118804    isVowel(z+1) &&
118805    isConsonant(z+2);
118806}
118807
118808/*
118809** If the word ends with zFrom and xCond() is true for the stem
118810** of the word that preceeds the zFrom ending, then change the
118811** ending to zTo.
118812**
118813** The input word *pz and zFrom are both in reverse order.  zTo
118814** is in normal order.
118815**
118816** Return TRUE if zFrom matches.  Return FALSE if zFrom does not
118817** match.  Not that TRUE is returned even if xCond() fails and
118818** no substitution occurs.
118819*/
118820static int stem(
118821  char **pz,             /* The word being stemmed (Reversed) */
118822  const char *zFrom,     /* If the ending matches this... (Reversed) */
118823  const char *zTo,       /* ... change the ending to this (not reversed) */
118824  int (*xCond)(const char*)   /* Condition that must be true */
118825){
118826  char *z = *pz;
118827  while( *zFrom && *zFrom==*z ){ z++; zFrom++; }
118828  if( *zFrom!=0 ) return 0;
118829  if( xCond && !xCond(z) ) return 1;
118830  while( *zTo ){
118831    *(--z) = *(zTo++);
118832  }
118833  *pz = z;
118834  return 1;
118835}
118836
118837/*
118838** This is the fallback stemmer used when the porter stemmer is
118839** inappropriate.  The input word is copied into the output with
118840** US-ASCII case folding.  If the input word is too long (more
118841** than 20 bytes if it contains no digits or more than 6 bytes if
118842** it contains digits) then word is truncated to 20 or 6 bytes
118843** by taking 10 or 3 bytes from the beginning and end.
118844*/
118845static void copy_stemmer(const char *zIn, int nIn, char *zOut, int *pnOut){
118846  int i, mx, j;
118847  int hasDigit = 0;
118848  for(i=0; i<nIn; i++){
118849    char c = zIn[i];
118850    if( c>='A' && c<='Z' ){
118851      zOut[i] = c - 'A' + 'a';
118852    }else{
118853      if( c>='0' && c<='9' ) hasDigit = 1;
118854      zOut[i] = c;
118855    }
118856  }
118857  mx = hasDigit ? 3 : 10;
118858  if( nIn>mx*2 ){
118859    for(j=mx, i=nIn-mx; i<nIn; i++, j++){
118860      zOut[j] = zOut[i];
118861    }
118862    i = j;
118863  }
118864  zOut[i] = 0;
118865  *pnOut = i;
118866}
118867
118868
118869/*
118870** Stem the input word zIn[0..nIn-1].  Store the output in zOut.
118871** zOut is at least big enough to hold nIn bytes.  Write the actual
118872** size of the output word (exclusive of the '\0' terminator) into *pnOut.
118873**
118874** Any upper-case characters in the US-ASCII character set ([A-Z])
118875** are converted to lower case.  Upper-case UTF characters are
118876** unchanged.
118877**
118878** Words that are longer than about 20 bytes are stemmed by retaining
118879** a few bytes from the beginning and the end of the word.  If the
118880** word contains digits, 3 bytes are taken from the beginning and
118881** 3 bytes from the end.  For long words without digits, 10 bytes
118882** are taken from each end.  US-ASCII case folding still applies.
118883**
118884** If the input word contains not digits but does characters not
118885** in [a-zA-Z] then no stemming is attempted and this routine just
118886** copies the input into the input into the output with US-ASCII
118887** case folding.
118888**
118889** Stemming never increases the length of the word.  So there is
118890** no chance of overflowing the zOut buffer.
118891*/
118892static void porter_stemmer(const char *zIn, int nIn, char *zOut, int *pnOut){
118893  int i, j;
118894  char zReverse[28];
118895  char *z, *z2;
118896  if( nIn<3 || nIn>=(int)sizeof(zReverse)-7 ){
118897    /* The word is too big or too small for the porter stemmer.
118898    ** Fallback to the copy stemmer */
118899    copy_stemmer(zIn, nIn, zOut, pnOut);
118900    return;
118901  }
118902  for(i=0, j=sizeof(zReverse)-6; i<nIn; i++, j--){
118903    char c = zIn[i];
118904    if( c>='A' && c<='Z' ){
118905      zReverse[j] = c + 'a' - 'A';
118906    }else if( c>='a' && c<='z' ){
118907      zReverse[j] = c;
118908    }else{
118909      /* The use of a character not in [a-zA-Z] means that we fallback
118910      ** to the copy stemmer */
118911      copy_stemmer(zIn, nIn, zOut, pnOut);
118912      return;
118913    }
118914  }
118915  memset(&zReverse[sizeof(zReverse)-5], 0, 5);
118916  z = &zReverse[j+1];
118917
118918
118919  /* Step 1a */
118920  if( z[0]=='s' ){
118921    if(
118922     !stem(&z, "sess", "ss", 0) &&
118923     !stem(&z, "sei", "i", 0)  &&
118924     !stem(&z, "ss", "ss", 0)
118925    ){
118926      z++;
118927    }
118928  }
118929
118930  /* Step 1b */
118931  z2 = z;
118932  if( stem(&z, "dee", "ee", m_gt_0) ){
118933    /* Do nothing.  The work was all in the test */
118934  }else if(
118935     (stem(&z, "gni", "", hasVowel) || stem(&z, "de", "", hasVowel))
118936      && z!=z2
118937  ){
118938     if( stem(&z, "ta", "ate", 0) ||
118939         stem(&z, "lb", "ble", 0) ||
118940         stem(&z, "zi", "ize", 0) ){
118941       /* Do nothing.  The work was all in the test */
118942     }else if( doubleConsonant(z) && (*z!='l' && *z!='s' && *z!='z') ){
118943       z++;
118944     }else if( m_eq_1(z) && star_oh(z) ){
118945       *(--z) = 'e';
118946     }
118947  }
118948
118949  /* Step 1c */
118950  if( z[0]=='y' && hasVowel(z+1) ){
118951    z[0] = 'i';
118952  }
118953
118954  /* Step 2 */
118955  switch( z[1] ){
118956   case 'a':
118957     stem(&z, "lanoita", "ate", m_gt_0) ||
118958     stem(&z, "lanoit", "tion", m_gt_0);
118959     break;
118960   case 'c':
118961     stem(&z, "icne", "ence", m_gt_0) ||
118962     stem(&z, "icna", "ance", m_gt_0);
118963     break;
118964   case 'e':
118965     stem(&z, "rezi", "ize", m_gt_0);
118966     break;
118967   case 'g':
118968     stem(&z, "igol", "log", m_gt_0);
118969     break;
118970   case 'l':
118971     stem(&z, "ilb", "ble", m_gt_0) ||
118972     stem(&z, "illa", "al", m_gt_0) ||
118973     stem(&z, "iltne", "ent", m_gt_0) ||
118974     stem(&z, "ile", "e", m_gt_0) ||
118975     stem(&z, "ilsuo", "ous", m_gt_0);
118976     break;
118977   case 'o':
118978     stem(&z, "noitazi", "ize", m_gt_0) ||
118979     stem(&z, "noita", "ate", m_gt_0) ||
118980     stem(&z, "rota", "ate", m_gt_0);
118981     break;
118982   case 's':
118983     stem(&z, "msila", "al", m_gt_0) ||
118984     stem(&z, "ssenevi", "ive", m_gt_0) ||
118985     stem(&z, "ssenluf", "ful", m_gt_0) ||
118986     stem(&z, "ssensuo", "ous", m_gt_0);
118987     break;
118988   case 't':
118989     stem(&z, "itila", "al", m_gt_0) ||
118990     stem(&z, "itivi", "ive", m_gt_0) ||
118991     stem(&z, "itilib", "ble", m_gt_0);
118992     break;
118993  }
118994
118995  /* Step 3 */
118996  switch( z[0] ){
118997   case 'e':
118998     stem(&z, "etaci", "ic", m_gt_0) ||
118999     stem(&z, "evita", "", m_gt_0)   ||
119000     stem(&z, "ezila", "al", m_gt_0);
119001     break;
119002   case 'i':
119003     stem(&z, "itici", "ic", m_gt_0);
119004     break;
119005   case 'l':
119006     stem(&z, "laci", "ic", m_gt_0) ||
119007     stem(&z, "luf", "", m_gt_0);
119008     break;
119009   case 's':
119010     stem(&z, "ssen", "", m_gt_0);
119011     break;
119012  }
119013
119014  /* Step 4 */
119015  switch( z[1] ){
119016   case 'a':
119017     if( z[0]=='l' && m_gt_1(z+2) ){
119018       z += 2;
119019     }
119020     break;
119021   case 'c':
119022     if( z[0]=='e' && z[2]=='n' && (z[3]=='a' || z[3]=='e')  && m_gt_1(z+4)  ){
119023       z += 4;
119024     }
119025     break;
119026   case 'e':
119027     if( z[0]=='r' && m_gt_1(z+2) ){
119028       z += 2;
119029     }
119030     break;
119031   case 'i':
119032     if( z[0]=='c' && m_gt_1(z+2) ){
119033       z += 2;
119034     }
119035     break;
119036   case 'l':
119037     if( z[0]=='e' && z[2]=='b' && (z[3]=='a' || z[3]=='i') && m_gt_1(z+4) ){
119038       z += 4;
119039     }
119040     break;
119041   case 'n':
119042     if( z[0]=='t' ){
119043       if( z[2]=='a' ){
119044         if( m_gt_1(z+3) ){
119045           z += 3;
119046         }
119047       }else if( z[2]=='e' ){
119048         stem(&z, "tneme", "", m_gt_1) ||
119049         stem(&z, "tnem", "", m_gt_1) ||
119050         stem(&z, "tne", "", m_gt_1);
119051       }
119052     }
119053     break;
119054   case 'o':
119055     if( z[0]=='u' ){
119056       if( m_gt_1(z+2) ){
119057         z += 2;
119058       }
119059     }else if( z[3]=='s' || z[3]=='t' ){
119060       stem(&z, "noi", "", m_gt_1);
119061     }
119062     break;
119063   case 's':
119064     if( z[0]=='m' && z[2]=='i' && m_gt_1(z+3) ){
119065       z += 3;
119066     }
119067     break;
119068   case 't':
119069     stem(&z, "eta", "", m_gt_1) ||
119070     stem(&z, "iti", "", m_gt_1);
119071     break;
119072   case 'u':
119073     if( z[0]=='s' && z[2]=='o' && m_gt_1(z+3) ){
119074       z += 3;
119075     }
119076     break;
119077   case 'v':
119078   case 'z':
119079     if( z[0]=='e' && z[2]=='i' && m_gt_1(z+3) ){
119080       z += 3;
119081     }
119082     break;
119083  }
119084
119085  /* Step 5a */
119086  if( z[0]=='e' ){
119087    if( m_gt_1(z+1) ){
119088      z++;
119089    }else if( m_eq_1(z+1) && !star_oh(z+1) ){
119090      z++;
119091    }
119092  }
119093
119094  /* Step 5b */
119095  if( m_gt_1(z) && z[0]=='l' && z[1]=='l' ){
119096    z++;
119097  }
119098
119099  /* z[] is now the stemmed word in reverse order.  Flip it back
119100  ** around into forward order and return.
119101  */
119102  *pnOut = i = (int)strlen(z);
119103  zOut[i] = 0;
119104  while( *z ){
119105    zOut[--i] = *(z++);
119106  }
119107}
119108
119109/*
119110** Characters that can be part of a token.  We assume any character
119111** whose value is greater than 0x80 (any UTF character) can be
119112** part of a token.  In other words, delimiters all must have
119113** values of 0x7f or lower.
119114*/
119115static const char porterIdChar[] = {
119116/* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
119117    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,  /* 3x */
119118    0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 4x */
119119    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1,  /* 5x */
119120    0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 6x */
119121    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0,  /* 7x */
119122};
119123#define isDelim(C) (((ch=C)&0x80)==0 && (ch<0x30 || !porterIdChar[ch-0x30]))
119124
119125/*
119126** Extract the next token from a tokenization cursor.  The cursor must
119127** have been opened by a prior call to porterOpen().
119128*/
119129static int porterNext(
119130  sqlite3_tokenizer_cursor *pCursor,  /* Cursor returned by porterOpen */
119131  const char **pzToken,               /* OUT: *pzToken is the token text */
119132  int *pnBytes,                       /* OUT: Number of bytes in token */
119133  int *piStartOffset,                 /* OUT: Starting offset of token */
119134  int *piEndOffset,                   /* OUT: Ending offset of token */
119135  int *piPosition                     /* OUT: Position integer of token */
119136){
119137  porter_tokenizer_cursor *c = (porter_tokenizer_cursor *) pCursor;
119138  const char *z = c->zInput;
119139
119140  while( c->iOffset<c->nInput ){
119141    int iStartOffset, ch;
119142
119143    /* Scan past delimiter characters */
119144    while( c->iOffset<c->nInput && isDelim(z[c->iOffset]) ){
119145      c->iOffset++;
119146    }
119147
119148    /* Count non-delimiter characters. */
119149    iStartOffset = c->iOffset;
119150    while( c->iOffset<c->nInput && !isDelim(z[c->iOffset]) ){
119151      c->iOffset++;
119152    }
119153
119154    if( c->iOffset>iStartOffset ){
119155      int n = c->iOffset-iStartOffset;
119156      if( n>c->nAllocated ){
119157        char *pNew;
119158        c->nAllocated = n+20;
119159        pNew = sqlite3_realloc(c->zToken, c->nAllocated);
119160        if( !pNew ) return SQLITE_NOMEM;
119161        c->zToken = pNew;
119162      }
119163      porter_stemmer(&z[iStartOffset], n, c->zToken, pnBytes);
119164      *pzToken = c->zToken;
119165      *piStartOffset = iStartOffset;
119166      *piEndOffset = c->iOffset;
119167      *piPosition = c->iToken++;
119168      return SQLITE_OK;
119169    }
119170  }
119171  return SQLITE_DONE;
119172}
119173
119174/*
119175** The set of routines that implement the porter-stemmer tokenizer
119176*/
119177static const sqlite3_tokenizer_module porterTokenizerModule = {
119178  0,
119179  porterCreate,
119180  porterDestroy,
119181  porterOpen,
119182  porterClose,
119183  porterNext,
119184};
119185
119186/*
119187** Allocate a new porter tokenizer.  Return a pointer to the new
119188** tokenizer in *ppModule
119189*/
119190SQLITE_PRIVATE void sqlite3Fts3PorterTokenizerModule(
119191  sqlite3_tokenizer_module const**ppModule
119192){
119193  *ppModule = &porterTokenizerModule;
119194}
119195
119196#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
119197
119198/************** End of fts3_porter.c *****************************************/
119199/************** Begin file fts3_tokenizer.c **********************************/
119200/*
119201** 2007 June 22
119202**
119203** The author disclaims copyright to this source code.  In place of
119204** a legal notice, here is a blessing:
119205**
119206**    May you do good and not evil.
119207**    May you find forgiveness for yourself and forgive others.
119208**    May you share freely, never taking more than you give.
119209**
119210******************************************************************************
119211**
119212** This is part of an SQLite module implementing full-text search.
119213** This particular file implements the generic tokenizer interface.
119214*/
119215
119216/*
119217** The code in this file is only compiled if:
119218**
119219**     * The FTS3 module is being built as an extension
119220**       (in which case SQLITE_CORE is not defined), or
119221**
119222**     * The FTS3 module is being built into the core of
119223**       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
119224*/
119225#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
119226
119227#ifndef SQLITE_CORE
119228  SQLITE_EXTENSION_INIT1
119229#endif
119230
119231
119232/*
119233** Implementation of the SQL scalar function for accessing the underlying
119234** hash table. This function may be called as follows:
119235**
119236**   SELECT <function-name>(<key-name>);
119237**   SELECT <function-name>(<key-name>, <pointer>);
119238**
119239** where <function-name> is the name passed as the second argument
119240** to the sqlite3Fts3InitHashTable() function (e.g. 'fts3_tokenizer').
119241**
119242** If the <pointer> argument is specified, it must be a blob value
119243** containing a pointer to be stored as the hash data corresponding
119244** to the string <key-name>. If <pointer> is not specified, then
119245** the string <key-name> must already exist in the has table. Otherwise,
119246** an error is returned.
119247**
119248** Whether or not the <pointer> argument is specified, the value returned
119249** is a blob containing the pointer stored as the hash data corresponding
119250** to string <key-name> (after the hash-table is updated, if applicable).
119251*/
119252static void scalarFunc(
119253  sqlite3_context *context,
119254  int argc,
119255  sqlite3_value **argv
119256){
119257  Fts3Hash *pHash;
119258  void *pPtr = 0;
119259  const unsigned char *zName;
119260  int nName;
119261
119262  assert( argc==1 || argc==2 );
119263
119264  pHash = (Fts3Hash *)sqlite3_user_data(context);
119265
119266  zName = sqlite3_value_text(argv[0]);
119267  nName = sqlite3_value_bytes(argv[0])+1;
119268
119269  if( argc==2 ){
119270    void *pOld;
119271    int n = sqlite3_value_bytes(argv[1]);
119272    if( n!=sizeof(pPtr) ){
119273      sqlite3_result_error(context, "argument type mismatch", -1);
119274      return;
119275    }
119276    pPtr = *(void **)sqlite3_value_blob(argv[1]);
119277    pOld = sqlite3Fts3HashInsert(pHash, (void *)zName, nName, pPtr);
119278    if( pOld==pPtr ){
119279      sqlite3_result_error(context, "out of memory", -1);
119280      return;
119281    }
119282  }else{
119283    pPtr = sqlite3Fts3HashFind(pHash, zName, nName);
119284    if( !pPtr ){
119285      char *zErr = sqlite3_mprintf("unknown tokenizer: %s", zName);
119286      sqlite3_result_error(context, zErr, -1);
119287      sqlite3_free(zErr);
119288      return;
119289    }
119290  }
119291
119292  sqlite3_result_blob(context, (void *)&pPtr, sizeof(pPtr), SQLITE_TRANSIENT);
119293}
119294
119295SQLITE_PRIVATE int sqlite3Fts3IsIdChar(char c){
119296  static const char isFtsIdChar[] = {
119297      0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* 0x */
119298      0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* 1x */
119299      0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* 2x */
119300      1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,  /* 3x */
119301      0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 4x */
119302      1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1,  /* 5x */
119303      0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 6x */
119304      1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0,  /* 7x */
119305  };
119306  return (c&0x80 || isFtsIdChar[(int)(c)]);
119307}
119308
119309SQLITE_PRIVATE const char *sqlite3Fts3NextToken(const char *zStr, int *pn){
119310  const char *z1;
119311  const char *z2 = 0;
119312
119313  /* Find the start of the next token. */
119314  z1 = zStr;
119315  while( z2==0 ){
119316    char c = *z1;
119317    switch( c ){
119318      case '\0': return 0;        /* No more tokens here */
119319      case '\'':
119320      case '"':
119321      case '`': {
119322        z2 = z1;
119323        while( *++z2 && (*z2!=c || *++z2==c) );
119324        break;
119325      }
119326      case '[':
119327        z2 = &z1[1];
119328        while( *z2 && z2[0]!=']' ) z2++;
119329        if( *z2 ) z2++;
119330        break;
119331
119332      default:
119333        if( sqlite3Fts3IsIdChar(*z1) ){
119334          z2 = &z1[1];
119335          while( sqlite3Fts3IsIdChar(*z2) ) z2++;
119336        }else{
119337          z1++;
119338        }
119339    }
119340  }
119341
119342  *pn = (int)(z2-z1);
119343  return z1;
119344}
119345
119346SQLITE_PRIVATE int sqlite3Fts3InitTokenizer(
119347  Fts3Hash *pHash,                /* Tokenizer hash table */
119348  const char *zArg,               /* Tokenizer name */
119349  sqlite3_tokenizer **ppTok,      /* OUT: Tokenizer (if applicable) */
119350  char **pzErr                    /* OUT: Set to malloced error message */
119351){
119352  int rc;
119353  char *z = (char *)zArg;
119354  int n;
119355  char *zCopy;
119356  char *zEnd;                     /* Pointer to nul-term of zCopy */
119357  sqlite3_tokenizer_module *m;
119358
119359  zCopy = sqlite3_mprintf("%s", zArg);
119360  if( !zCopy ) return SQLITE_NOMEM;
119361  zEnd = &zCopy[strlen(zCopy)];
119362
119363  z = (char *)sqlite3Fts3NextToken(zCopy, &n);
119364  z[n] = '\0';
119365  sqlite3Fts3Dequote(z);
119366
119367  m = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash,z,(int)strlen(z)+1);
119368  if( !m ){
119369    *pzErr = sqlite3_mprintf("unknown tokenizer: %s", z);
119370    rc = SQLITE_ERROR;
119371  }else{
119372    char const **aArg = 0;
119373    int iArg = 0;
119374    z = &z[n+1];
119375    while( z<zEnd && (NULL!=(z = (char *)sqlite3Fts3NextToken(z, &n))) ){
119376      int nNew = sizeof(char *)*(iArg+1);
119377      char const **aNew = (const char **)sqlite3_realloc((void *)aArg, nNew);
119378      if( !aNew ){
119379        sqlite3_free(zCopy);
119380        sqlite3_free((void *)aArg);
119381        return SQLITE_NOMEM;
119382      }
119383      aArg = aNew;
119384      aArg[iArg++] = z;
119385      z[n] = '\0';
119386      sqlite3Fts3Dequote(z);
119387      z = &z[n+1];
119388    }
119389    rc = m->xCreate(iArg, aArg, ppTok);
119390    assert( rc!=SQLITE_OK || *ppTok );
119391    if( rc!=SQLITE_OK ){
119392      *pzErr = sqlite3_mprintf("unknown tokenizer");
119393    }else{
119394      (*ppTok)->pModule = m;
119395    }
119396    sqlite3_free((void *)aArg);
119397  }
119398
119399  sqlite3_free(zCopy);
119400  return rc;
119401}
119402
119403
119404#ifdef SQLITE_TEST
119405
119406
119407/*
119408** Implementation of a special SQL scalar function for testing tokenizers
119409** designed to be used in concert with the Tcl testing framework. This
119410** function must be called with two arguments:
119411**
119412**   SELECT <function-name>(<key-name>, <input-string>);
119413**   SELECT <function-name>(<key-name>, <pointer>);
119414**
119415** where <function-name> is the name passed as the second argument
119416** to the sqlite3Fts3InitHashTable() function (e.g. 'fts3_tokenizer')
119417** concatenated with the string '_test' (e.g. 'fts3_tokenizer_test').
119418**
119419** The return value is a string that may be interpreted as a Tcl
119420** list. For each token in the <input-string>, three elements are
119421** added to the returned list. The first is the token position, the
119422** second is the token text (folded, stemmed, etc.) and the third is the
119423** substring of <input-string> associated with the token. For example,
119424** using the built-in "simple" tokenizer:
119425**
119426**   SELECT fts_tokenizer_test('simple', 'I don't see how');
119427**
119428** will return the string:
119429**
119430**   "{0 i I 1 dont don't 2 see see 3 how how}"
119431**
119432*/
119433static void testFunc(
119434  sqlite3_context *context,
119435  int argc,
119436  sqlite3_value **argv
119437){
119438  Fts3Hash *pHash;
119439  sqlite3_tokenizer_module *p;
119440  sqlite3_tokenizer *pTokenizer = 0;
119441  sqlite3_tokenizer_cursor *pCsr = 0;
119442
119443  const char *zErr = 0;
119444
119445  const char *zName;
119446  int nName;
119447  const char *zInput;
119448  int nInput;
119449
119450  const char *zArg = 0;
119451
119452  const char *zToken;
119453  int nToken;
119454  int iStart;
119455  int iEnd;
119456  int iPos;
119457
119458  Tcl_Obj *pRet;
119459
119460  assert( argc==2 || argc==3 );
119461
119462  nName = sqlite3_value_bytes(argv[0]);
119463  zName = (const char *)sqlite3_value_text(argv[0]);
119464  nInput = sqlite3_value_bytes(argv[argc-1]);
119465  zInput = (const char *)sqlite3_value_text(argv[argc-1]);
119466
119467  if( argc==3 ){
119468    zArg = (const char *)sqlite3_value_text(argv[1]);
119469  }
119470
119471  pHash = (Fts3Hash *)sqlite3_user_data(context);
119472  p = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash, zName, nName+1);
119473
119474  if( !p ){
119475    char *zErr = sqlite3_mprintf("unknown tokenizer: %s", zName);
119476    sqlite3_result_error(context, zErr, -1);
119477    sqlite3_free(zErr);
119478    return;
119479  }
119480
119481  pRet = Tcl_NewObj();
119482  Tcl_IncrRefCount(pRet);
119483
119484  if( SQLITE_OK!=p->xCreate(zArg ? 1 : 0, &zArg, &pTokenizer) ){
119485    zErr = "error in xCreate()";
119486    goto finish;
119487  }
119488  pTokenizer->pModule = p;
119489  if( SQLITE_OK!=p->xOpen(pTokenizer, zInput, nInput, &pCsr) ){
119490    zErr = "error in xOpen()";
119491    goto finish;
119492  }
119493  pCsr->pTokenizer = pTokenizer;
119494
119495  while( SQLITE_OK==p->xNext(pCsr, &zToken, &nToken, &iStart, &iEnd, &iPos) ){
119496    Tcl_ListObjAppendElement(0, pRet, Tcl_NewIntObj(iPos));
119497    Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zToken, nToken));
119498    zToken = &zInput[iStart];
119499    nToken = iEnd-iStart;
119500    Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zToken, nToken));
119501  }
119502
119503  if( SQLITE_OK!=p->xClose(pCsr) ){
119504    zErr = "error in xClose()";
119505    goto finish;
119506  }
119507  if( SQLITE_OK!=p->xDestroy(pTokenizer) ){
119508    zErr = "error in xDestroy()";
119509    goto finish;
119510  }
119511
119512finish:
119513  if( zErr ){
119514    sqlite3_result_error(context, zErr, -1);
119515  }else{
119516    sqlite3_result_text(context, Tcl_GetString(pRet), -1, SQLITE_TRANSIENT);
119517  }
119518  Tcl_DecrRefCount(pRet);
119519}
119520
119521static
119522int registerTokenizer(
119523  sqlite3 *db,
119524  char *zName,
119525  const sqlite3_tokenizer_module *p
119526){
119527  int rc;
119528  sqlite3_stmt *pStmt;
119529  const char zSql[] = "SELECT fts3_tokenizer(?, ?)";
119530
119531  rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
119532  if( rc!=SQLITE_OK ){
119533    return rc;
119534  }
119535
119536  sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
119537  sqlite3_bind_blob(pStmt, 2, &p, sizeof(p), SQLITE_STATIC);
119538  sqlite3_step(pStmt);
119539
119540  return sqlite3_finalize(pStmt);
119541}
119542
119543static
119544int queryTokenizer(
119545  sqlite3 *db,
119546  char *zName,
119547  const sqlite3_tokenizer_module **pp
119548){
119549  int rc;
119550  sqlite3_stmt *pStmt;
119551  const char zSql[] = "SELECT fts3_tokenizer(?)";
119552
119553  *pp = 0;
119554  rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
119555  if( rc!=SQLITE_OK ){
119556    return rc;
119557  }
119558
119559  sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
119560  if( SQLITE_ROW==sqlite3_step(pStmt) ){
119561    if( sqlite3_column_type(pStmt, 0)==SQLITE_BLOB ){
119562      memcpy((void *)pp, sqlite3_column_blob(pStmt, 0), sizeof(*pp));
119563    }
119564  }
119565
119566  return sqlite3_finalize(pStmt);
119567}
119568
119569SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule);
119570
119571/*
119572** Implementation of the scalar function fts3_tokenizer_internal_test().
119573** This function is used for testing only, it is not included in the
119574** build unless SQLITE_TEST is defined.
119575**
119576** The purpose of this is to test that the fts3_tokenizer() function
119577** can be used as designed by the C-code in the queryTokenizer and
119578** registerTokenizer() functions above. These two functions are repeated
119579** in the README.tokenizer file as an example, so it is important to
119580** test them.
119581**
119582** To run the tests, evaluate the fts3_tokenizer_internal_test() scalar
119583** function with no arguments. An assert() will fail if a problem is
119584** detected. i.e.:
119585**
119586**     SELECT fts3_tokenizer_internal_test();
119587**
119588*/
119589static void intTestFunc(
119590  sqlite3_context *context,
119591  int argc,
119592  sqlite3_value **argv
119593){
119594  int rc;
119595  const sqlite3_tokenizer_module *p1;
119596  const sqlite3_tokenizer_module *p2;
119597  sqlite3 *db = (sqlite3 *)sqlite3_user_data(context);
119598
119599  UNUSED_PARAMETER(argc);
119600  UNUSED_PARAMETER(argv);
119601
119602  /* Test the query function */
119603  sqlite3Fts3SimpleTokenizerModule(&p1);
119604  rc = queryTokenizer(db, "simple", &p2);
119605  assert( rc==SQLITE_OK );
119606  assert( p1==p2 );
119607  rc = queryTokenizer(db, "nosuchtokenizer", &p2);
119608  assert( rc==SQLITE_ERROR );
119609  assert( p2==0 );
119610  assert( 0==strcmp(sqlite3_errmsg(db), "unknown tokenizer: nosuchtokenizer") );
119611
119612  /* Test the storage function */
119613  rc = registerTokenizer(db, "nosuchtokenizer", p1);
119614  assert( rc==SQLITE_OK );
119615  rc = queryTokenizer(db, "nosuchtokenizer", &p2);
119616  assert( rc==SQLITE_OK );
119617  assert( p2==p1 );
119618
119619  sqlite3_result_text(context, "ok", -1, SQLITE_STATIC);
119620}
119621
119622#endif
119623
119624/*
119625** Set up SQL objects in database db used to access the contents of
119626** the hash table pointed to by argument pHash. The hash table must
119627** been initialised to use string keys, and to take a private copy
119628** of the key when a value is inserted. i.e. by a call similar to:
119629**
119630**    sqlite3Fts3HashInit(pHash, FTS3_HASH_STRING, 1);
119631**
119632** This function adds a scalar function (see header comment above
119633** scalarFunc() in this file for details) and, if ENABLE_TABLE is
119634** defined at compilation time, a temporary virtual table (see header
119635** comment above struct HashTableVtab) to the database schema. Both
119636** provide read/write access to the contents of *pHash.
119637**
119638** The third argument to this function, zName, is used as the name
119639** of both the scalar and, if created, the virtual table.
119640*/
119641SQLITE_PRIVATE int sqlite3Fts3InitHashTable(
119642  sqlite3 *db,
119643  Fts3Hash *pHash,
119644  const char *zName
119645){
119646  int rc = SQLITE_OK;
119647  void *p = (void *)pHash;
119648  const int any = SQLITE_ANY;
119649
119650#ifdef SQLITE_TEST
119651  char *zTest = 0;
119652  char *zTest2 = 0;
119653  void *pdb = (void *)db;
119654  zTest = sqlite3_mprintf("%s_test", zName);
119655  zTest2 = sqlite3_mprintf("%s_internal_test", zName);
119656  if( !zTest || !zTest2 ){
119657    rc = SQLITE_NOMEM;
119658  }
119659#endif
119660
119661  if( SQLITE_OK==rc ){
119662    rc = sqlite3_create_function(db, zName, 1, any, p, scalarFunc, 0, 0);
119663  }
119664  if( SQLITE_OK==rc ){
119665    rc = sqlite3_create_function(db, zName, 2, any, p, scalarFunc, 0, 0);
119666  }
119667#ifdef SQLITE_TEST
119668  if( SQLITE_OK==rc ){
119669    rc = sqlite3_create_function(db, zTest, 2, any, p, testFunc, 0, 0);
119670  }
119671  if( SQLITE_OK==rc ){
119672    rc = sqlite3_create_function(db, zTest, 3, any, p, testFunc, 0, 0);
119673  }
119674  if( SQLITE_OK==rc ){
119675    rc = sqlite3_create_function(db, zTest2, 0, any, pdb, intTestFunc, 0, 0);
119676  }
119677#endif
119678
119679#ifdef SQLITE_TEST
119680  sqlite3_free(zTest);
119681  sqlite3_free(zTest2);
119682#endif
119683
119684  return rc;
119685}
119686
119687#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
119688
119689/************** End of fts3_tokenizer.c **************************************/
119690/************** Begin file fts3_tokenizer1.c *********************************/
119691/*
119692** 2006 Oct 10
119693**
119694** The author disclaims copyright to this source code.  In place of
119695** a legal notice, here is a blessing:
119696**
119697**    May you do good and not evil.
119698**    May you find forgiveness for yourself and forgive others.
119699**    May you share freely, never taking more than you give.
119700**
119701******************************************************************************
119702**
119703** Implementation of the "simple" full-text-search tokenizer.
119704*/
119705
119706/*
119707** The code in this file is only compiled if:
119708**
119709**     * The FTS3 module is being built as an extension
119710**       (in which case SQLITE_CORE is not defined), or
119711**
119712**     * The FTS3 module is being built into the core of
119713**       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
119714*/
119715#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
119716
119717
119718
119719
119720typedef struct simple_tokenizer {
119721  sqlite3_tokenizer base;
119722  char delim[128];             /* flag ASCII delimiters */
119723} simple_tokenizer;
119724
119725typedef struct simple_tokenizer_cursor {
119726  sqlite3_tokenizer_cursor base;
119727  const char *pInput;          /* input we are tokenizing */
119728  int nBytes;                  /* size of the input */
119729  int iOffset;                 /* current position in pInput */
119730  int iToken;                  /* index of next token to be returned */
119731  char *pToken;                /* storage for current token */
119732  int nTokenAllocated;         /* space allocated to zToken buffer */
119733} simple_tokenizer_cursor;
119734
119735
119736static int simpleDelim(simple_tokenizer *t, unsigned char c){
119737  return c<0x80 && t->delim[c];
119738}
119739static int fts3_isalnum(int x){
119740  return (x>='0' && x<='9') || (x>='A' && x<='Z') || (x>='a' && x<='z');
119741}
119742
119743/*
119744** Create a new tokenizer instance.
119745*/
119746static int simpleCreate(
119747  int argc, const char * const *argv,
119748  sqlite3_tokenizer **ppTokenizer
119749){
119750  simple_tokenizer *t;
119751
119752  t = (simple_tokenizer *) sqlite3_malloc(sizeof(*t));
119753  if( t==NULL ) return SQLITE_NOMEM;
119754  memset(t, 0, sizeof(*t));
119755
119756  /* TODO(shess) Delimiters need to remain the same from run to run,
119757  ** else we need to reindex.  One solution would be a meta-table to
119758  ** track such information in the database, then we'd only want this
119759  ** information on the initial create.
119760  */
119761  if( argc>1 ){
119762    int i, n = (int)strlen(argv[1]);
119763    for(i=0; i<n; i++){
119764      unsigned char ch = argv[1][i];
119765      /* We explicitly don't support UTF-8 delimiters for now. */
119766      if( ch>=0x80 ){
119767        sqlite3_free(t);
119768        return SQLITE_ERROR;
119769      }
119770      t->delim[ch] = 1;
119771    }
119772  } else {
119773    /* Mark non-alphanumeric ASCII characters as delimiters */
119774    int i;
119775    for(i=1; i<0x80; i++){
119776      t->delim[i] = !fts3_isalnum(i) ? -1 : 0;
119777    }
119778  }
119779
119780  *ppTokenizer = &t->base;
119781  return SQLITE_OK;
119782}
119783
119784/*
119785** Destroy a tokenizer
119786*/
119787static int simpleDestroy(sqlite3_tokenizer *pTokenizer){
119788  sqlite3_free(pTokenizer);
119789  return SQLITE_OK;
119790}
119791
119792/*
119793** Prepare to begin tokenizing a particular string.  The input
119794** string to be tokenized is pInput[0..nBytes-1].  A cursor
119795** used to incrementally tokenize this string is returned in
119796** *ppCursor.
119797*/
119798static int simpleOpen(
119799  sqlite3_tokenizer *pTokenizer,         /* The tokenizer */
119800  const char *pInput, int nBytes,        /* String to be tokenized */
119801  sqlite3_tokenizer_cursor **ppCursor    /* OUT: Tokenization cursor */
119802){
119803  simple_tokenizer_cursor *c;
119804
119805  UNUSED_PARAMETER(pTokenizer);
119806
119807  c = (simple_tokenizer_cursor *) sqlite3_malloc(sizeof(*c));
119808  if( c==NULL ) return SQLITE_NOMEM;
119809
119810  c->pInput = pInput;
119811  if( pInput==0 ){
119812    c->nBytes = 0;
119813  }else if( nBytes<0 ){
119814    c->nBytes = (int)strlen(pInput);
119815  }else{
119816    c->nBytes = nBytes;
119817  }
119818  c->iOffset = 0;                 /* start tokenizing at the beginning */
119819  c->iToken = 0;
119820  c->pToken = NULL;               /* no space allocated, yet. */
119821  c->nTokenAllocated = 0;
119822
119823  *ppCursor = &c->base;
119824  return SQLITE_OK;
119825}
119826
119827/*
119828** Close a tokenization cursor previously opened by a call to
119829** simpleOpen() above.
119830*/
119831static int simpleClose(sqlite3_tokenizer_cursor *pCursor){
119832  simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor;
119833  sqlite3_free(c->pToken);
119834  sqlite3_free(c);
119835  return SQLITE_OK;
119836}
119837
119838/*
119839** Extract the next token from a tokenization cursor.  The cursor must
119840** have been opened by a prior call to simpleOpen().
119841*/
119842static int simpleNext(
119843  sqlite3_tokenizer_cursor *pCursor,  /* Cursor returned by simpleOpen */
119844  const char **ppToken,               /* OUT: *ppToken is the token text */
119845  int *pnBytes,                       /* OUT: Number of bytes in token */
119846  int *piStartOffset,                 /* OUT: Starting offset of token */
119847  int *piEndOffset,                   /* OUT: Ending offset of token */
119848  int *piPosition                     /* OUT: Position integer of token */
119849){
119850  simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor;
119851  simple_tokenizer *t = (simple_tokenizer *) pCursor->pTokenizer;
119852  unsigned char *p = (unsigned char *)c->pInput;
119853
119854  while( c->iOffset<c->nBytes ){
119855    int iStartOffset;
119856
119857    /* Scan past delimiter characters */
119858    while( c->iOffset<c->nBytes && simpleDelim(t, p[c->iOffset]) ){
119859      c->iOffset++;
119860    }
119861
119862    /* Count non-delimiter characters. */
119863    iStartOffset = c->iOffset;
119864    while( c->iOffset<c->nBytes && !simpleDelim(t, p[c->iOffset]) ){
119865      c->iOffset++;
119866    }
119867
119868    if( c->iOffset>iStartOffset ){
119869      int i, n = c->iOffset-iStartOffset;
119870      if( n>c->nTokenAllocated ){
119871        char *pNew;
119872        c->nTokenAllocated = n+20;
119873        pNew = sqlite3_realloc(c->pToken, c->nTokenAllocated);
119874        if( !pNew ) return SQLITE_NOMEM;
119875        c->pToken = pNew;
119876      }
119877      for(i=0; i<n; i++){
119878        /* TODO(shess) This needs expansion to handle UTF-8
119879        ** case-insensitivity.
119880        */
119881        unsigned char ch = p[iStartOffset+i];
119882        c->pToken[i] = (char)((ch>='A' && ch<='Z') ? ch-'A'+'a' : ch);
119883      }
119884      *ppToken = c->pToken;
119885      *pnBytes = n;
119886      *piStartOffset = iStartOffset;
119887      *piEndOffset = c->iOffset;
119888      *piPosition = c->iToken++;
119889
119890      return SQLITE_OK;
119891    }
119892  }
119893  return SQLITE_DONE;
119894}
119895
119896/*
119897** The set of routines that implement the simple tokenizer
119898*/
119899static const sqlite3_tokenizer_module simpleTokenizerModule = {
119900  0,
119901  simpleCreate,
119902  simpleDestroy,
119903  simpleOpen,
119904  simpleClose,
119905  simpleNext,
119906};
119907
119908/*
119909** Allocate a new simple tokenizer.  Return a pointer to the new
119910** tokenizer in *ppModule
119911*/
119912SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(
119913  sqlite3_tokenizer_module const**ppModule
119914){
119915  *ppModule = &simpleTokenizerModule;
119916}
119917
119918#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
119919
119920/************** End of fts3_tokenizer1.c *************************************/
119921/************** Begin file fts3_write.c **************************************/
119922/*
119923** 2009 Oct 23
119924**
119925** The author disclaims copyright to this source code.  In place of
119926** a legal notice, here is a blessing:
119927**
119928**    May you do good and not evil.
119929**    May you find forgiveness for yourself and forgive others.
119930**    May you share freely, never taking more than you give.
119931**
119932******************************************************************************
119933**
119934** This file is part of the SQLite FTS3 extension module. Specifically,
119935** this file contains code to insert, update and delete rows from FTS3
119936** tables. It also contains code to merge FTS3 b-tree segments. Some
119937** of the sub-routines used to merge segments are also used by the query
119938** code in fts3.c.
119939*/
119940
119941#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
119942
119943
119944/*
119945** When full-text index nodes are loaded from disk, the buffer that they
119946** are loaded into has the following number of bytes of padding at the end
119947** of it. i.e. if a full-text index node is 900 bytes in size, then a buffer
119948** of 920 bytes is allocated for it.
119949**
119950** This means that if we have a pointer into a buffer containing node data,
119951** it is always safe to read up to two varints from it without risking an
119952** overread, even if the node data is corrupted.
119953*/
119954#define FTS3_NODE_PADDING (FTS3_VARINT_MAX*2)
119955
119956typedef struct PendingList PendingList;
119957typedef struct SegmentNode SegmentNode;
119958typedef struct SegmentWriter SegmentWriter;
119959
119960/*
119961** Data structure used while accumulating terms in the pending-terms hash
119962** table. The hash table entry maps from term (a string) to a malloc'd
119963** instance of this structure.
119964*/
119965struct PendingList {
119966  int nData;
119967  char *aData;
119968  int nSpace;
119969  sqlite3_int64 iLastDocid;
119970  sqlite3_int64 iLastCol;
119971  sqlite3_int64 iLastPos;
119972};
119973
119974
119975/*
119976** Each cursor has a (possibly empty) linked list of the following objects.
119977*/
119978struct Fts3DeferredToken {
119979  Fts3PhraseToken *pToken;        /* Pointer to corresponding expr token */
119980  int iCol;                       /* Column token must occur in */
119981  Fts3DeferredToken *pNext;       /* Next in list of deferred tokens */
119982  PendingList *pList;             /* Doclist is assembled here */
119983};
119984
119985/*
119986** An instance of this structure is used to iterate through the terms on
119987** a contiguous set of segment b-tree leaf nodes. Although the details of
119988** this structure are only manipulated by code in this file, opaque handles
119989** of type Fts3SegReader* are also used by code in fts3.c to iterate through
119990** terms when querying the full-text index. See functions:
119991**
119992**   sqlite3Fts3SegReaderNew()
119993**   sqlite3Fts3SegReaderFree()
119994**   sqlite3Fts3SegReaderCost()
119995**   sqlite3Fts3SegReaderIterate()
119996**
119997** Methods used to manipulate Fts3SegReader structures:
119998**
119999**   fts3SegReaderNext()
120000**   fts3SegReaderFirstDocid()
120001**   fts3SegReaderNextDocid()
120002*/
120003struct Fts3SegReader {
120004  int iIdx;                       /* Index within level, or 0x7FFFFFFF for PT */
120005
120006  sqlite3_int64 iStartBlock;      /* Rowid of first leaf block to traverse */
120007  sqlite3_int64 iLeafEndBlock;    /* Rowid of final leaf block to traverse */
120008  sqlite3_int64 iEndBlock;        /* Rowid of final block in segment (or 0) */
120009  sqlite3_int64 iCurrentBlock;    /* Current leaf block (or 0) */
120010
120011  char *aNode;                    /* Pointer to node data (or NULL) */
120012  int nNode;                      /* Size of buffer at aNode (or 0) */
120013  Fts3HashElem **ppNextElem;
120014
120015  /* Variables set by fts3SegReaderNext(). These may be read directly
120016  ** by the caller. They are valid from the time SegmentReaderNew() returns
120017  ** until SegmentReaderNext() returns something other than SQLITE_OK
120018  ** (i.e. SQLITE_DONE).
120019  */
120020  int nTerm;                      /* Number of bytes in current term */
120021  char *zTerm;                    /* Pointer to current term */
120022  int nTermAlloc;                 /* Allocated size of zTerm buffer */
120023  char *aDoclist;                 /* Pointer to doclist of current entry */
120024  int nDoclist;                   /* Size of doclist in current entry */
120025
120026  /* The following variables are used to iterate through the current doclist */
120027  char *pOffsetList;
120028  sqlite3_int64 iDocid;
120029};
120030
120031#define fts3SegReaderIsPending(p) ((p)->ppNextElem!=0)
120032#define fts3SegReaderIsRootOnly(p) ((p)->aNode==(char *)&(p)[1])
120033
120034/*
120035** An instance of this structure is used to create a segment b-tree in the
120036** database. The internal details of this type are only accessed by the
120037** following functions:
120038**
120039**   fts3SegWriterAdd()
120040**   fts3SegWriterFlush()
120041**   fts3SegWriterFree()
120042*/
120043struct SegmentWriter {
120044  SegmentNode *pTree;             /* Pointer to interior tree structure */
120045  sqlite3_int64 iFirst;           /* First slot in %_segments written */
120046  sqlite3_int64 iFree;            /* Next free slot in %_segments */
120047  char *zTerm;                    /* Pointer to previous term buffer */
120048  int nTerm;                      /* Number of bytes in zTerm */
120049  int nMalloc;                    /* Size of malloc'd buffer at zMalloc */
120050  char *zMalloc;                  /* Malloc'd space (possibly) used for zTerm */
120051  int nSize;                      /* Size of allocation at aData */
120052  int nData;                      /* Bytes of data in aData */
120053  char *aData;                    /* Pointer to block from malloc() */
120054};
120055
120056/*
120057** Type SegmentNode is used by the following three functions to create
120058** the interior part of the segment b+-tree structures (everything except
120059** the leaf nodes). These functions and type are only ever used by code
120060** within the fts3SegWriterXXX() family of functions described above.
120061**
120062**   fts3NodeAddTerm()
120063**   fts3NodeWrite()
120064**   fts3NodeFree()
120065*/
120066struct SegmentNode {
120067  SegmentNode *pParent;           /* Parent node (or NULL for root node) */
120068  SegmentNode *pRight;            /* Pointer to right-sibling */
120069  SegmentNode *pLeftmost;         /* Pointer to left-most node of this depth */
120070  int nEntry;                     /* Number of terms written to node so far */
120071  char *zTerm;                    /* Pointer to previous term buffer */
120072  int nTerm;                      /* Number of bytes in zTerm */
120073  int nMalloc;                    /* Size of malloc'd buffer at zMalloc */
120074  char *zMalloc;                  /* Malloc'd space (possibly) used for zTerm */
120075  int nData;                      /* Bytes of valid data so far */
120076  char *aData;                    /* Node data */
120077};
120078
120079/*
120080** Valid values for the second argument to fts3SqlStmt().
120081*/
120082#define SQL_DELETE_CONTENT             0
120083#define SQL_IS_EMPTY                   1
120084#define SQL_DELETE_ALL_CONTENT         2
120085#define SQL_DELETE_ALL_SEGMENTS        3
120086#define SQL_DELETE_ALL_SEGDIR          4
120087#define SQL_DELETE_ALL_DOCSIZE         5
120088#define SQL_DELETE_ALL_STAT            6
120089#define SQL_SELECT_CONTENT_BY_ROWID    7
120090#define SQL_NEXT_SEGMENT_INDEX         8
120091#define SQL_INSERT_SEGMENTS            9
120092#define SQL_NEXT_SEGMENTS_ID          10
120093#define SQL_INSERT_SEGDIR             11
120094#define SQL_SELECT_LEVEL              12
120095#define SQL_SELECT_ALL_LEVEL          13
120096#define SQL_SELECT_LEVEL_COUNT        14
120097#define SQL_SELECT_SEGDIR_COUNT_MAX   15
120098#define SQL_DELETE_SEGDIR_BY_LEVEL    16
120099#define SQL_DELETE_SEGMENTS_RANGE     17
120100#define SQL_CONTENT_INSERT            18
120101#define SQL_DELETE_DOCSIZE            19
120102#define SQL_REPLACE_DOCSIZE           20
120103#define SQL_SELECT_DOCSIZE            21
120104#define SQL_SELECT_DOCTOTAL           22
120105#define SQL_REPLACE_DOCTOTAL          23
120106
120107/*
120108** This function is used to obtain an SQLite prepared statement handle
120109** for the statement identified by the second argument. If successful,
120110** *pp is set to the requested statement handle and SQLITE_OK returned.
120111** Otherwise, an SQLite error code is returned and *pp is set to 0.
120112**
120113** If argument apVal is not NULL, then it must point to an array with
120114** at least as many entries as the requested statement has bound
120115** parameters. The values are bound to the statements parameters before
120116** returning.
120117*/
120118static int fts3SqlStmt(
120119  Fts3Table *p,                   /* Virtual table handle */
120120  int eStmt,                      /* One of the SQL_XXX constants above */
120121  sqlite3_stmt **pp,              /* OUT: Statement handle */
120122  sqlite3_value **apVal           /* Values to bind to statement */
120123){
120124  const char *azSql[] = {
120125/* 0  */  "DELETE FROM %Q.'%q_content' WHERE rowid = ?",
120126/* 1  */  "SELECT NOT EXISTS(SELECT docid FROM %Q.'%q_content' WHERE rowid!=?)",
120127/* 2  */  "DELETE FROM %Q.'%q_content'",
120128/* 3  */  "DELETE FROM %Q.'%q_segments'",
120129/* 4  */  "DELETE FROM %Q.'%q_segdir'",
120130/* 5  */  "DELETE FROM %Q.'%q_docsize'",
120131/* 6  */  "DELETE FROM %Q.'%q_stat'",
120132/* 7  */  "SELECT %s FROM %Q.'%q_content' AS x WHERE rowid=?",
120133/* 8  */  "SELECT (SELECT max(idx) FROM %Q.'%q_segdir' WHERE level = ?) + 1",
120134/* 9  */  "INSERT INTO %Q.'%q_segments'(blockid, block) VALUES(?, ?)",
120135/* 10 */  "SELECT coalesce((SELECT max(blockid) FROM %Q.'%q_segments') + 1, 1)",
120136/* 11 */  "INSERT INTO %Q.'%q_segdir' VALUES(?,?,?,?,?,?)",
120137
120138          /* Return segments in order from oldest to newest.*/
120139/* 12 */  "SELECT idx, start_block, leaves_end_block, end_block, root "
120140            "FROM %Q.'%q_segdir' WHERE level = ? ORDER BY idx ASC",
120141/* 13 */  "SELECT idx, start_block, leaves_end_block, end_block, root "
120142            "FROM %Q.'%q_segdir' ORDER BY level DESC, idx ASC",
120143
120144/* 14 */  "SELECT count(*) FROM %Q.'%q_segdir' WHERE level = ?",
120145/* 15 */  "SELECT count(*), max(level) FROM %Q.'%q_segdir'",
120146
120147/* 16 */  "DELETE FROM %Q.'%q_segdir' WHERE level = ?",
120148/* 17 */  "DELETE FROM %Q.'%q_segments' WHERE blockid BETWEEN ? AND ?",
120149/* 18 */  "INSERT INTO %Q.'%q_content' VALUES(%s)",
120150/* 19 */  "DELETE FROM %Q.'%q_docsize' WHERE docid = ?",
120151/* 20 */  "REPLACE INTO %Q.'%q_docsize' VALUES(?,?)",
120152/* 21 */  "SELECT size FROM %Q.'%q_docsize' WHERE docid=?",
120153/* 22 */  "SELECT value FROM %Q.'%q_stat' WHERE id=0",
120154/* 23 */  "REPLACE INTO %Q.'%q_stat' VALUES(0,?)",
120155  };
120156  int rc = SQLITE_OK;
120157  sqlite3_stmt *pStmt;
120158
120159  assert( SizeofArray(azSql)==SizeofArray(p->aStmt) );
120160  assert( eStmt<SizeofArray(azSql) && eStmt>=0 );
120161
120162  pStmt = p->aStmt[eStmt];
120163  if( !pStmt ){
120164    char *zSql;
120165    if( eStmt==SQL_CONTENT_INSERT ){
120166      zSql = sqlite3_mprintf(azSql[eStmt], p->zDb, p->zName, p->zWriteExprlist);
120167    }else if( eStmt==SQL_SELECT_CONTENT_BY_ROWID ){
120168      zSql = sqlite3_mprintf(azSql[eStmt], p->zReadExprlist, p->zDb, p->zName);
120169    }else{
120170      zSql = sqlite3_mprintf(azSql[eStmt], p->zDb, p->zName);
120171    }
120172    if( !zSql ){
120173      rc = SQLITE_NOMEM;
120174    }else{
120175      rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, NULL);
120176      sqlite3_free(zSql);
120177      assert( rc==SQLITE_OK || pStmt==0 );
120178      p->aStmt[eStmt] = pStmt;
120179    }
120180  }
120181  if( apVal ){
120182    int i;
120183    int nParam = sqlite3_bind_parameter_count(pStmt);
120184    for(i=0; rc==SQLITE_OK && i<nParam; i++){
120185      rc = sqlite3_bind_value(pStmt, i+1, apVal[i]);
120186    }
120187  }
120188  *pp = pStmt;
120189  return rc;
120190}
120191
120192static int fts3SelectDocsize(
120193  Fts3Table *pTab,                /* FTS3 table handle */
120194  int eStmt,                      /* Either SQL_SELECT_DOCSIZE or DOCTOTAL */
120195  sqlite3_int64 iDocid,           /* Docid to bind for SQL_SELECT_DOCSIZE */
120196  sqlite3_stmt **ppStmt           /* OUT: Statement handle */
120197){
120198  sqlite3_stmt *pStmt = 0;        /* Statement requested from fts3SqlStmt() */
120199  int rc;                         /* Return code */
120200
120201  assert( eStmt==SQL_SELECT_DOCSIZE || eStmt==SQL_SELECT_DOCTOTAL );
120202
120203  rc = fts3SqlStmt(pTab, eStmt, &pStmt, 0);
120204  if( rc==SQLITE_OK ){
120205    if( eStmt==SQL_SELECT_DOCSIZE ){
120206      sqlite3_bind_int64(pStmt, 1, iDocid);
120207    }
120208    rc = sqlite3_step(pStmt);
120209    if( rc!=SQLITE_ROW || sqlite3_column_type(pStmt, 0)!=SQLITE_BLOB ){
120210      rc = sqlite3_reset(pStmt);
120211      if( rc==SQLITE_OK ) rc = SQLITE_CORRUPT;
120212      pStmt = 0;
120213    }else{
120214      rc = SQLITE_OK;
120215    }
120216  }
120217
120218  *ppStmt = pStmt;
120219  return rc;
120220}
120221
120222SQLITE_PRIVATE int sqlite3Fts3SelectDoctotal(
120223  Fts3Table *pTab,                /* Fts3 table handle */
120224  sqlite3_stmt **ppStmt           /* OUT: Statement handle */
120225){
120226  return fts3SelectDocsize(pTab, SQL_SELECT_DOCTOTAL, 0, ppStmt);
120227}
120228
120229SQLITE_PRIVATE int sqlite3Fts3SelectDocsize(
120230  Fts3Table *pTab,                /* Fts3 table handle */
120231  sqlite3_int64 iDocid,           /* Docid to read size data for */
120232  sqlite3_stmt **ppStmt           /* OUT: Statement handle */
120233){
120234  return fts3SelectDocsize(pTab, SQL_SELECT_DOCSIZE, iDocid, ppStmt);
120235}
120236
120237/*
120238** Similar to fts3SqlStmt(). Except, after binding the parameters in
120239** array apVal[] to the SQL statement identified by eStmt, the statement
120240** is executed.
120241**
120242** Returns SQLITE_OK if the statement is successfully executed, or an
120243** SQLite error code otherwise.
120244*/
120245static void fts3SqlExec(
120246  int *pRC,                /* Result code */
120247  Fts3Table *p,            /* The FTS3 table */
120248  int eStmt,               /* Index of statement to evaluate */
120249  sqlite3_value **apVal    /* Parameters to bind */
120250){
120251  sqlite3_stmt *pStmt;
120252  int rc;
120253  if( *pRC ) return;
120254  rc = fts3SqlStmt(p, eStmt, &pStmt, apVal);
120255  if( rc==SQLITE_OK ){
120256    sqlite3_step(pStmt);
120257    rc = sqlite3_reset(pStmt);
120258  }
120259  *pRC = rc;
120260}
120261
120262
120263/*
120264** This function ensures that the caller has obtained a shared-cache
120265** table-lock on the %_content table. This is required before reading
120266** data from the fts3 table. If this lock is not acquired first, then
120267** the caller may end up holding read-locks on the %_segments and %_segdir
120268** tables, but no read-lock on the %_content table. If this happens
120269** a second connection will be able to write to the fts3 table, but
120270** attempting to commit those writes might return SQLITE_LOCKED or
120271** SQLITE_LOCKED_SHAREDCACHE (because the commit attempts to obtain
120272** write-locks on the %_segments and %_segdir ** tables).
120273**
120274** We try to avoid this because if FTS3 returns any error when committing
120275** a transaction, the whole transaction will be rolled back. And this is
120276** not what users expect when they get SQLITE_LOCKED_SHAREDCACHE. It can
120277** still happen if the user reads data directly from the %_segments or
120278** %_segdir tables instead of going through FTS3 though.
120279*/
120280SQLITE_PRIVATE int sqlite3Fts3ReadLock(Fts3Table *p){
120281  int rc;                         /* Return code */
120282  sqlite3_stmt *pStmt;            /* Statement used to obtain lock */
120283
120284  rc = fts3SqlStmt(p, SQL_SELECT_CONTENT_BY_ROWID, &pStmt, 0);
120285  if( rc==SQLITE_OK ){
120286    sqlite3_bind_null(pStmt, 1);
120287    sqlite3_step(pStmt);
120288    rc = sqlite3_reset(pStmt);
120289  }
120290  return rc;
120291}
120292
120293/*
120294** Set *ppStmt to a statement handle that may be used to iterate through
120295** all rows in the %_segdir table, from oldest to newest. If successful,
120296** return SQLITE_OK. If an error occurs while preparing the statement,
120297** return an SQLite error code.
120298**
120299** There is only ever one instance of this SQL statement compiled for
120300** each FTS3 table.
120301**
120302** The statement returns the following columns from the %_segdir table:
120303**
120304**   0: idx
120305**   1: start_block
120306**   2: leaves_end_block
120307**   3: end_block
120308**   4: root
120309*/
120310SQLITE_PRIVATE int sqlite3Fts3AllSegdirs(Fts3Table *p, int iLevel, sqlite3_stmt **ppStmt){
120311  int rc;
120312  sqlite3_stmt *pStmt = 0;
120313  if( iLevel<0 ){
120314    rc = fts3SqlStmt(p, SQL_SELECT_ALL_LEVEL, &pStmt, 0);
120315  }else{
120316    rc = fts3SqlStmt(p, SQL_SELECT_LEVEL, &pStmt, 0);
120317    if( rc==SQLITE_OK ) sqlite3_bind_int(pStmt, 1, iLevel);
120318  }
120319  *ppStmt = pStmt;
120320  return rc;
120321}
120322
120323
120324/*
120325** Append a single varint to a PendingList buffer. SQLITE_OK is returned
120326** if successful, or an SQLite error code otherwise.
120327**
120328** This function also serves to allocate the PendingList structure itself.
120329** For example, to create a new PendingList structure containing two
120330** varints:
120331**
120332**   PendingList *p = 0;
120333**   fts3PendingListAppendVarint(&p, 1);
120334**   fts3PendingListAppendVarint(&p, 2);
120335*/
120336static int fts3PendingListAppendVarint(
120337  PendingList **pp,               /* IN/OUT: Pointer to PendingList struct */
120338  sqlite3_int64 i                 /* Value to append to data */
120339){
120340  PendingList *p = *pp;
120341
120342  /* Allocate or grow the PendingList as required. */
120343  if( !p ){
120344    p = sqlite3_malloc(sizeof(*p) + 100);
120345    if( !p ){
120346      return SQLITE_NOMEM;
120347    }
120348    p->nSpace = 100;
120349    p->aData = (char *)&p[1];
120350    p->nData = 0;
120351  }
120352  else if( p->nData+FTS3_VARINT_MAX+1>p->nSpace ){
120353    int nNew = p->nSpace * 2;
120354    p = sqlite3_realloc(p, sizeof(*p) + nNew);
120355    if( !p ){
120356      sqlite3_free(*pp);
120357      *pp = 0;
120358      return SQLITE_NOMEM;
120359    }
120360    p->nSpace = nNew;
120361    p->aData = (char *)&p[1];
120362  }
120363
120364  /* Append the new serialized varint to the end of the list. */
120365  p->nData += sqlite3Fts3PutVarint(&p->aData[p->nData], i);
120366  p->aData[p->nData] = '\0';
120367  *pp = p;
120368  return SQLITE_OK;
120369}
120370
120371/*
120372** Add a docid/column/position entry to a PendingList structure. Non-zero
120373** is returned if the structure is sqlite3_realloced as part of adding
120374** the entry. Otherwise, zero.
120375**
120376** If an OOM error occurs, *pRc is set to SQLITE_NOMEM before returning.
120377** Zero is always returned in this case. Otherwise, if no OOM error occurs,
120378** it is set to SQLITE_OK.
120379*/
120380static int fts3PendingListAppend(
120381  PendingList **pp,               /* IN/OUT: PendingList structure */
120382  sqlite3_int64 iDocid,           /* Docid for entry to add */
120383  sqlite3_int64 iCol,             /* Column for entry to add */
120384  sqlite3_int64 iPos,             /* Position of term for entry to add */
120385  int *pRc                        /* OUT: Return code */
120386){
120387  PendingList *p = *pp;
120388  int rc = SQLITE_OK;
120389
120390  assert( !p || p->iLastDocid<=iDocid );
120391
120392  if( !p || p->iLastDocid!=iDocid ){
120393    sqlite3_int64 iDelta = iDocid - (p ? p->iLastDocid : 0);
120394    if( p ){
120395      assert( p->nData<p->nSpace );
120396      assert( p->aData[p->nData]==0 );
120397      p->nData++;
120398    }
120399    if( SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, iDelta)) ){
120400      goto pendinglistappend_out;
120401    }
120402    p->iLastCol = -1;
120403    p->iLastPos = 0;
120404    p->iLastDocid = iDocid;
120405  }
120406  if( iCol>0 && p->iLastCol!=iCol ){
120407    if( SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, 1))
120408     || SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, iCol))
120409    ){
120410      goto pendinglistappend_out;
120411    }
120412    p->iLastCol = iCol;
120413    p->iLastPos = 0;
120414  }
120415  if( iCol>=0 ){
120416    assert( iPos>p->iLastPos || (iPos==0 && p->iLastPos==0) );
120417    rc = fts3PendingListAppendVarint(&p, 2+iPos-p->iLastPos);
120418    if( rc==SQLITE_OK ){
120419      p->iLastPos = iPos;
120420    }
120421  }
120422
120423 pendinglistappend_out:
120424  *pRc = rc;
120425  if( p!=*pp ){
120426    *pp = p;
120427    return 1;
120428  }
120429  return 0;
120430}
120431
120432/*
120433** Tokenize the nul-terminated string zText and add all tokens to the
120434** pending-terms hash-table. The docid used is that currently stored in
120435** p->iPrevDocid, and the column is specified by argument iCol.
120436**
120437** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code.
120438*/
120439static int fts3PendingTermsAdd(
120440  Fts3Table *p,                   /* Table into which text will be inserted */
120441  const char *zText,              /* Text of document to be inserted */
120442  int iCol,                       /* Column into which text is being inserted */
120443  u32 *pnWord                     /* OUT: Number of tokens inserted */
120444){
120445  int rc;
120446  int iStart;
120447  int iEnd;
120448  int iPos;
120449  int nWord = 0;
120450
120451  char const *zToken;
120452  int nToken;
120453
120454  sqlite3_tokenizer *pTokenizer = p->pTokenizer;
120455  sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
120456  sqlite3_tokenizer_cursor *pCsr;
120457  int (*xNext)(sqlite3_tokenizer_cursor *pCursor,
120458      const char**,int*,int*,int*,int*);
120459
120460  assert( pTokenizer && pModule );
120461
120462  rc = pModule->xOpen(pTokenizer, zText, -1, &pCsr);
120463  if( rc!=SQLITE_OK ){
120464    return rc;
120465  }
120466  pCsr->pTokenizer = pTokenizer;
120467
120468  xNext = pModule->xNext;
120469  while( SQLITE_OK==rc
120470      && SQLITE_OK==(rc = xNext(pCsr, &zToken, &nToken, &iStart, &iEnd, &iPos))
120471  ){
120472    PendingList *pList;
120473
120474    if( iPos>=nWord ) nWord = iPos+1;
120475
120476    /* Positions cannot be negative; we use -1 as a terminator internally.
120477    ** Tokens must have a non-zero length.
120478    */
120479    if( iPos<0 || !zToken || nToken<=0 ){
120480      rc = SQLITE_ERROR;
120481      break;
120482    }
120483
120484    pList = (PendingList *)fts3HashFind(&p->pendingTerms, zToken, nToken);
120485    if( pList ){
120486      p->nPendingData -= (pList->nData + nToken + sizeof(Fts3HashElem));
120487    }
120488    if( fts3PendingListAppend(&pList, p->iPrevDocid, iCol, iPos, &rc) ){
120489      if( pList==fts3HashInsert(&p->pendingTerms, zToken, nToken, pList) ){
120490        /* Malloc failed while inserting the new entry. This can only
120491        ** happen if there was no previous entry for this token.
120492        */
120493        assert( 0==fts3HashFind(&p->pendingTerms, zToken, nToken) );
120494        sqlite3_free(pList);
120495        rc = SQLITE_NOMEM;
120496      }
120497    }
120498    if( rc==SQLITE_OK ){
120499      p->nPendingData += (pList->nData + nToken + sizeof(Fts3HashElem));
120500    }
120501  }
120502
120503  pModule->xClose(pCsr);
120504  *pnWord = nWord;
120505  return (rc==SQLITE_DONE ? SQLITE_OK : rc);
120506}
120507
120508/*
120509** Calling this function indicates that subsequent calls to
120510** fts3PendingTermsAdd() are to add term/position-list pairs for the
120511** contents of the document with docid iDocid.
120512*/
120513static int fts3PendingTermsDocid(Fts3Table *p, sqlite_int64 iDocid){
120514  /* TODO(shess) Explore whether partially flushing the buffer on
120515  ** forced-flush would provide better performance.  I suspect that if
120516  ** we ordered the doclists by size and flushed the largest until the
120517  ** buffer was half empty, that would let the less frequent terms
120518  ** generate longer doclists.
120519  */
120520  if( iDocid<=p->iPrevDocid || p->nPendingData>p->nMaxPendingData ){
120521    int rc = sqlite3Fts3PendingTermsFlush(p);
120522    if( rc!=SQLITE_OK ) return rc;
120523  }
120524  p->iPrevDocid = iDocid;
120525  return SQLITE_OK;
120526}
120527
120528/*
120529** Discard the contents of the pending-terms hash table.
120530*/
120531SQLITE_PRIVATE void sqlite3Fts3PendingTermsClear(Fts3Table *p){
120532  Fts3HashElem *pElem;
120533  for(pElem=fts3HashFirst(&p->pendingTerms); pElem; pElem=fts3HashNext(pElem)){
120534    sqlite3_free(fts3HashData(pElem));
120535  }
120536  fts3HashClear(&p->pendingTerms);
120537  p->nPendingData = 0;
120538}
120539
120540/*
120541** This function is called by the xUpdate() method as part of an INSERT
120542** operation. It adds entries for each term in the new record to the
120543** pendingTerms hash table.
120544**
120545** Argument apVal is the same as the similarly named argument passed to
120546** fts3InsertData(). Parameter iDocid is the docid of the new row.
120547*/
120548static int fts3InsertTerms(Fts3Table *p, sqlite3_value **apVal, u32 *aSz){
120549  int i;                          /* Iterator variable */
120550  for(i=2; i<p->nColumn+2; i++){
120551    const char *zText = (const char *)sqlite3_value_text(apVal[i]);
120552    if( zText ){
120553      int rc = fts3PendingTermsAdd(p, zText, i-2, &aSz[i-2]);
120554      if( rc!=SQLITE_OK ){
120555        return rc;
120556      }
120557    }
120558    aSz[p->nColumn] += sqlite3_value_bytes(apVal[i]);
120559  }
120560  return SQLITE_OK;
120561}
120562
120563/*
120564** This function is called by the xUpdate() method for an INSERT operation.
120565** The apVal parameter is passed a copy of the apVal argument passed by
120566** SQLite to the xUpdate() method. i.e:
120567**
120568**   apVal[0]                Not used for INSERT.
120569**   apVal[1]                rowid
120570**   apVal[2]                Left-most user-defined column
120571**   ...
120572**   apVal[p->nColumn+1]     Right-most user-defined column
120573**   apVal[p->nColumn+2]     Hidden column with same name as table
120574**   apVal[p->nColumn+3]     Hidden "docid" column (alias for rowid)
120575*/
120576static int fts3InsertData(
120577  Fts3Table *p,                   /* Full-text table */
120578  sqlite3_value **apVal,          /* Array of values to insert */
120579  sqlite3_int64 *piDocid          /* OUT: Docid for row just inserted */
120580){
120581  int rc;                         /* Return code */
120582  sqlite3_stmt *pContentInsert;   /* INSERT INTO %_content VALUES(...) */
120583
120584  /* Locate the statement handle used to insert data into the %_content
120585  ** table. The SQL for this statement is:
120586  **
120587  **   INSERT INTO %_content VALUES(?, ?, ?, ...)
120588  **
120589  ** The statement features N '?' variables, where N is the number of user
120590  ** defined columns in the FTS3 table, plus one for the docid field.
120591  */
120592  rc = fts3SqlStmt(p, SQL_CONTENT_INSERT, &pContentInsert, &apVal[1]);
120593  if( rc!=SQLITE_OK ){
120594    return rc;
120595  }
120596
120597  /* There is a quirk here. The users INSERT statement may have specified
120598  ** a value for the "rowid" field, for the "docid" field, or for both.
120599  ** Which is a problem, since "rowid" and "docid" are aliases for the
120600  ** same value. For example:
120601  **
120602  **   INSERT INTO fts3tbl(rowid, docid) VALUES(1, 2);
120603  **
120604  ** In FTS3, this is an error. It is an error to specify non-NULL values
120605  ** for both docid and some other rowid alias.
120606  */
120607  if( SQLITE_NULL!=sqlite3_value_type(apVal[3+p->nColumn]) ){
120608    if( SQLITE_NULL==sqlite3_value_type(apVal[0])
120609     && SQLITE_NULL!=sqlite3_value_type(apVal[1])
120610    ){
120611      /* A rowid/docid conflict. */
120612      return SQLITE_ERROR;
120613    }
120614    rc = sqlite3_bind_value(pContentInsert, 1, apVal[3+p->nColumn]);
120615    if( rc!=SQLITE_OK ) return rc;
120616  }
120617
120618  /* Execute the statement to insert the record. Set *piDocid to the
120619  ** new docid value.
120620  */
120621  sqlite3_step(pContentInsert);
120622  rc = sqlite3_reset(pContentInsert);
120623
120624  *piDocid = sqlite3_last_insert_rowid(p->db);
120625  return rc;
120626}
120627
120628
120629
120630/*
120631** Remove all data from the FTS3 table. Clear the hash table containing
120632** pending terms.
120633*/
120634static int fts3DeleteAll(Fts3Table *p){
120635  int rc = SQLITE_OK;             /* Return code */
120636
120637  /* Discard the contents of the pending-terms hash table. */
120638  sqlite3Fts3PendingTermsClear(p);
120639
120640  /* Delete everything from the %_content, %_segments and %_segdir tables. */
120641  fts3SqlExec(&rc, p, SQL_DELETE_ALL_CONTENT, 0);
120642  fts3SqlExec(&rc, p, SQL_DELETE_ALL_SEGMENTS, 0);
120643  fts3SqlExec(&rc, p, SQL_DELETE_ALL_SEGDIR, 0);
120644  if( p->bHasDocsize ){
120645    fts3SqlExec(&rc, p, SQL_DELETE_ALL_DOCSIZE, 0);
120646  }
120647  if( p->bHasStat ){
120648    fts3SqlExec(&rc, p, SQL_DELETE_ALL_STAT, 0);
120649  }
120650  return rc;
120651}
120652
120653/*
120654** The first element in the apVal[] array is assumed to contain the docid
120655** (an integer) of a row about to be deleted. Remove all terms from the
120656** full-text index.
120657*/
120658static void fts3DeleteTerms(
120659  int *pRC,               /* Result code */
120660  Fts3Table *p,           /* The FTS table to delete from */
120661  sqlite3_value **apVal,  /* apVal[] contains the docid to be deleted */
120662  u32 *aSz                /* Sizes of deleted document written here */
120663){
120664  int rc;
120665  sqlite3_stmt *pSelect;
120666
120667  if( *pRC ) return;
120668  rc = fts3SqlStmt(p, SQL_SELECT_CONTENT_BY_ROWID, &pSelect, apVal);
120669  if( rc==SQLITE_OK ){
120670    if( SQLITE_ROW==sqlite3_step(pSelect) ){
120671      int i;
120672      for(i=1; i<=p->nColumn; i++){
120673        const char *zText = (const char *)sqlite3_column_text(pSelect, i);
120674        rc = fts3PendingTermsAdd(p, zText, -1, &aSz[i-1]);
120675        if( rc!=SQLITE_OK ){
120676          sqlite3_reset(pSelect);
120677          *pRC = rc;
120678          return;
120679        }
120680        aSz[p->nColumn] += sqlite3_column_bytes(pSelect, i);
120681      }
120682    }
120683    rc = sqlite3_reset(pSelect);
120684  }else{
120685    sqlite3_reset(pSelect);
120686  }
120687  *pRC = rc;
120688}
120689
120690/*
120691** Forward declaration to account for the circular dependency between
120692** functions fts3SegmentMerge() and fts3AllocateSegdirIdx().
120693*/
120694static int fts3SegmentMerge(Fts3Table *, int);
120695
120696/*
120697** This function allocates a new level iLevel index in the segdir table.
120698** Usually, indexes are allocated within a level sequentially starting
120699** with 0, so the allocated index is one greater than the value returned
120700** by:
120701**
120702**   SELECT max(idx) FROM %_segdir WHERE level = :iLevel
120703**
120704** However, if there are already FTS3_MERGE_COUNT indexes at the requested
120705** level, they are merged into a single level (iLevel+1) segment and the
120706** allocated index is 0.
120707**
120708** If successful, *piIdx is set to the allocated index slot and SQLITE_OK
120709** returned. Otherwise, an SQLite error code is returned.
120710*/
120711static int fts3AllocateSegdirIdx(Fts3Table *p, int iLevel, int *piIdx){
120712  int rc;                         /* Return Code */
120713  sqlite3_stmt *pNextIdx;         /* Query for next idx at level iLevel */
120714  int iNext = 0;                  /* Result of query pNextIdx */
120715
120716  /* Set variable iNext to the next available segdir index at level iLevel. */
120717  rc = fts3SqlStmt(p, SQL_NEXT_SEGMENT_INDEX, &pNextIdx, 0);
120718  if( rc==SQLITE_OK ){
120719    sqlite3_bind_int(pNextIdx, 1, iLevel);
120720    if( SQLITE_ROW==sqlite3_step(pNextIdx) ){
120721      iNext = sqlite3_column_int(pNextIdx, 0);
120722    }
120723    rc = sqlite3_reset(pNextIdx);
120724  }
120725
120726  if( rc==SQLITE_OK ){
120727    /* If iNext is FTS3_MERGE_COUNT, indicating that level iLevel is already
120728    ** full, merge all segments in level iLevel into a single iLevel+1
120729    ** segment and allocate (newly freed) index 0 at level iLevel. Otherwise,
120730    ** if iNext is less than FTS3_MERGE_COUNT, allocate index iNext.
120731    */
120732    if( iNext>=FTS3_MERGE_COUNT ){
120733      rc = fts3SegmentMerge(p, iLevel);
120734      *piIdx = 0;
120735    }else{
120736      *piIdx = iNext;
120737    }
120738  }
120739
120740  return rc;
120741}
120742
120743/*
120744** The %_segments table is declared as follows:
120745**
120746**   CREATE TABLE %_segments(blockid INTEGER PRIMARY KEY, block BLOB)
120747**
120748** This function reads data from a single row of the %_segments table. The
120749** specific row is identified by the iBlockid parameter. If paBlob is not
120750** NULL, then a buffer is allocated using sqlite3_malloc() and populated
120751** with the contents of the blob stored in the "block" column of the
120752** identified table row is. Whether or not paBlob is NULL, *pnBlob is set
120753** to the size of the blob in bytes before returning.
120754**
120755** If an error occurs, or the table does not contain the specified row,
120756** an SQLite error code is returned. Otherwise, SQLITE_OK is returned. If
120757** paBlob is non-NULL, then it is the responsibility of the caller to
120758** eventually free the returned buffer.
120759**
120760** This function may leave an open sqlite3_blob* handle in the
120761** Fts3Table.pSegments variable. This handle is reused by subsequent calls
120762** to this function. The handle may be closed by calling the
120763** sqlite3Fts3SegmentsClose() function. Reusing a blob handle is a handy
120764** performance improvement, but the blob handle should always be closed
120765** before control is returned to the user (to prevent a lock being held
120766** on the database file for longer than necessary). Thus, any virtual table
120767** method (xFilter etc.) that may directly or indirectly call this function
120768** must call sqlite3Fts3SegmentsClose() before returning.
120769*/
120770SQLITE_PRIVATE int sqlite3Fts3ReadBlock(
120771  Fts3Table *p,                   /* FTS3 table handle */
120772  sqlite3_int64 iBlockid,         /* Access the row with blockid=$iBlockid */
120773  char **paBlob,                  /* OUT: Blob data in malloc'd buffer */
120774  int *pnBlob                     /* OUT: Size of blob data */
120775){
120776  int rc;                         /* Return code */
120777
120778  /* pnBlob must be non-NULL. paBlob may be NULL or non-NULL. */
120779  assert( pnBlob);
120780
120781  if( p->pSegments ){
120782    rc = sqlite3_blob_reopen(p->pSegments, iBlockid);
120783  }else{
120784    if( 0==p->zSegmentsTbl ){
120785      p->zSegmentsTbl = sqlite3_mprintf("%s_segments", p->zName);
120786      if( 0==p->zSegmentsTbl ) return SQLITE_NOMEM;
120787    }
120788    rc = sqlite3_blob_open(
120789       p->db, p->zDb, p->zSegmentsTbl, "block", iBlockid, 0, &p->pSegments
120790    );
120791  }
120792
120793  if( rc==SQLITE_OK ){
120794    int nByte = sqlite3_blob_bytes(p->pSegments);
120795    if( paBlob ){
120796      char *aByte = sqlite3_malloc(nByte + FTS3_NODE_PADDING);
120797      if( !aByte ){
120798        rc = SQLITE_NOMEM;
120799      }else{
120800        rc = sqlite3_blob_read(p->pSegments, aByte, nByte, 0);
120801        memset(&aByte[nByte], 0, FTS3_NODE_PADDING);
120802        if( rc!=SQLITE_OK ){
120803          sqlite3_free(aByte);
120804          aByte = 0;
120805        }
120806      }
120807      *paBlob = aByte;
120808    }
120809    *pnBlob = nByte;
120810  }
120811
120812  return rc;
120813}
120814
120815/*
120816** Close the blob handle at p->pSegments, if it is open. See comments above
120817** the sqlite3Fts3ReadBlock() function for details.
120818*/
120819SQLITE_PRIVATE void sqlite3Fts3SegmentsClose(Fts3Table *p){
120820  sqlite3_blob_close(p->pSegments);
120821  p->pSegments = 0;
120822}
120823
120824/*
120825** Move the iterator passed as the first argument to the next term in the
120826** segment. If successful, SQLITE_OK is returned. If there is no next term,
120827** SQLITE_DONE. Otherwise, an SQLite error code.
120828*/
120829static int fts3SegReaderNext(Fts3Table *p, Fts3SegReader *pReader){
120830  char *pNext;                    /* Cursor variable */
120831  int nPrefix;                    /* Number of bytes in term prefix */
120832  int nSuffix;                    /* Number of bytes in term suffix */
120833
120834  if( !pReader->aDoclist ){
120835    pNext = pReader->aNode;
120836  }else{
120837    pNext = &pReader->aDoclist[pReader->nDoclist];
120838  }
120839
120840  if( !pNext || pNext>=&pReader->aNode[pReader->nNode] ){
120841    int rc;                       /* Return code from Fts3ReadBlock() */
120842
120843    if( fts3SegReaderIsPending(pReader) ){
120844      Fts3HashElem *pElem = *(pReader->ppNextElem);
120845      if( pElem==0 ){
120846        pReader->aNode = 0;
120847      }else{
120848        PendingList *pList = (PendingList *)fts3HashData(pElem);
120849        pReader->zTerm = (char *)fts3HashKey(pElem);
120850        pReader->nTerm = fts3HashKeysize(pElem);
120851        pReader->nNode = pReader->nDoclist = pList->nData + 1;
120852        pReader->aNode = pReader->aDoclist = pList->aData;
120853        pReader->ppNextElem++;
120854        assert( pReader->aNode );
120855      }
120856      return SQLITE_OK;
120857    }
120858
120859    if( !fts3SegReaderIsRootOnly(pReader) ){
120860      sqlite3_free(pReader->aNode);
120861    }
120862    pReader->aNode = 0;
120863
120864    /* If iCurrentBlock>=iLeafEndBlock, this is an EOF condition. All leaf
120865    ** blocks have already been traversed.  */
120866    assert( pReader->iCurrentBlock<=pReader->iLeafEndBlock );
120867    if( pReader->iCurrentBlock>=pReader->iLeafEndBlock ){
120868      return SQLITE_OK;
120869    }
120870
120871    rc = sqlite3Fts3ReadBlock(
120872        p, ++pReader->iCurrentBlock, &pReader->aNode, &pReader->nNode
120873    );
120874    if( rc!=SQLITE_OK ) return rc;
120875    pNext = pReader->aNode;
120876  }
120877
120878  /* Because of the FTS3_NODE_PADDING bytes of padding, the following is
120879  ** safe (no risk of overread) even if the node data is corrupted.
120880  */
120881  pNext += sqlite3Fts3GetVarint32(pNext, &nPrefix);
120882  pNext += sqlite3Fts3GetVarint32(pNext, &nSuffix);
120883  if( nPrefix<0 || nSuffix<=0
120884   || &pNext[nSuffix]>&pReader->aNode[pReader->nNode]
120885  ){
120886    return SQLITE_CORRUPT;
120887  }
120888
120889  if( nPrefix+nSuffix>pReader->nTermAlloc ){
120890    int nNew = (nPrefix+nSuffix)*2;
120891    char *zNew = sqlite3_realloc(pReader->zTerm, nNew);
120892    if( !zNew ){
120893      return SQLITE_NOMEM;
120894    }
120895    pReader->zTerm = zNew;
120896    pReader->nTermAlloc = nNew;
120897  }
120898  memcpy(&pReader->zTerm[nPrefix], pNext, nSuffix);
120899  pReader->nTerm = nPrefix+nSuffix;
120900  pNext += nSuffix;
120901  pNext += sqlite3Fts3GetVarint32(pNext, &pReader->nDoclist);
120902  pReader->aDoclist = pNext;
120903  pReader->pOffsetList = 0;
120904
120905  /* Check that the doclist does not appear to extend past the end of the
120906  ** b-tree node. And that the final byte of the doclist is 0x00. If either
120907  ** of these statements is untrue, then the data structure is corrupt.
120908  */
120909  if( &pReader->aDoclist[pReader->nDoclist]>&pReader->aNode[pReader->nNode]
120910   || pReader->aDoclist[pReader->nDoclist-1]
120911  ){
120912    return SQLITE_CORRUPT;
120913  }
120914  return SQLITE_OK;
120915}
120916
120917/*
120918** Set the SegReader to point to the first docid in the doclist associated
120919** with the current term.
120920*/
120921static void fts3SegReaderFirstDocid(Fts3SegReader *pReader){
120922  int n;
120923  assert( pReader->aDoclist );
120924  assert( !pReader->pOffsetList );
120925  n = sqlite3Fts3GetVarint(pReader->aDoclist, &pReader->iDocid);
120926  pReader->pOffsetList = &pReader->aDoclist[n];
120927}
120928
120929/*
120930** Advance the SegReader to point to the next docid in the doclist
120931** associated with the current term.
120932**
120933** If arguments ppOffsetList and pnOffsetList are not NULL, then
120934** *ppOffsetList is set to point to the first column-offset list
120935** in the doclist entry (i.e. immediately past the docid varint).
120936** *pnOffsetList is set to the length of the set of column-offset
120937** lists, not including the nul-terminator byte. For example:
120938*/
120939static void fts3SegReaderNextDocid(
120940  Fts3SegReader *pReader,
120941  char **ppOffsetList,
120942  int *pnOffsetList
120943){
120944  char *p = pReader->pOffsetList;
120945  char c = 0;
120946
120947  /* Pointer p currently points at the first byte of an offset list. The
120948  ** following two lines advance it to point one byte past the end of
120949  ** the same offset list.
120950  */
120951  while( *p | c ) c = *p++ & 0x80;
120952  p++;
120953
120954  /* If required, populate the output variables with a pointer to and the
120955  ** size of the previous offset-list.
120956  */
120957  if( ppOffsetList ){
120958    *ppOffsetList = pReader->pOffsetList;
120959    *pnOffsetList = (int)(p - pReader->pOffsetList - 1);
120960  }
120961
120962  /* If there are no more entries in the doclist, set pOffsetList to
120963  ** NULL. Otherwise, set Fts3SegReader.iDocid to the next docid and
120964  ** Fts3SegReader.pOffsetList to point to the next offset list before
120965  ** returning.
120966  */
120967  if( p>=&pReader->aDoclist[pReader->nDoclist] ){
120968    pReader->pOffsetList = 0;
120969  }else{
120970    sqlite3_int64 iDelta;
120971    pReader->pOffsetList = p + sqlite3Fts3GetVarint(p, &iDelta);
120972    pReader->iDocid += iDelta;
120973  }
120974}
120975
120976/*
120977** This function is called to estimate the amount of data that will be
120978** loaded from the disk If SegReaderIterate() is called on this seg-reader,
120979** in units of average document size.
120980**
120981** This can be used as follows: If the caller has a small doclist that
120982** contains references to N documents, and is considering merging it with
120983** a large doclist (size X "average documents"), it may opt not to load
120984** the large doclist if X>N.
120985*/
120986SQLITE_PRIVATE int sqlite3Fts3SegReaderCost(
120987  Fts3Cursor *pCsr,               /* FTS3 cursor handle */
120988  Fts3SegReader *pReader,         /* Segment-reader handle */
120989  int *pnCost                     /* IN/OUT: Number of bytes read */
120990){
120991  Fts3Table *p = (Fts3Table*)pCsr->base.pVtab;
120992  int rc = SQLITE_OK;             /* Return code */
120993  int nCost = 0;                  /* Cost in bytes to return */
120994  int pgsz = p->nPgsz;            /* Database page size */
120995
120996  /* If this seg-reader is reading the pending-terms table, or if all data
120997  ** for the segment is stored on the root page of the b-tree, then the cost
120998  ** is zero. In this case all required data is already in main memory.
120999  */
121000  if( p->bHasStat
121001   && !fts3SegReaderIsPending(pReader)
121002   && !fts3SegReaderIsRootOnly(pReader)
121003  ){
121004    int nBlob = 0;
121005    sqlite3_int64 iBlock;
121006
121007    if( pCsr->nRowAvg==0 ){
121008      /* The average document size, which is required to calculate the cost
121009      ** of each doclist, has not yet been determined. Read the required
121010      ** data from the %_stat table to calculate it.
121011      **
121012      ** Entry 0 of the %_stat table is a blob containing (nCol+1) FTS3
121013      ** varints, where nCol is the number of columns in the FTS3 table.
121014      ** The first varint is the number of documents currently stored in
121015      ** the table. The following nCol varints contain the total amount of
121016      ** data stored in all rows of each column of the table, from left
121017      ** to right.
121018      */
121019      sqlite3_stmt *pStmt;
121020      sqlite3_int64 nDoc = 0;
121021      sqlite3_int64 nByte = 0;
121022      const char *pEnd;
121023      const char *a;
121024
121025      rc = sqlite3Fts3SelectDoctotal(p, &pStmt);
121026      if( rc!=SQLITE_OK ) return rc;
121027      a = sqlite3_column_blob(pStmt, 0);
121028      assert( a );
121029
121030      pEnd = &a[sqlite3_column_bytes(pStmt, 0)];
121031      a += sqlite3Fts3GetVarint(a, &nDoc);
121032      while( a<pEnd ){
121033        a += sqlite3Fts3GetVarint(a, &nByte);
121034      }
121035      if( nDoc==0 || nByte==0 ){
121036        sqlite3_reset(pStmt);
121037        return SQLITE_CORRUPT;
121038      }
121039
121040      pCsr->nRowAvg = (int)(((nByte / nDoc) + pgsz) / pgsz);
121041      assert( pCsr->nRowAvg>0 );
121042      rc = sqlite3_reset(pStmt);
121043      if( rc!=SQLITE_OK ) return rc;
121044    }
121045
121046    /* Assume that a blob flows over onto overflow pages if it is larger
121047    ** than (pgsz-35) bytes in size (the file-format documentation
121048    ** confirms this).
121049    */
121050    for(iBlock=pReader->iStartBlock; iBlock<=pReader->iLeafEndBlock; iBlock++){
121051      rc = sqlite3Fts3ReadBlock(p, iBlock, 0, &nBlob);
121052      if( rc!=SQLITE_OK ) break;
121053      if( (nBlob+35)>pgsz ){
121054        int nOvfl = (nBlob + 34)/pgsz;
121055        nCost += ((nOvfl + pCsr->nRowAvg - 1)/pCsr->nRowAvg);
121056      }
121057    }
121058  }
121059
121060  *pnCost += nCost;
121061  return rc;
121062}
121063
121064/*
121065** Free all allocations associated with the iterator passed as the
121066** second argument.
121067*/
121068SQLITE_PRIVATE void sqlite3Fts3SegReaderFree(Fts3SegReader *pReader){
121069  if( pReader && !fts3SegReaderIsPending(pReader) ){
121070    sqlite3_free(pReader->zTerm);
121071    if( !fts3SegReaderIsRootOnly(pReader) ){
121072      sqlite3_free(pReader->aNode);
121073    }
121074  }
121075  sqlite3_free(pReader);
121076}
121077
121078/*
121079** Allocate a new SegReader object.
121080*/
121081SQLITE_PRIVATE int sqlite3Fts3SegReaderNew(
121082  int iAge,                       /* Segment "age". */
121083  sqlite3_int64 iStartLeaf,       /* First leaf to traverse */
121084  sqlite3_int64 iEndLeaf,         /* Final leaf to traverse */
121085  sqlite3_int64 iEndBlock,        /* Final block of segment */
121086  const char *zRoot,              /* Buffer containing root node */
121087  int nRoot,                      /* Size of buffer containing root node */
121088  Fts3SegReader **ppReader        /* OUT: Allocated Fts3SegReader */
121089){
121090  int rc = SQLITE_OK;             /* Return code */
121091  Fts3SegReader *pReader;         /* Newly allocated SegReader object */
121092  int nExtra = 0;                 /* Bytes to allocate segment root node */
121093
121094  assert( iStartLeaf<=iEndLeaf );
121095  if( iStartLeaf==0 ){
121096    nExtra = nRoot + FTS3_NODE_PADDING;
121097  }
121098
121099  pReader = (Fts3SegReader *)sqlite3_malloc(sizeof(Fts3SegReader) + nExtra);
121100  if( !pReader ){
121101    return SQLITE_NOMEM;
121102  }
121103  memset(pReader, 0, sizeof(Fts3SegReader));
121104  pReader->iIdx = iAge;
121105  pReader->iStartBlock = iStartLeaf;
121106  pReader->iLeafEndBlock = iEndLeaf;
121107  pReader->iEndBlock = iEndBlock;
121108
121109  if( nExtra ){
121110    /* The entire segment is stored in the root node. */
121111    pReader->aNode = (char *)&pReader[1];
121112    pReader->nNode = nRoot;
121113    memcpy(pReader->aNode, zRoot, nRoot);
121114    memset(&pReader->aNode[nRoot], 0, FTS3_NODE_PADDING);
121115  }else{
121116    pReader->iCurrentBlock = iStartLeaf-1;
121117  }
121118
121119  if( rc==SQLITE_OK ){
121120    *ppReader = pReader;
121121  }else{
121122    sqlite3Fts3SegReaderFree(pReader);
121123  }
121124  return rc;
121125}
121126
121127/*
121128** This is a comparison function used as a qsort() callback when sorting
121129** an array of pending terms by term. This occurs as part of flushing
121130** the contents of the pending-terms hash table to the database.
121131*/
121132static int fts3CompareElemByTerm(const void *lhs, const void *rhs){
121133  char *z1 = fts3HashKey(*(Fts3HashElem **)lhs);
121134  char *z2 = fts3HashKey(*(Fts3HashElem **)rhs);
121135  int n1 = fts3HashKeysize(*(Fts3HashElem **)lhs);
121136  int n2 = fts3HashKeysize(*(Fts3HashElem **)rhs);
121137
121138  int n = (n1<n2 ? n1 : n2);
121139  int c = memcmp(z1, z2, n);
121140  if( c==0 ){
121141    c = n1 - n2;
121142  }
121143  return c;
121144}
121145
121146/*
121147** This function is used to allocate an Fts3SegReader that iterates through
121148** a subset of the terms stored in the Fts3Table.pendingTerms array.
121149*/
121150SQLITE_PRIVATE int sqlite3Fts3SegReaderPending(
121151  Fts3Table *p,                   /* Virtual table handle */
121152  const char *zTerm,              /* Term to search for */
121153  int nTerm,                      /* Size of buffer zTerm */
121154  int isPrefix,                   /* True for a term-prefix query */
121155  Fts3SegReader **ppReader        /* OUT: SegReader for pending-terms */
121156){
121157  Fts3SegReader *pReader = 0;     /* Fts3SegReader object to return */
121158  Fts3HashElem *pE;               /* Iterator variable */
121159  Fts3HashElem **aElem = 0;       /* Array of term hash entries to scan */
121160  int nElem = 0;                  /* Size of array at aElem */
121161  int rc = SQLITE_OK;             /* Return Code */
121162
121163  if( isPrefix ){
121164    int nAlloc = 0;               /* Size of allocated array at aElem */
121165
121166    for(pE=fts3HashFirst(&p->pendingTerms); pE; pE=fts3HashNext(pE)){
121167      char *zKey = (char *)fts3HashKey(pE);
121168      int nKey = fts3HashKeysize(pE);
121169      if( nTerm==0 || (nKey>=nTerm && 0==memcmp(zKey, zTerm, nTerm)) ){
121170        if( nElem==nAlloc ){
121171          Fts3HashElem **aElem2;
121172          nAlloc += 16;
121173          aElem2 = (Fts3HashElem **)sqlite3_realloc(
121174              aElem, nAlloc*sizeof(Fts3HashElem *)
121175          );
121176          if( !aElem2 ){
121177            rc = SQLITE_NOMEM;
121178            nElem = 0;
121179            break;
121180          }
121181          aElem = aElem2;
121182        }
121183        aElem[nElem++] = pE;
121184      }
121185    }
121186
121187    /* If more than one term matches the prefix, sort the Fts3HashElem
121188    ** objects in term order using qsort(). This uses the same comparison
121189    ** callback as is used when flushing terms to disk.
121190    */
121191    if( nElem>1 ){
121192      qsort(aElem, nElem, sizeof(Fts3HashElem *), fts3CompareElemByTerm);
121193    }
121194
121195  }else{
121196    pE = fts3HashFindElem(&p->pendingTerms, zTerm, nTerm);
121197    if( pE ){
121198      aElem = &pE;
121199      nElem = 1;
121200    }
121201  }
121202
121203  if( nElem>0 ){
121204    int nByte = sizeof(Fts3SegReader) + (nElem+1)*sizeof(Fts3HashElem *);
121205    pReader = (Fts3SegReader *)sqlite3_malloc(nByte);
121206    if( !pReader ){
121207      rc = SQLITE_NOMEM;
121208    }else{
121209      memset(pReader, 0, nByte);
121210      pReader->iIdx = 0x7FFFFFFF;
121211      pReader->ppNextElem = (Fts3HashElem **)&pReader[1];
121212      memcpy(pReader->ppNextElem, aElem, nElem*sizeof(Fts3HashElem *));
121213    }
121214  }
121215
121216  if( isPrefix ){
121217    sqlite3_free(aElem);
121218  }
121219  *ppReader = pReader;
121220  return rc;
121221}
121222
121223/*
121224** Compare the entries pointed to by two Fts3SegReader structures.
121225** Comparison is as follows:
121226**
121227**   1) EOF is greater than not EOF.
121228**
121229**   2) The current terms (if any) are compared using memcmp(). If one
121230**      term is a prefix of another, the longer term is considered the
121231**      larger.
121232**
121233**   3) By segment age. An older segment is considered larger.
121234*/
121235static int fts3SegReaderCmp(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
121236  int rc;
121237  if( pLhs->aNode && pRhs->aNode ){
121238    int rc2 = pLhs->nTerm - pRhs->nTerm;
121239    if( rc2<0 ){
121240      rc = memcmp(pLhs->zTerm, pRhs->zTerm, pLhs->nTerm);
121241    }else{
121242      rc = memcmp(pLhs->zTerm, pRhs->zTerm, pRhs->nTerm);
121243    }
121244    if( rc==0 ){
121245      rc = rc2;
121246    }
121247  }else{
121248    rc = (pLhs->aNode==0) - (pRhs->aNode==0);
121249  }
121250  if( rc==0 ){
121251    rc = pRhs->iIdx - pLhs->iIdx;
121252  }
121253  assert( rc!=0 );
121254  return rc;
121255}
121256
121257/*
121258** A different comparison function for SegReader structures. In this
121259** version, it is assumed that each SegReader points to an entry in
121260** a doclist for identical terms. Comparison is made as follows:
121261**
121262**   1) EOF (end of doclist in this case) is greater than not EOF.
121263**
121264**   2) By current docid.
121265**
121266**   3) By segment age. An older segment is considered larger.
121267*/
121268static int fts3SegReaderDoclistCmp(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
121269  int rc = (pLhs->pOffsetList==0)-(pRhs->pOffsetList==0);
121270  if( rc==0 ){
121271    if( pLhs->iDocid==pRhs->iDocid ){
121272      rc = pRhs->iIdx - pLhs->iIdx;
121273    }else{
121274      rc = (pLhs->iDocid > pRhs->iDocid) ? 1 : -1;
121275    }
121276  }
121277  assert( pLhs->aNode && pRhs->aNode );
121278  return rc;
121279}
121280
121281/*
121282** Compare the term that the Fts3SegReader object passed as the first argument
121283** points to with the term specified by arguments zTerm and nTerm.
121284**
121285** If the pSeg iterator is already at EOF, return 0. Otherwise, return
121286** -ve if the pSeg term is less than zTerm/nTerm, 0 if the two terms are
121287** equal, or +ve if the pSeg term is greater than zTerm/nTerm.
121288*/
121289static int fts3SegReaderTermCmp(
121290  Fts3SegReader *pSeg,            /* Segment reader object */
121291  const char *zTerm,              /* Term to compare to */
121292  int nTerm                       /* Size of term zTerm in bytes */
121293){
121294  int res = 0;
121295  if( pSeg->aNode ){
121296    if( pSeg->nTerm>nTerm ){
121297      res = memcmp(pSeg->zTerm, zTerm, nTerm);
121298    }else{
121299      res = memcmp(pSeg->zTerm, zTerm, pSeg->nTerm);
121300    }
121301    if( res==0 ){
121302      res = pSeg->nTerm-nTerm;
121303    }
121304  }
121305  return res;
121306}
121307
121308/*
121309** Argument apSegment is an array of nSegment elements. It is known that
121310** the final (nSegment-nSuspect) members are already in sorted order
121311** (according to the comparison function provided). This function shuffles
121312** the array around until all entries are in sorted order.
121313*/
121314static void fts3SegReaderSort(
121315  Fts3SegReader **apSegment,                     /* Array to sort entries of */
121316  int nSegment,                                  /* Size of apSegment array */
121317  int nSuspect,                                  /* Unsorted entry count */
121318  int (*xCmp)(Fts3SegReader *, Fts3SegReader *)  /* Comparison function */
121319){
121320  int i;                          /* Iterator variable */
121321
121322  assert( nSuspect<=nSegment );
121323
121324  if( nSuspect==nSegment ) nSuspect--;
121325  for(i=nSuspect-1; i>=0; i--){
121326    int j;
121327    for(j=i; j<(nSegment-1); j++){
121328      Fts3SegReader *pTmp;
121329      if( xCmp(apSegment[j], apSegment[j+1])<0 ) break;
121330      pTmp = apSegment[j+1];
121331      apSegment[j+1] = apSegment[j];
121332      apSegment[j] = pTmp;
121333    }
121334  }
121335
121336#ifndef NDEBUG
121337  /* Check that the list really is sorted now. */
121338  for(i=0; i<(nSuspect-1); i++){
121339    assert( xCmp(apSegment[i], apSegment[i+1])<0 );
121340  }
121341#endif
121342}
121343
121344/*
121345** Insert a record into the %_segments table.
121346*/
121347static int fts3WriteSegment(
121348  Fts3Table *p,                   /* Virtual table handle */
121349  sqlite3_int64 iBlock,           /* Block id for new block */
121350  char *z,                        /* Pointer to buffer containing block data */
121351  int n                           /* Size of buffer z in bytes */
121352){
121353  sqlite3_stmt *pStmt;
121354  int rc = fts3SqlStmt(p, SQL_INSERT_SEGMENTS, &pStmt, 0);
121355  if( rc==SQLITE_OK ){
121356    sqlite3_bind_int64(pStmt, 1, iBlock);
121357    sqlite3_bind_blob(pStmt, 2, z, n, SQLITE_STATIC);
121358    sqlite3_step(pStmt);
121359    rc = sqlite3_reset(pStmt);
121360  }
121361  return rc;
121362}
121363
121364/*
121365** Insert a record into the %_segdir table.
121366*/
121367static int fts3WriteSegdir(
121368  Fts3Table *p,                   /* Virtual table handle */
121369  int iLevel,                     /* Value for "level" field */
121370  int iIdx,                       /* Value for "idx" field */
121371  sqlite3_int64 iStartBlock,      /* Value for "start_block" field */
121372  sqlite3_int64 iLeafEndBlock,    /* Value for "leaves_end_block" field */
121373  sqlite3_int64 iEndBlock,        /* Value for "end_block" field */
121374  char *zRoot,                    /* Blob value for "root" field */
121375  int nRoot                       /* Number of bytes in buffer zRoot */
121376){
121377  sqlite3_stmt *pStmt;
121378  int rc = fts3SqlStmt(p, SQL_INSERT_SEGDIR, &pStmt, 0);
121379  if( rc==SQLITE_OK ){
121380    sqlite3_bind_int(pStmt, 1, iLevel);
121381    sqlite3_bind_int(pStmt, 2, iIdx);
121382    sqlite3_bind_int64(pStmt, 3, iStartBlock);
121383    sqlite3_bind_int64(pStmt, 4, iLeafEndBlock);
121384    sqlite3_bind_int64(pStmt, 5, iEndBlock);
121385    sqlite3_bind_blob(pStmt, 6, zRoot, nRoot, SQLITE_STATIC);
121386    sqlite3_step(pStmt);
121387    rc = sqlite3_reset(pStmt);
121388  }
121389  return rc;
121390}
121391
121392/*
121393** Return the size of the common prefix (if any) shared by zPrev and
121394** zNext, in bytes. For example,
121395**
121396**   fts3PrefixCompress("abc", 3, "abcdef", 6)   // returns 3
121397**   fts3PrefixCompress("abX", 3, "abcdef", 6)   // returns 2
121398**   fts3PrefixCompress("abX", 3, "Xbcdef", 6)   // returns 0
121399*/
121400static int fts3PrefixCompress(
121401  const char *zPrev,              /* Buffer containing previous term */
121402  int nPrev,                      /* Size of buffer zPrev in bytes */
121403  const char *zNext,              /* Buffer containing next term */
121404  int nNext                       /* Size of buffer zNext in bytes */
121405){
121406  int n;
121407  UNUSED_PARAMETER(nNext);
121408  for(n=0; n<nPrev && zPrev[n]==zNext[n]; n++);
121409  return n;
121410}
121411
121412/*
121413** Add term zTerm to the SegmentNode. It is guaranteed that zTerm is larger
121414** (according to memcmp) than the previous term.
121415*/
121416static int fts3NodeAddTerm(
121417  Fts3Table *p,                   /* Virtual table handle */
121418  SegmentNode **ppTree,           /* IN/OUT: SegmentNode handle */
121419  int isCopyTerm,                 /* True if zTerm/nTerm is transient */
121420  const char *zTerm,              /* Pointer to buffer containing term */
121421  int nTerm                       /* Size of term in bytes */
121422){
121423  SegmentNode *pTree = *ppTree;
121424  int rc;
121425  SegmentNode *pNew;
121426
121427  /* First try to append the term to the current node. Return early if
121428  ** this is possible.
121429  */
121430  if( pTree ){
121431    int nData = pTree->nData;     /* Current size of node in bytes */
121432    int nReq = nData;             /* Required space after adding zTerm */
121433    int nPrefix;                  /* Number of bytes of prefix compression */
121434    int nSuffix;                  /* Suffix length */
121435
121436    nPrefix = fts3PrefixCompress(pTree->zTerm, pTree->nTerm, zTerm, nTerm);
121437    nSuffix = nTerm-nPrefix;
121438
121439    nReq += sqlite3Fts3VarintLen(nPrefix)+sqlite3Fts3VarintLen(nSuffix)+nSuffix;
121440    if( nReq<=p->nNodeSize || !pTree->zTerm ){
121441
121442      if( nReq>p->nNodeSize ){
121443        /* An unusual case: this is the first term to be added to the node
121444        ** and the static node buffer (p->nNodeSize bytes) is not large
121445        ** enough. Use a separately malloced buffer instead This wastes
121446        ** p->nNodeSize bytes, but since this scenario only comes about when
121447        ** the database contain two terms that share a prefix of almost 2KB,
121448        ** this is not expected to be a serious problem.
121449        */
121450        assert( pTree->aData==(char *)&pTree[1] );
121451        pTree->aData = (char *)sqlite3_malloc(nReq);
121452        if( !pTree->aData ){
121453          return SQLITE_NOMEM;
121454        }
121455      }
121456
121457      if( pTree->zTerm ){
121458        /* There is no prefix-length field for first term in a node */
121459        nData += sqlite3Fts3PutVarint(&pTree->aData[nData], nPrefix);
121460      }
121461
121462      nData += sqlite3Fts3PutVarint(&pTree->aData[nData], nSuffix);
121463      memcpy(&pTree->aData[nData], &zTerm[nPrefix], nSuffix);
121464      pTree->nData = nData + nSuffix;
121465      pTree->nEntry++;
121466
121467      if( isCopyTerm ){
121468        if( pTree->nMalloc<nTerm ){
121469          char *zNew = sqlite3_realloc(pTree->zMalloc, nTerm*2);
121470          if( !zNew ){
121471            return SQLITE_NOMEM;
121472          }
121473          pTree->nMalloc = nTerm*2;
121474          pTree->zMalloc = zNew;
121475        }
121476        pTree->zTerm = pTree->zMalloc;
121477        memcpy(pTree->zTerm, zTerm, nTerm);
121478        pTree->nTerm = nTerm;
121479      }else{
121480        pTree->zTerm = (char *)zTerm;
121481        pTree->nTerm = nTerm;
121482      }
121483      return SQLITE_OK;
121484    }
121485  }
121486
121487  /* If control flows to here, it was not possible to append zTerm to the
121488  ** current node. Create a new node (a right-sibling of the current node).
121489  ** If this is the first node in the tree, the term is added to it.
121490  **
121491  ** Otherwise, the term is not added to the new node, it is left empty for
121492  ** now. Instead, the term is inserted into the parent of pTree. If pTree
121493  ** has no parent, one is created here.
121494  */
121495  pNew = (SegmentNode *)sqlite3_malloc(sizeof(SegmentNode) + p->nNodeSize);
121496  if( !pNew ){
121497    return SQLITE_NOMEM;
121498  }
121499  memset(pNew, 0, sizeof(SegmentNode));
121500  pNew->nData = 1 + FTS3_VARINT_MAX;
121501  pNew->aData = (char *)&pNew[1];
121502
121503  if( pTree ){
121504    SegmentNode *pParent = pTree->pParent;
121505    rc = fts3NodeAddTerm(p, &pParent, isCopyTerm, zTerm, nTerm);
121506    if( pTree->pParent==0 ){
121507      pTree->pParent = pParent;
121508    }
121509    pTree->pRight = pNew;
121510    pNew->pLeftmost = pTree->pLeftmost;
121511    pNew->pParent = pParent;
121512    pNew->zMalloc = pTree->zMalloc;
121513    pNew->nMalloc = pTree->nMalloc;
121514    pTree->zMalloc = 0;
121515  }else{
121516    pNew->pLeftmost = pNew;
121517    rc = fts3NodeAddTerm(p, &pNew, isCopyTerm, zTerm, nTerm);
121518  }
121519
121520  *ppTree = pNew;
121521  return rc;
121522}
121523
121524/*
121525** Helper function for fts3NodeWrite().
121526*/
121527static int fts3TreeFinishNode(
121528  SegmentNode *pTree,
121529  int iHeight,
121530  sqlite3_int64 iLeftChild
121531){
121532  int nStart;
121533  assert( iHeight>=1 && iHeight<128 );
121534  nStart = FTS3_VARINT_MAX - sqlite3Fts3VarintLen(iLeftChild);
121535  pTree->aData[nStart] = (char)iHeight;
121536  sqlite3Fts3PutVarint(&pTree->aData[nStart+1], iLeftChild);
121537  return nStart;
121538}
121539
121540/*
121541** Write the buffer for the segment node pTree and all of its peers to the
121542** database. Then call this function recursively to write the parent of
121543** pTree and its peers to the database.
121544**
121545** Except, if pTree is a root node, do not write it to the database. Instead,
121546** set output variables *paRoot and *pnRoot to contain the root node.
121547**
121548** If successful, SQLITE_OK is returned and output variable *piLast is
121549** set to the largest blockid written to the database (or zero if no
121550** blocks were written to the db). Otherwise, an SQLite error code is
121551** returned.
121552*/
121553static int fts3NodeWrite(
121554  Fts3Table *p,                   /* Virtual table handle */
121555  SegmentNode *pTree,             /* SegmentNode handle */
121556  int iHeight,                    /* Height of this node in tree */
121557  sqlite3_int64 iLeaf,            /* Block id of first leaf node */
121558  sqlite3_int64 iFree,            /* Block id of next free slot in %_segments */
121559  sqlite3_int64 *piLast,          /* OUT: Block id of last entry written */
121560  char **paRoot,                  /* OUT: Data for root node */
121561  int *pnRoot                     /* OUT: Size of root node in bytes */
121562){
121563  int rc = SQLITE_OK;
121564
121565  if( !pTree->pParent ){
121566    /* Root node of the tree. */
121567    int nStart = fts3TreeFinishNode(pTree, iHeight, iLeaf);
121568    *piLast = iFree-1;
121569    *pnRoot = pTree->nData - nStart;
121570    *paRoot = &pTree->aData[nStart];
121571  }else{
121572    SegmentNode *pIter;
121573    sqlite3_int64 iNextFree = iFree;
121574    sqlite3_int64 iNextLeaf = iLeaf;
121575    for(pIter=pTree->pLeftmost; pIter && rc==SQLITE_OK; pIter=pIter->pRight){
121576      int nStart = fts3TreeFinishNode(pIter, iHeight, iNextLeaf);
121577      int nWrite = pIter->nData - nStart;
121578
121579      rc = fts3WriteSegment(p, iNextFree, &pIter->aData[nStart], nWrite);
121580      iNextFree++;
121581      iNextLeaf += (pIter->nEntry+1);
121582    }
121583    if( rc==SQLITE_OK ){
121584      assert( iNextLeaf==iFree );
121585      rc = fts3NodeWrite(
121586          p, pTree->pParent, iHeight+1, iFree, iNextFree, piLast, paRoot, pnRoot
121587      );
121588    }
121589  }
121590
121591  return rc;
121592}
121593
121594/*
121595** Free all memory allocations associated with the tree pTree.
121596*/
121597static void fts3NodeFree(SegmentNode *pTree){
121598  if( pTree ){
121599    SegmentNode *p = pTree->pLeftmost;
121600    fts3NodeFree(p->pParent);
121601    while( p ){
121602      SegmentNode *pRight = p->pRight;
121603      if( p->aData!=(char *)&p[1] ){
121604        sqlite3_free(p->aData);
121605      }
121606      assert( pRight==0 || p->zMalloc==0 );
121607      sqlite3_free(p->zMalloc);
121608      sqlite3_free(p);
121609      p = pRight;
121610    }
121611  }
121612}
121613
121614/*
121615** Add a term to the segment being constructed by the SegmentWriter object
121616** *ppWriter. When adding the first term to a segment, *ppWriter should
121617** be passed NULL. This function will allocate a new SegmentWriter object
121618** and return it via the input/output variable *ppWriter in this case.
121619**
121620** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code.
121621*/
121622static int fts3SegWriterAdd(
121623  Fts3Table *p,                   /* Virtual table handle */
121624  SegmentWriter **ppWriter,       /* IN/OUT: SegmentWriter handle */
121625  int isCopyTerm,                 /* True if buffer zTerm must be copied */
121626  const char *zTerm,              /* Pointer to buffer containing term */
121627  int nTerm,                      /* Size of term in bytes */
121628  const char *aDoclist,           /* Pointer to buffer containing doclist */
121629  int nDoclist                    /* Size of doclist in bytes */
121630){
121631  int nPrefix;                    /* Size of term prefix in bytes */
121632  int nSuffix;                    /* Size of term suffix in bytes */
121633  int nReq;                       /* Number of bytes required on leaf page */
121634  int nData;
121635  SegmentWriter *pWriter = *ppWriter;
121636
121637  if( !pWriter ){
121638    int rc;
121639    sqlite3_stmt *pStmt;
121640
121641    /* Allocate the SegmentWriter structure */
121642    pWriter = (SegmentWriter *)sqlite3_malloc(sizeof(SegmentWriter));
121643    if( !pWriter ) return SQLITE_NOMEM;
121644    memset(pWriter, 0, sizeof(SegmentWriter));
121645    *ppWriter = pWriter;
121646
121647    /* Allocate a buffer in which to accumulate data */
121648    pWriter->aData = (char *)sqlite3_malloc(p->nNodeSize);
121649    if( !pWriter->aData ) return SQLITE_NOMEM;
121650    pWriter->nSize = p->nNodeSize;
121651
121652    /* Find the next free blockid in the %_segments table */
121653    rc = fts3SqlStmt(p, SQL_NEXT_SEGMENTS_ID, &pStmt, 0);
121654    if( rc!=SQLITE_OK ) return rc;
121655    if( SQLITE_ROW==sqlite3_step(pStmt) ){
121656      pWriter->iFree = sqlite3_column_int64(pStmt, 0);
121657      pWriter->iFirst = pWriter->iFree;
121658    }
121659    rc = sqlite3_reset(pStmt);
121660    if( rc!=SQLITE_OK ) return rc;
121661  }
121662  nData = pWriter->nData;
121663
121664  nPrefix = fts3PrefixCompress(pWriter->zTerm, pWriter->nTerm, zTerm, nTerm);
121665  nSuffix = nTerm-nPrefix;
121666
121667  /* Figure out how many bytes are required by this new entry */
121668  nReq = sqlite3Fts3VarintLen(nPrefix) +    /* varint containing prefix size */
121669    sqlite3Fts3VarintLen(nSuffix) +         /* varint containing suffix size */
121670    nSuffix +                               /* Term suffix */
121671    sqlite3Fts3VarintLen(nDoclist) +        /* Size of doclist */
121672    nDoclist;                               /* Doclist data */
121673
121674  if( nData>0 && nData+nReq>p->nNodeSize ){
121675    int rc;
121676
121677    /* The current leaf node is full. Write it out to the database. */
121678    rc = fts3WriteSegment(p, pWriter->iFree++, pWriter->aData, nData);
121679    if( rc!=SQLITE_OK ) return rc;
121680
121681    /* Add the current term to the interior node tree. The term added to
121682    ** the interior tree must:
121683    **
121684    **   a) be greater than the largest term on the leaf node just written
121685    **      to the database (still available in pWriter->zTerm), and
121686    **
121687    **   b) be less than or equal to the term about to be added to the new
121688    **      leaf node (zTerm/nTerm).
121689    **
121690    ** In other words, it must be the prefix of zTerm 1 byte longer than
121691    ** the common prefix (if any) of zTerm and pWriter->zTerm.
121692    */
121693    assert( nPrefix<nTerm );
121694    rc = fts3NodeAddTerm(p, &pWriter->pTree, isCopyTerm, zTerm, nPrefix+1);
121695    if( rc!=SQLITE_OK ) return rc;
121696
121697    nData = 0;
121698    pWriter->nTerm = 0;
121699
121700    nPrefix = 0;
121701    nSuffix = nTerm;
121702    nReq = 1 +                              /* varint containing prefix size */
121703      sqlite3Fts3VarintLen(nTerm) +         /* varint containing suffix size */
121704      nTerm +                               /* Term suffix */
121705      sqlite3Fts3VarintLen(nDoclist) +      /* Size of doclist */
121706      nDoclist;                             /* Doclist data */
121707  }
121708
121709  /* If the buffer currently allocated is too small for this entry, realloc
121710  ** the buffer to make it large enough.
121711  */
121712  if( nReq>pWriter->nSize ){
121713    char *aNew = sqlite3_realloc(pWriter->aData, nReq);
121714    if( !aNew ) return SQLITE_NOMEM;
121715    pWriter->aData = aNew;
121716    pWriter->nSize = nReq;
121717  }
121718  assert( nData+nReq<=pWriter->nSize );
121719
121720  /* Append the prefix-compressed term and doclist to the buffer. */
121721  nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nPrefix);
121722  nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nSuffix);
121723  memcpy(&pWriter->aData[nData], &zTerm[nPrefix], nSuffix);
121724  nData += nSuffix;
121725  nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nDoclist);
121726  memcpy(&pWriter->aData[nData], aDoclist, nDoclist);
121727  pWriter->nData = nData + nDoclist;
121728
121729  /* Save the current term so that it can be used to prefix-compress the next.
121730  ** If the isCopyTerm parameter is true, then the buffer pointed to by
121731  ** zTerm is transient, so take a copy of the term data. Otherwise, just
121732  ** store a copy of the pointer.
121733  */
121734  if( isCopyTerm ){
121735    if( nTerm>pWriter->nMalloc ){
121736      char *zNew = sqlite3_realloc(pWriter->zMalloc, nTerm*2);
121737      if( !zNew ){
121738        return SQLITE_NOMEM;
121739      }
121740      pWriter->nMalloc = nTerm*2;
121741      pWriter->zMalloc = zNew;
121742      pWriter->zTerm = zNew;
121743    }
121744    assert( pWriter->zTerm==pWriter->zMalloc );
121745    memcpy(pWriter->zTerm, zTerm, nTerm);
121746  }else{
121747    pWriter->zTerm = (char *)zTerm;
121748  }
121749  pWriter->nTerm = nTerm;
121750
121751  return SQLITE_OK;
121752}
121753
121754/*
121755** Flush all data associated with the SegmentWriter object pWriter to the
121756** database. This function must be called after all terms have been added
121757** to the segment using fts3SegWriterAdd(). If successful, SQLITE_OK is
121758** returned. Otherwise, an SQLite error code.
121759*/
121760static int fts3SegWriterFlush(
121761  Fts3Table *p,                   /* Virtual table handle */
121762  SegmentWriter *pWriter,         /* SegmentWriter to flush to the db */
121763  int iLevel,                     /* Value for 'level' column of %_segdir */
121764  int iIdx                        /* Value for 'idx' column of %_segdir */
121765){
121766  int rc;                         /* Return code */
121767  if( pWriter->pTree ){
121768    sqlite3_int64 iLast = 0;      /* Largest block id written to database */
121769    sqlite3_int64 iLastLeaf;      /* Largest leaf block id written to db */
121770    char *zRoot = NULL;           /* Pointer to buffer containing root node */
121771    int nRoot = 0;                /* Size of buffer zRoot */
121772
121773    iLastLeaf = pWriter->iFree;
121774    rc = fts3WriteSegment(p, pWriter->iFree++, pWriter->aData, pWriter->nData);
121775    if( rc==SQLITE_OK ){
121776      rc = fts3NodeWrite(p, pWriter->pTree, 1,
121777          pWriter->iFirst, pWriter->iFree, &iLast, &zRoot, &nRoot);
121778    }
121779    if( rc==SQLITE_OK ){
121780      rc = fts3WriteSegdir(
121781          p, iLevel, iIdx, pWriter->iFirst, iLastLeaf, iLast, zRoot, nRoot);
121782    }
121783  }else{
121784    /* The entire tree fits on the root node. Write it to the segdir table. */
121785    rc = fts3WriteSegdir(
121786        p, iLevel, iIdx, 0, 0, 0, pWriter->aData, pWriter->nData);
121787  }
121788  return rc;
121789}
121790
121791/*
121792** Release all memory held by the SegmentWriter object passed as the
121793** first argument.
121794*/
121795static void fts3SegWriterFree(SegmentWriter *pWriter){
121796  if( pWriter ){
121797    sqlite3_free(pWriter->aData);
121798    sqlite3_free(pWriter->zMalloc);
121799    fts3NodeFree(pWriter->pTree);
121800    sqlite3_free(pWriter);
121801  }
121802}
121803
121804/*
121805** The first value in the apVal[] array is assumed to contain an integer.
121806** This function tests if there exist any documents with docid values that
121807** are different from that integer. i.e. if deleting the document with docid
121808** apVal[0] would mean the FTS3 table were empty.
121809**
121810** If successful, *pisEmpty is set to true if the table is empty except for
121811** document apVal[0], or false otherwise, and SQLITE_OK is returned. If an
121812** error occurs, an SQLite error code is returned.
121813*/
121814static int fts3IsEmpty(Fts3Table *p, sqlite3_value **apVal, int *pisEmpty){
121815  sqlite3_stmt *pStmt;
121816  int rc;
121817  rc = fts3SqlStmt(p, SQL_IS_EMPTY, &pStmt, apVal);
121818  if( rc==SQLITE_OK ){
121819    if( SQLITE_ROW==sqlite3_step(pStmt) ){
121820      *pisEmpty = sqlite3_column_int(pStmt, 0);
121821    }
121822    rc = sqlite3_reset(pStmt);
121823  }
121824  return rc;
121825}
121826
121827/*
121828** Set *pnSegment to the total number of segments in the database. Set
121829** *pnMax to the largest segment level in the database (segment levels
121830** are stored in the 'level' column of the %_segdir table).
121831**
121832** Return SQLITE_OK if successful, or an SQLite error code if not.
121833*/
121834static int fts3SegmentCountMax(Fts3Table *p, int *pnSegment, int *pnMax){
121835  sqlite3_stmt *pStmt;
121836  int rc;
121837
121838  rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR_COUNT_MAX, &pStmt, 0);
121839  if( rc!=SQLITE_OK ) return rc;
121840  if( SQLITE_ROW==sqlite3_step(pStmt) ){
121841    *pnSegment = sqlite3_column_int(pStmt, 0);
121842    *pnMax = sqlite3_column_int(pStmt, 1);
121843  }
121844  return sqlite3_reset(pStmt);
121845}
121846
121847/*
121848** This function is used after merging multiple segments into a single large
121849** segment to delete the old, now redundant, segment b-trees. Specifically,
121850** it:
121851**
121852**   1) Deletes all %_segments entries for the segments associated with
121853**      each of the SegReader objects in the array passed as the third
121854**      argument, and
121855**
121856**   2) deletes all %_segdir entries with level iLevel, or all %_segdir
121857**      entries regardless of level if (iLevel<0).
121858**
121859** SQLITE_OK is returned if successful, otherwise an SQLite error code.
121860*/
121861static int fts3DeleteSegdir(
121862  Fts3Table *p,                   /* Virtual table handle */
121863  int iLevel,                     /* Level of %_segdir entries to delete */
121864  Fts3SegReader **apSegment,      /* Array of SegReader objects */
121865  int nReader                     /* Size of array apSegment */
121866){
121867  int rc;                         /* Return Code */
121868  int i;                          /* Iterator variable */
121869  sqlite3_stmt *pDelete;          /* SQL statement to delete rows */
121870
121871  rc = fts3SqlStmt(p, SQL_DELETE_SEGMENTS_RANGE, &pDelete, 0);
121872  for(i=0; rc==SQLITE_OK && i<nReader; i++){
121873    Fts3SegReader *pSegment = apSegment[i];
121874    if( pSegment->iStartBlock ){
121875      sqlite3_bind_int64(pDelete, 1, pSegment->iStartBlock);
121876      sqlite3_bind_int64(pDelete, 2, pSegment->iEndBlock);
121877      sqlite3_step(pDelete);
121878      rc = sqlite3_reset(pDelete);
121879    }
121880  }
121881  if( rc!=SQLITE_OK ){
121882    return rc;
121883  }
121884
121885  if( iLevel==FTS3_SEGCURSOR_ALL ){
121886    fts3SqlExec(&rc, p, SQL_DELETE_ALL_SEGDIR, 0);
121887  }else if( iLevel==FTS3_SEGCURSOR_PENDING ){
121888    sqlite3Fts3PendingTermsClear(p);
121889  }else{
121890    assert( iLevel>=0 );
121891    rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_BY_LEVEL, &pDelete, 0);
121892    if( rc==SQLITE_OK ){
121893      sqlite3_bind_int(pDelete, 1, iLevel);
121894      sqlite3_step(pDelete);
121895      rc = sqlite3_reset(pDelete);
121896    }
121897  }
121898
121899  return rc;
121900}
121901
121902/*
121903** When this function is called, buffer *ppList (size *pnList bytes) contains
121904** a position list that may (or may not) feature multiple columns. This
121905** function adjusts the pointer *ppList and the length *pnList so that they
121906** identify the subset of the position list that corresponds to column iCol.
121907**
121908** If there are no entries in the input position list for column iCol, then
121909** *pnList is set to zero before returning.
121910*/
121911static void fts3ColumnFilter(
121912  int iCol,                       /* Column to filter on */
121913  char **ppList,                  /* IN/OUT: Pointer to position list */
121914  int *pnList                     /* IN/OUT: Size of buffer *ppList in bytes */
121915){
121916  char *pList = *ppList;
121917  int nList = *pnList;
121918  char *pEnd = &pList[nList];
121919  int iCurrent = 0;
121920  char *p = pList;
121921
121922  assert( iCol>=0 );
121923  while( 1 ){
121924    char c = 0;
121925    while( p<pEnd && (c | *p)&0xFE ) c = *p++ & 0x80;
121926
121927    if( iCol==iCurrent ){
121928      nList = (int)(p - pList);
121929      break;
121930    }
121931
121932    nList -= (int)(p - pList);
121933    pList = p;
121934    if( nList==0 ){
121935      break;
121936    }
121937    p = &pList[1];
121938    p += sqlite3Fts3GetVarint32(p, &iCurrent);
121939  }
121940
121941  *ppList = pList;
121942  *pnList = nList;
121943}
121944
121945SQLITE_PRIVATE int sqlite3Fts3SegReaderStart(
121946  Fts3Table *p,                   /* Virtual table handle */
121947  Fts3SegReaderCursor *pCsr,      /* Cursor object */
121948  Fts3SegFilter *pFilter          /* Restrictions on range of iteration */
121949){
121950  int i;
121951
121952  /* Initialize the cursor object */
121953  pCsr->pFilter = pFilter;
121954
121955  /* If the Fts3SegFilter defines a specific term (or term prefix) to search
121956  ** for, then advance each segment iterator until it points to a term of
121957  ** equal or greater value than the specified term. This prevents many
121958  ** unnecessary merge/sort operations for the case where single segment
121959  ** b-tree leaf nodes contain more than one term.
121960  */
121961  for(i=0; i<pCsr->nSegment; i++){
121962    int nTerm = pFilter->nTerm;
121963    const char *zTerm = pFilter->zTerm;
121964    Fts3SegReader *pSeg = pCsr->apSegment[i];
121965    do {
121966      int rc = fts3SegReaderNext(p, pSeg);
121967      if( rc!=SQLITE_OK ) return rc;
121968    }while( zTerm && fts3SegReaderTermCmp(pSeg, zTerm, nTerm)<0 );
121969  }
121970  fts3SegReaderSort(
121971      pCsr->apSegment, pCsr->nSegment, pCsr->nSegment, fts3SegReaderCmp);
121972
121973  return SQLITE_OK;
121974}
121975
121976SQLITE_PRIVATE int sqlite3Fts3SegReaderStep(
121977  Fts3Table *p,                   /* Virtual table handle */
121978  Fts3SegReaderCursor *pCsr       /* Cursor object */
121979){
121980  int rc = SQLITE_OK;
121981
121982  int isIgnoreEmpty =  (pCsr->pFilter->flags & FTS3_SEGMENT_IGNORE_EMPTY);
121983  int isRequirePos =   (pCsr->pFilter->flags & FTS3_SEGMENT_REQUIRE_POS);
121984  int isColFilter =    (pCsr->pFilter->flags & FTS3_SEGMENT_COLUMN_FILTER);
121985  int isPrefix =       (pCsr->pFilter->flags & FTS3_SEGMENT_PREFIX);
121986  int isScan =         (pCsr->pFilter->flags & FTS3_SEGMENT_SCAN);
121987
121988  Fts3SegReader **apSegment = pCsr->apSegment;
121989  int nSegment = pCsr->nSegment;
121990  Fts3SegFilter *pFilter = pCsr->pFilter;
121991
121992  if( pCsr->nSegment==0 ) return SQLITE_OK;
121993
121994  do {
121995    int nMerge;
121996    int i;
121997
121998    /* Advance the first pCsr->nAdvance entries in the apSegment[] array
121999    ** forward. Then sort the list in order of current term again.
122000    */
122001    for(i=0; i<pCsr->nAdvance; i++){
122002      rc = fts3SegReaderNext(p, apSegment[i]);
122003      if( rc!=SQLITE_OK ) return rc;
122004    }
122005    fts3SegReaderSort(apSegment, nSegment, pCsr->nAdvance, fts3SegReaderCmp);
122006    pCsr->nAdvance = 0;
122007
122008    /* If all the seg-readers are at EOF, we're finished. return SQLITE_OK. */
122009    assert( rc==SQLITE_OK );
122010    if( apSegment[0]->aNode==0 ) break;
122011
122012    pCsr->nTerm = apSegment[0]->nTerm;
122013    pCsr->zTerm = apSegment[0]->zTerm;
122014
122015    /* If this is a prefix-search, and if the term that apSegment[0] points
122016    ** to does not share a suffix with pFilter->zTerm/nTerm, then all
122017    ** required callbacks have been made. In this case exit early.
122018    **
122019    ** Similarly, if this is a search for an exact match, and the first term
122020    ** of segment apSegment[0] is not a match, exit early.
122021    */
122022    if( pFilter->zTerm && !isScan ){
122023      if( pCsr->nTerm<pFilter->nTerm
122024       || (!isPrefix && pCsr->nTerm>pFilter->nTerm)
122025       || memcmp(pCsr->zTerm, pFilter->zTerm, pFilter->nTerm)
122026      ){
122027        break;
122028      }
122029    }
122030
122031    nMerge = 1;
122032    while( nMerge<nSegment
122033        && apSegment[nMerge]->aNode
122034        && apSegment[nMerge]->nTerm==pCsr->nTerm
122035        && 0==memcmp(pCsr->zTerm, apSegment[nMerge]->zTerm, pCsr->nTerm)
122036    ){
122037      nMerge++;
122038    }
122039
122040    assert( isIgnoreEmpty || (isRequirePos && !isColFilter) );
122041    if( nMerge==1 && !isIgnoreEmpty ){
122042      pCsr->aDoclist = apSegment[0]->aDoclist;
122043      pCsr->nDoclist = apSegment[0]->nDoclist;
122044      rc = SQLITE_ROW;
122045    }else{
122046      int nDoclist = 0;           /* Size of doclist */
122047      sqlite3_int64 iPrev = 0;    /* Previous docid stored in doclist */
122048
122049      /* The current term of the first nMerge entries in the array
122050      ** of Fts3SegReader objects is the same. The doclists must be merged
122051      ** and a single term returned with the merged doclist.
122052      */
122053      for(i=0; i<nMerge; i++){
122054        fts3SegReaderFirstDocid(apSegment[i]);
122055      }
122056      fts3SegReaderSort(apSegment, nMerge, nMerge, fts3SegReaderDoclistCmp);
122057      while( apSegment[0]->pOffsetList ){
122058        int j;                    /* Number of segments that share a docid */
122059        char *pList;
122060        int nList;
122061        int nByte;
122062        sqlite3_int64 iDocid = apSegment[0]->iDocid;
122063        fts3SegReaderNextDocid(apSegment[0], &pList, &nList);
122064        j = 1;
122065        while( j<nMerge
122066            && apSegment[j]->pOffsetList
122067            && apSegment[j]->iDocid==iDocid
122068        ){
122069          fts3SegReaderNextDocid(apSegment[j], 0, 0);
122070          j++;
122071        }
122072
122073        if( isColFilter ){
122074          fts3ColumnFilter(pFilter->iCol, &pList, &nList);
122075        }
122076
122077        if( !isIgnoreEmpty || nList>0 ){
122078          nByte = sqlite3Fts3VarintLen(iDocid-iPrev) + (isRequirePos?nList+1:0);
122079          if( nDoclist+nByte>pCsr->nBuffer ){
122080            char *aNew;
122081            pCsr->nBuffer = (nDoclist+nByte)*2;
122082            aNew = sqlite3_realloc(pCsr->aBuffer, pCsr->nBuffer);
122083            if( !aNew ){
122084              return SQLITE_NOMEM;
122085            }
122086            pCsr->aBuffer = aNew;
122087          }
122088          nDoclist += sqlite3Fts3PutVarint(
122089              &pCsr->aBuffer[nDoclist], iDocid-iPrev
122090          );
122091          iPrev = iDocid;
122092          if( isRequirePos ){
122093            memcpy(&pCsr->aBuffer[nDoclist], pList, nList);
122094            nDoclist += nList;
122095            pCsr->aBuffer[nDoclist++] = '\0';
122096          }
122097        }
122098
122099        fts3SegReaderSort(apSegment, nMerge, j, fts3SegReaderDoclistCmp);
122100      }
122101      if( nDoclist>0 ){
122102        pCsr->aDoclist = pCsr->aBuffer;
122103        pCsr->nDoclist = nDoclist;
122104        rc = SQLITE_ROW;
122105      }
122106    }
122107    pCsr->nAdvance = nMerge;
122108  }while( rc==SQLITE_OK );
122109
122110  return rc;
122111}
122112
122113SQLITE_PRIVATE void sqlite3Fts3SegReaderFinish(
122114  Fts3SegReaderCursor *pCsr       /* Cursor object */
122115){
122116  if( pCsr ){
122117    int i;
122118    for(i=0; i<pCsr->nSegment; i++){
122119      sqlite3Fts3SegReaderFree(pCsr->apSegment[i]);
122120    }
122121    sqlite3_free(pCsr->apSegment);
122122    sqlite3_free(pCsr->aBuffer);
122123
122124    pCsr->nSegment = 0;
122125    pCsr->apSegment = 0;
122126    pCsr->aBuffer = 0;
122127  }
122128}
122129
122130/*
122131** Merge all level iLevel segments in the database into a single
122132** iLevel+1 segment. Or, if iLevel<0, merge all segments into a
122133** single segment with a level equal to the numerically largest level
122134** currently present in the database.
122135**
122136** If this function is called with iLevel<0, but there is only one
122137** segment in the database, SQLITE_DONE is returned immediately.
122138** Otherwise, if successful, SQLITE_OK is returned. If an error occurs,
122139** an SQLite error code is returned.
122140*/
122141static int fts3SegmentMerge(Fts3Table *p, int iLevel){
122142  int rc;                         /* Return code */
122143  int iIdx = 0;                   /* Index of new segment */
122144  int iNewLevel = 0;              /* Level to create new segment at */
122145  SegmentWriter *pWriter = 0;     /* Used to write the new, merged, segment */
122146  Fts3SegFilter filter;           /* Segment term filter condition */
122147  Fts3SegReaderCursor csr;        /* Cursor to iterate through level(s) */
122148
122149  rc = sqlite3Fts3SegReaderCursor(p, iLevel, 0, 0, 1, 0, &csr);
122150  if( rc!=SQLITE_OK || csr.nSegment==0 ) goto finished;
122151
122152  if( iLevel==FTS3_SEGCURSOR_ALL ){
122153    /* This call is to merge all segments in the database to a single
122154    ** segment. The level of the new segment is equal to the the numerically
122155    ** greatest segment level currently present in the database. The index
122156    ** of the new segment is always 0.  */
122157    int nDummy; /* TODO: Remove this */
122158    if( csr.nSegment==1 ){
122159      rc = SQLITE_DONE;
122160      goto finished;
122161    }
122162    rc = fts3SegmentCountMax(p, &nDummy, &iNewLevel);
122163  }else{
122164    /* This call is to merge all segments at level iLevel. Find the next
122165    ** available segment index at level iLevel+1. The call to
122166    ** fts3AllocateSegdirIdx() will merge the segments at level iLevel+1 to
122167    ** a single iLevel+2 segment if necessary.  */
122168    iNewLevel = iLevel+1;
122169    rc = fts3AllocateSegdirIdx(p, iNewLevel, &iIdx);
122170  }
122171  if( rc!=SQLITE_OK ) goto finished;
122172  assert( csr.nSegment>0 );
122173  assert( iNewLevel>=0 );
122174
122175  memset(&filter, 0, sizeof(Fts3SegFilter));
122176  filter.flags = FTS3_SEGMENT_REQUIRE_POS;
122177  filter.flags |= (iLevel==FTS3_SEGCURSOR_ALL ? FTS3_SEGMENT_IGNORE_EMPTY : 0);
122178
122179  rc = sqlite3Fts3SegReaderStart(p, &csr, &filter);
122180  while( SQLITE_OK==rc ){
122181    rc = sqlite3Fts3SegReaderStep(p, &csr);
122182    if( rc!=SQLITE_ROW ) break;
122183    rc = fts3SegWriterAdd(p, &pWriter, 1,
122184        csr.zTerm, csr.nTerm, csr.aDoclist, csr.nDoclist);
122185  }
122186  if( rc!=SQLITE_OK ) goto finished;
122187  assert( pWriter );
122188
122189  rc = fts3DeleteSegdir(p, iLevel, csr.apSegment, csr.nSegment);
122190  if( rc!=SQLITE_OK ) goto finished;
122191  rc = fts3SegWriterFlush(p, pWriter, iNewLevel, iIdx);
122192
122193 finished:
122194  fts3SegWriterFree(pWriter);
122195  sqlite3Fts3SegReaderFinish(&csr);
122196  return rc;
122197}
122198
122199
122200/*
122201** Flush the contents of pendingTerms to a level 0 segment.
122202*/
122203SQLITE_PRIVATE int sqlite3Fts3PendingTermsFlush(Fts3Table *p){
122204  return fts3SegmentMerge(p, FTS3_SEGCURSOR_PENDING);
122205}
122206
122207/*
122208** Encode N integers as varints into a blob.
122209*/
122210static void fts3EncodeIntArray(
122211  int N,             /* The number of integers to encode */
122212  u32 *a,            /* The integer values */
122213  char *zBuf,        /* Write the BLOB here */
122214  int *pNBuf         /* Write number of bytes if zBuf[] used here */
122215){
122216  int i, j;
122217  for(i=j=0; i<N; i++){
122218    j += sqlite3Fts3PutVarint(&zBuf[j], (sqlite3_int64)a[i]);
122219  }
122220  *pNBuf = j;
122221}
122222
122223/*
122224** Decode a blob of varints into N integers
122225*/
122226static void fts3DecodeIntArray(
122227  int N,             /* The number of integers to decode */
122228  u32 *a,            /* Write the integer values */
122229  const char *zBuf,  /* The BLOB containing the varints */
122230  int nBuf           /* size of the BLOB */
122231){
122232  int i, j;
122233  UNUSED_PARAMETER(nBuf);
122234  for(i=j=0; i<N; i++){
122235    sqlite3_int64 x;
122236    j += sqlite3Fts3GetVarint(&zBuf[j], &x);
122237    assert(j<=nBuf);
122238    a[i] = (u32)(x & 0xffffffff);
122239  }
122240}
122241
122242/*
122243** Insert the sizes (in tokens) for each column of the document
122244** with docid equal to p->iPrevDocid.  The sizes are encoded as
122245** a blob of varints.
122246*/
122247static void fts3InsertDocsize(
122248  int *pRC,         /* Result code */
122249  Fts3Table *p,     /* Table into which to insert */
122250  u32 *aSz          /* Sizes of each column */
122251){
122252  char *pBlob;             /* The BLOB encoding of the document size */
122253  int nBlob;               /* Number of bytes in the BLOB */
122254  sqlite3_stmt *pStmt;     /* Statement used to insert the encoding */
122255  int rc;                  /* Result code from subfunctions */
122256
122257  if( *pRC ) return;
122258  pBlob = sqlite3_malloc( 10*p->nColumn );
122259  if( pBlob==0 ){
122260    *pRC = SQLITE_NOMEM;
122261    return;
122262  }
122263  fts3EncodeIntArray(p->nColumn, aSz, pBlob, &nBlob);
122264  rc = fts3SqlStmt(p, SQL_REPLACE_DOCSIZE, &pStmt, 0);
122265  if( rc ){
122266    sqlite3_free(pBlob);
122267    *pRC = rc;
122268    return;
122269  }
122270  sqlite3_bind_int64(pStmt, 1, p->iPrevDocid);
122271  sqlite3_bind_blob(pStmt, 2, pBlob, nBlob, sqlite3_free);
122272  sqlite3_step(pStmt);
122273  *pRC = sqlite3_reset(pStmt);
122274}
122275
122276/*
122277** Record 0 of the %_stat table contains a blob consisting of N varints,
122278** where N is the number of user defined columns in the fts3 table plus
122279** two. If nCol is the number of user defined columns, then values of the
122280** varints are set as follows:
122281**
122282**   Varint 0:       Total number of rows in the table.
122283**
122284**   Varint 1..nCol: For each column, the total number of tokens stored in
122285**                   the column for all rows of the table.
122286**
122287**   Varint 1+nCol:  The total size, in bytes, of all text values in all
122288**                   columns of all rows of the table.
122289**
122290*/
122291static void fts3UpdateDocTotals(
122292  int *pRC,                       /* The result code */
122293  Fts3Table *p,                   /* Table being updated */
122294  u32 *aSzIns,                    /* Size increases */
122295  u32 *aSzDel,                    /* Size decreases */
122296  int nChng                       /* Change in the number of documents */
122297){
122298  char *pBlob;             /* Storage for BLOB written into %_stat */
122299  int nBlob;               /* Size of BLOB written into %_stat */
122300  u32 *a;                  /* Array of integers that becomes the BLOB */
122301  sqlite3_stmt *pStmt;     /* Statement for reading and writing */
122302  int i;                   /* Loop counter */
122303  int rc;                  /* Result code from subfunctions */
122304
122305  const int nStat = p->nColumn+2;
122306
122307  if( *pRC ) return;
122308  a = sqlite3_malloc( (sizeof(u32)+10)*nStat );
122309  if( a==0 ){
122310    *pRC = SQLITE_NOMEM;
122311    return;
122312  }
122313  pBlob = (char*)&a[nStat];
122314  rc = fts3SqlStmt(p, SQL_SELECT_DOCTOTAL, &pStmt, 0);
122315  if( rc ){
122316    sqlite3_free(a);
122317    *pRC = rc;
122318    return;
122319  }
122320  if( sqlite3_step(pStmt)==SQLITE_ROW ){
122321    fts3DecodeIntArray(nStat, a,
122322         sqlite3_column_blob(pStmt, 0),
122323         sqlite3_column_bytes(pStmt, 0));
122324  }else{
122325    memset(a, 0, sizeof(u32)*(nStat) );
122326  }
122327  sqlite3_reset(pStmt);
122328  if( nChng<0 && a[0]<(u32)(-nChng) ){
122329    a[0] = 0;
122330  }else{
122331    a[0] += nChng;
122332  }
122333  for(i=0; i<p->nColumn+1; i++){
122334    u32 x = a[i+1];
122335    if( x+aSzIns[i] < aSzDel[i] ){
122336      x = 0;
122337    }else{
122338      x = x + aSzIns[i] - aSzDel[i];
122339    }
122340    a[i+1] = x;
122341  }
122342  fts3EncodeIntArray(nStat, a, pBlob, &nBlob);
122343  rc = fts3SqlStmt(p, SQL_REPLACE_DOCTOTAL, &pStmt, 0);
122344  if( rc ){
122345    sqlite3_free(a);
122346    *pRC = rc;
122347    return;
122348  }
122349  sqlite3_bind_blob(pStmt, 1, pBlob, nBlob, SQLITE_STATIC);
122350  sqlite3_step(pStmt);
122351  *pRC = sqlite3_reset(pStmt);
122352  sqlite3_free(a);
122353}
122354
122355/*
122356** Handle a 'special' INSERT of the form:
122357**
122358**   "INSERT INTO tbl(tbl) VALUES(<expr>)"
122359**
122360** Argument pVal contains the result of <expr>. Currently the only
122361** meaningful value to insert is the text 'optimize'.
122362*/
122363static int fts3SpecialInsert(Fts3Table *p, sqlite3_value *pVal){
122364  int rc;                         /* Return Code */
122365  const char *zVal = (const char *)sqlite3_value_text(pVal);
122366  int nVal = sqlite3_value_bytes(pVal);
122367
122368  if( !zVal ){
122369    return SQLITE_NOMEM;
122370  }else if( nVal==8 && 0==sqlite3_strnicmp(zVal, "optimize", 8) ){
122371    rc = fts3SegmentMerge(p, FTS3_SEGCURSOR_ALL);
122372    if( rc==SQLITE_DONE ){
122373      rc = SQLITE_OK;
122374    }else{
122375      sqlite3Fts3PendingTermsClear(p);
122376    }
122377#ifdef SQLITE_TEST
122378  }else if( nVal>9 && 0==sqlite3_strnicmp(zVal, "nodesize=", 9) ){
122379    p->nNodeSize = atoi(&zVal[9]);
122380    rc = SQLITE_OK;
122381  }else if( nVal>11 && 0==sqlite3_strnicmp(zVal, "maxpending=", 9) ){
122382    p->nMaxPendingData = atoi(&zVal[11]);
122383    rc = SQLITE_OK;
122384#endif
122385  }else{
122386    rc = SQLITE_ERROR;
122387  }
122388
122389  sqlite3Fts3SegmentsClose(p);
122390  return rc;
122391}
122392
122393/*
122394** Return the deferred doclist associated with deferred token pDeferred.
122395** This function assumes that sqlite3Fts3CacheDeferredDoclists() has already
122396** been called to allocate and populate the doclist.
122397*/
122398SQLITE_PRIVATE char *sqlite3Fts3DeferredDoclist(Fts3DeferredToken *pDeferred, int *pnByte){
122399  if( pDeferred->pList ){
122400    *pnByte = pDeferred->pList->nData;
122401    return pDeferred->pList->aData;
122402  }
122403  *pnByte = 0;
122404  return 0;
122405}
122406
122407/*
122408** Helper fucntion for FreeDeferredDoclists(). This function removes all
122409** references to deferred doclists from within the tree of Fts3Expr
122410** structures headed by
122411*/
122412static void fts3DeferredDoclistClear(Fts3Expr *pExpr){
122413  if( pExpr ){
122414    fts3DeferredDoclistClear(pExpr->pLeft);
122415    fts3DeferredDoclistClear(pExpr->pRight);
122416    if( pExpr->isLoaded ){
122417      sqlite3_free(pExpr->aDoclist);
122418      pExpr->isLoaded = 0;
122419      pExpr->aDoclist = 0;
122420      pExpr->nDoclist = 0;
122421      pExpr->pCurrent = 0;
122422      pExpr->iCurrent = 0;
122423    }
122424  }
122425}
122426
122427/*
122428** Delete all cached deferred doclists. Deferred doclists are cached
122429** (allocated) by the sqlite3Fts3CacheDeferredDoclists() function.
122430*/
122431SQLITE_PRIVATE void sqlite3Fts3FreeDeferredDoclists(Fts3Cursor *pCsr){
122432  Fts3DeferredToken *pDef;
122433  for(pDef=pCsr->pDeferred; pDef; pDef=pDef->pNext){
122434    sqlite3_free(pDef->pList);
122435    pDef->pList = 0;
122436  }
122437  if( pCsr->pDeferred ){
122438    fts3DeferredDoclistClear(pCsr->pExpr);
122439  }
122440}
122441
122442/*
122443** Free all entries in the pCsr->pDeffered list. Entries are added to
122444** this list using sqlite3Fts3DeferToken().
122445*/
122446SQLITE_PRIVATE void sqlite3Fts3FreeDeferredTokens(Fts3Cursor *pCsr){
122447  Fts3DeferredToken *pDef;
122448  Fts3DeferredToken *pNext;
122449  for(pDef=pCsr->pDeferred; pDef; pDef=pNext){
122450    pNext = pDef->pNext;
122451    sqlite3_free(pDef->pList);
122452    sqlite3_free(pDef);
122453  }
122454  pCsr->pDeferred = 0;
122455}
122456
122457/*
122458** Generate deferred-doclists for all tokens in the pCsr->pDeferred list
122459** based on the row that pCsr currently points to.
122460**
122461** A deferred-doclist is like any other doclist with position information
122462** included, except that it only contains entries for a single row of the
122463** table, not for all rows.
122464*/
122465SQLITE_PRIVATE int sqlite3Fts3CacheDeferredDoclists(Fts3Cursor *pCsr){
122466  int rc = SQLITE_OK;             /* Return code */
122467  if( pCsr->pDeferred ){
122468    int i;                        /* Used to iterate through table columns */
122469    sqlite3_int64 iDocid;         /* Docid of the row pCsr points to */
122470    Fts3DeferredToken *pDef;      /* Used to iterate through deferred tokens */
122471
122472    Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
122473    sqlite3_tokenizer *pT = p->pTokenizer;
122474    sqlite3_tokenizer_module const *pModule = pT->pModule;
122475
122476    assert( pCsr->isRequireSeek==0 );
122477    iDocid = sqlite3_column_int64(pCsr->pStmt, 0);
122478
122479    for(i=0; i<p->nColumn && rc==SQLITE_OK; i++){
122480      const char *zText = (const char *)sqlite3_column_text(pCsr->pStmt, i+1);
122481      sqlite3_tokenizer_cursor *pTC = 0;
122482
122483      rc = pModule->xOpen(pT, zText, -1, &pTC);
122484      while( rc==SQLITE_OK ){
122485        char const *zToken;       /* Buffer containing token */
122486        int nToken;               /* Number of bytes in token */
122487        int iDum1, iDum2;         /* Dummy variables */
122488        int iPos;                 /* Position of token in zText */
122489
122490        pTC->pTokenizer = pT;
122491        rc = pModule->xNext(pTC, &zToken, &nToken, &iDum1, &iDum2, &iPos);
122492        for(pDef=pCsr->pDeferred; pDef && rc==SQLITE_OK; pDef=pDef->pNext){
122493          Fts3PhraseToken *pPT = pDef->pToken;
122494          if( (pDef->iCol>=p->nColumn || pDef->iCol==i)
122495           && (pPT->n==nToken || (pPT->isPrefix && pPT->n<nToken))
122496           && (0==memcmp(zToken, pPT->z, pPT->n))
122497          ){
122498            fts3PendingListAppend(&pDef->pList, iDocid, i, iPos, &rc);
122499          }
122500        }
122501      }
122502      if( pTC ) pModule->xClose(pTC);
122503      if( rc==SQLITE_DONE ) rc = SQLITE_OK;
122504    }
122505
122506    for(pDef=pCsr->pDeferred; pDef && rc==SQLITE_OK; pDef=pDef->pNext){
122507      if( pDef->pList ){
122508        rc = fts3PendingListAppendVarint(&pDef->pList, 0);
122509      }
122510    }
122511  }
122512
122513  return rc;
122514}
122515
122516/*
122517** Add an entry for token pToken to the pCsr->pDeferred list.
122518*/
122519SQLITE_PRIVATE int sqlite3Fts3DeferToken(
122520  Fts3Cursor *pCsr,               /* Fts3 table cursor */
122521  Fts3PhraseToken *pToken,        /* Token to defer */
122522  int iCol                        /* Column that token must appear in (or -1) */
122523){
122524  Fts3DeferredToken *pDeferred;
122525  pDeferred = sqlite3_malloc(sizeof(*pDeferred));
122526  if( !pDeferred ){
122527    return SQLITE_NOMEM;
122528  }
122529  memset(pDeferred, 0, sizeof(*pDeferred));
122530  pDeferred->pToken = pToken;
122531  pDeferred->pNext = pCsr->pDeferred;
122532  pDeferred->iCol = iCol;
122533  pCsr->pDeferred = pDeferred;
122534
122535  assert( pToken->pDeferred==0 );
122536  pToken->pDeferred = pDeferred;
122537
122538  return SQLITE_OK;
122539}
122540
122541
122542/*
122543** This function does the work for the xUpdate method of FTS3 virtual
122544** tables.
122545*/
122546SQLITE_PRIVATE int sqlite3Fts3UpdateMethod(
122547  sqlite3_vtab *pVtab,            /* FTS3 vtab object */
122548  int nArg,                       /* Size of argument array */
122549  sqlite3_value **apVal,          /* Array of arguments */
122550  sqlite_int64 *pRowid            /* OUT: The affected (or effected) rowid */
122551){
122552  Fts3Table *p = (Fts3Table *)pVtab;
122553  int rc = SQLITE_OK;             /* Return Code */
122554  int isRemove = 0;               /* True for an UPDATE or DELETE */
122555  sqlite3_int64 iRemove = 0;      /* Rowid removed by UPDATE or DELETE */
122556  u32 *aSzIns;                    /* Sizes of inserted documents */
122557  u32 *aSzDel;                    /* Sizes of deleted documents */
122558  int nChng = 0;                  /* Net change in number of documents */
122559
122560  assert( p->pSegments==0 );
122561
122562  /* Allocate space to hold the change in document sizes */
122563  aSzIns = sqlite3_malloc( sizeof(aSzIns[0])*(p->nColumn+1)*2 );
122564  if( aSzIns==0 ) return SQLITE_NOMEM;
122565  aSzDel = &aSzIns[p->nColumn+1];
122566  memset(aSzIns, 0, sizeof(aSzIns[0])*(p->nColumn+1)*2);
122567
122568  /* If this is a DELETE or UPDATE operation, remove the old record. */
122569  if( sqlite3_value_type(apVal[0])!=SQLITE_NULL ){
122570    int isEmpty = 0;
122571    rc = fts3IsEmpty(p, apVal, &isEmpty);
122572    if( rc==SQLITE_OK ){
122573      if( isEmpty ){
122574        /* Deleting this row means the whole table is empty. In this case
122575        ** delete the contents of all three tables and throw away any
122576        ** data in the pendingTerms hash table.
122577        */
122578        rc = fts3DeleteAll(p);
122579      }else{
122580        isRemove = 1;
122581        iRemove = sqlite3_value_int64(apVal[0]);
122582        rc = fts3PendingTermsDocid(p, iRemove);
122583        fts3DeleteTerms(&rc, p, apVal, aSzDel);
122584        fts3SqlExec(&rc, p, SQL_DELETE_CONTENT, apVal);
122585        if( p->bHasDocsize ){
122586          fts3SqlExec(&rc, p, SQL_DELETE_DOCSIZE, apVal);
122587        }
122588        nChng--;
122589      }
122590    }
122591  }else if( sqlite3_value_type(apVal[p->nColumn+2])!=SQLITE_NULL ){
122592    sqlite3_free(aSzIns);
122593    return fts3SpecialInsert(p, apVal[p->nColumn+2]);
122594  }
122595
122596  /* If this is an INSERT or UPDATE operation, insert the new record. */
122597  if( nArg>1 && rc==SQLITE_OK ){
122598    rc = fts3InsertData(p, apVal, pRowid);
122599    if( rc==SQLITE_OK && (!isRemove || *pRowid!=iRemove) ){
122600      rc = fts3PendingTermsDocid(p, *pRowid);
122601    }
122602    if( rc==SQLITE_OK ){
122603      rc = fts3InsertTerms(p, apVal, aSzIns);
122604    }
122605    if( p->bHasDocsize ){
122606      fts3InsertDocsize(&rc, p, aSzIns);
122607    }
122608    nChng++;
122609  }
122610
122611  if( p->bHasStat ){
122612    fts3UpdateDocTotals(&rc, p, aSzIns, aSzDel, nChng);
122613  }
122614
122615  sqlite3_free(aSzIns);
122616  sqlite3Fts3SegmentsClose(p);
122617  return rc;
122618}
122619
122620/*
122621** Flush any data in the pending-terms hash table to disk. If successful,
122622** merge all segments in the database (including the new segment, if
122623** there was any data to flush) into a single segment.
122624*/
122625SQLITE_PRIVATE int sqlite3Fts3Optimize(Fts3Table *p){
122626  int rc;
122627  rc = sqlite3_exec(p->db, "SAVEPOINT fts3", 0, 0, 0);
122628  if( rc==SQLITE_OK ){
122629    rc = fts3SegmentMerge(p, FTS3_SEGCURSOR_ALL);
122630    if( rc==SQLITE_OK ){
122631      rc = sqlite3_exec(p->db, "RELEASE fts3", 0, 0, 0);
122632      if( rc==SQLITE_OK ){
122633        sqlite3Fts3PendingTermsClear(p);
122634      }
122635    }else{
122636      sqlite3_exec(p->db, "ROLLBACK TO fts3", 0, 0, 0);
122637      sqlite3_exec(p->db, "RELEASE fts3", 0, 0, 0);
122638    }
122639  }
122640  sqlite3Fts3SegmentsClose(p);
122641  return rc;
122642}
122643
122644#endif
122645
122646/************** End of fts3_write.c ******************************************/
122647/************** Begin file fts3_snippet.c ************************************/
122648/*
122649** 2009 Oct 23
122650**
122651** The author disclaims copyright to this source code.  In place of
122652** a legal notice, here is a blessing:
122653**
122654**    May you do good and not evil.
122655**    May you find forgiveness for yourself and forgive others.
122656**    May you share freely, never taking more than you give.
122657**
122658******************************************************************************
122659*/
122660
122661#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
122662
122663
122664/*
122665** Characters that may appear in the second argument to matchinfo().
122666*/
122667#define FTS3_MATCHINFO_NPHRASE   'p'        /* 1 value */
122668#define FTS3_MATCHINFO_NCOL      'c'        /* 1 value */
122669#define FTS3_MATCHINFO_NDOC      'n'        /* 1 value */
122670#define FTS3_MATCHINFO_AVGLENGTH 'a'        /* nCol values */
122671#define FTS3_MATCHINFO_LENGTH    'l'        /* nCol values */
122672#define FTS3_MATCHINFO_LCS       's'        /* nCol values */
122673#define FTS3_MATCHINFO_HITS      'x'        /* 3*nCol*nPhrase values */
122674
122675/*
122676** The default value for the second argument to matchinfo().
122677*/
122678#define FTS3_MATCHINFO_DEFAULT   "pcx"
122679
122680
122681/*
122682** Used as an fts3ExprIterate() context when loading phrase doclists to
122683** Fts3Expr.aDoclist[]/nDoclist.
122684*/
122685typedef struct LoadDoclistCtx LoadDoclistCtx;
122686struct LoadDoclistCtx {
122687  Fts3Cursor *pCsr;               /* FTS3 Cursor */
122688  int nPhrase;                    /* Number of phrases seen so far */
122689  int nToken;                     /* Number of tokens seen so far */
122690};
122691
122692/*
122693** The following types are used as part of the implementation of the
122694** fts3BestSnippet() routine.
122695*/
122696typedef struct SnippetIter SnippetIter;
122697typedef struct SnippetPhrase SnippetPhrase;
122698typedef struct SnippetFragment SnippetFragment;
122699
122700struct SnippetIter {
122701  Fts3Cursor *pCsr;               /* Cursor snippet is being generated from */
122702  int iCol;                       /* Extract snippet from this column */
122703  int nSnippet;                   /* Requested snippet length (in tokens) */
122704  int nPhrase;                    /* Number of phrases in query */
122705  SnippetPhrase *aPhrase;         /* Array of size nPhrase */
122706  int iCurrent;                   /* First token of current snippet */
122707};
122708
122709struct SnippetPhrase {
122710  int nToken;                     /* Number of tokens in phrase */
122711  char *pList;                    /* Pointer to start of phrase position list */
122712  int iHead;                      /* Next value in position list */
122713  char *pHead;                    /* Position list data following iHead */
122714  int iTail;                      /* Next value in trailing position list */
122715  char *pTail;                    /* Position list data following iTail */
122716};
122717
122718struct SnippetFragment {
122719  int iCol;                       /* Column snippet is extracted from */
122720  int iPos;                       /* Index of first token in snippet */
122721  u64 covered;                    /* Mask of query phrases covered */
122722  u64 hlmask;                     /* Mask of snippet terms to highlight */
122723};
122724
122725/*
122726** This type is used as an fts3ExprIterate() context object while
122727** accumulating the data returned by the matchinfo() function.
122728*/
122729typedef struct MatchInfo MatchInfo;
122730struct MatchInfo {
122731  Fts3Cursor *pCursor;            /* FTS3 Cursor */
122732  int nCol;                       /* Number of columns in table */
122733  int nPhrase;                    /* Number of matchable phrases in query */
122734  sqlite3_int64 nDoc;             /* Number of docs in database */
122735  u32 *aMatchinfo;                /* Pre-allocated buffer */
122736};
122737
122738
122739
122740/*
122741** The snippet() and offsets() functions both return text values. An instance
122742** of the following structure is used to accumulate those values while the
122743** functions are running. See fts3StringAppend() for details.
122744*/
122745typedef struct StrBuffer StrBuffer;
122746struct StrBuffer {
122747  char *z;                        /* Pointer to buffer containing string */
122748  int n;                          /* Length of z in bytes (excl. nul-term) */
122749  int nAlloc;                     /* Allocated size of buffer z in bytes */
122750};
122751
122752
122753/*
122754** This function is used to help iterate through a position-list. A position
122755** list is a list of unique integers, sorted from smallest to largest. Each
122756** element of the list is represented by an FTS3 varint that takes the value
122757** of the difference between the current element and the previous one plus
122758** two. For example, to store the position-list:
122759**
122760**     4 9 113
122761**
122762** the three varints:
122763**
122764**     6 7 106
122765**
122766** are encoded.
122767**
122768** When this function is called, *pp points to the start of an element of
122769** the list. *piPos contains the value of the previous entry in the list.
122770** After it returns, *piPos contains the value of the next element of the
122771** list and *pp is advanced to the following varint.
122772*/
122773static void fts3GetDeltaPosition(char **pp, int *piPos){
122774  int iVal;
122775  *pp += sqlite3Fts3GetVarint32(*pp, &iVal);
122776  *piPos += (iVal-2);
122777}
122778
122779/*
122780** Helper function for fts3ExprIterate() (see below).
122781*/
122782static int fts3ExprIterate2(
122783  Fts3Expr *pExpr,                /* Expression to iterate phrases of */
122784  int *piPhrase,                  /* Pointer to phrase counter */
122785  int (*x)(Fts3Expr*,int,void*),  /* Callback function to invoke for phrases */
122786  void *pCtx                      /* Second argument to pass to callback */
122787){
122788  int rc;                         /* Return code */
122789  int eType = pExpr->eType;       /* Type of expression node pExpr */
122790
122791  if( eType!=FTSQUERY_PHRASE ){
122792    assert( pExpr->pLeft && pExpr->pRight );
122793    rc = fts3ExprIterate2(pExpr->pLeft, piPhrase, x, pCtx);
122794    if( rc==SQLITE_OK && eType!=FTSQUERY_NOT ){
122795      rc = fts3ExprIterate2(pExpr->pRight, piPhrase, x, pCtx);
122796    }
122797  }else{
122798    rc = x(pExpr, *piPhrase, pCtx);
122799    (*piPhrase)++;
122800  }
122801  return rc;
122802}
122803
122804/*
122805** Iterate through all phrase nodes in an FTS3 query, except those that
122806** are part of a sub-tree that is the right-hand-side of a NOT operator.
122807** For each phrase node found, the supplied callback function is invoked.
122808**
122809** If the callback function returns anything other than SQLITE_OK,
122810** the iteration is abandoned and the error code returned immediately.
122811** Otherwise, SQLITE_OK is returned after a callback has been made for
122812** all eligible phrase nodes.
122813*/
122814static int fts3ExprIterate(
122815  Fts3Expr *pExpr,                /* Expression to iterate phrases of */
122816  int (*x)(Fts3Expr*,int,void*),  /* Callback function to invoke for phrases */
122817  void *pCtx                      /* Second argument to pass to callback */
122818){
122819  int iPhrase = 0;                /* Variable used as the phrase counter */
122820  return fts3ExprIterate2(pExpr, &iPhrase, x, pCtx);
122821}
122822
122823/*
122824** The argument to this function is always a phrase node. Its doclist
122825** (Fts3Expr.aDoclist[]) and the doclists associated with all phrase nodes
122826** to the left of this one in the query tree have already been loaded.
122827**
122828** If this phrase node is part of a series of phrase nodes joined by
122829** NEAR operators (and is not the left-most of said series), then elements are
122830** removed from the phrases doclist consistent with the NEAR restriction. If
122831** required, elements may be removed from the doclists of phrases to the
122832** left of this one that are part of the same series of NEAR operator
122833** connected phrases.
122834**
122835** If an OOM error occurs, SQLITE_NOMEM is returned. Otherwise, SQLITE_OK.
122836*/
122837static int fts3ExprNearTrim(Fts3Expr *pExpr){
122838  int rc = SQLITE_OK;
122839  Fts3Expr *pParent = pExpr->pParent;
122840
122841  assert( pExpr->eType==FTSQUERY_PHRASE );
122842  while( rc==SQLITE_OK
122843   && pParent
122844   && pParent->eType==FTSQUERY_NEAR
122845   && pParent->pRight==pExpr
122846  ){
122847    /* This expression (pExpr) is the right-hand-side of a NEAR operator.
122848    ** Find the expression to the left of the same operator.
122849    */
122850    int nNear = pParent->nNear;
122851    Fts3Expr *pLeft = pParent->pLeft;
122852
122853    if( pLeft->eType!=FTSQUERY_PHRASE ){
122854      assert( pLeft->eType==FTSQUERY_NEAR );
122855      assert( pLeft->pRight->eType==FTSQUERY_PHRASE );
122856      pLeft = pLeft->pRight;
122857    }
122858
122859    rc = sqlite3Fts3ExprNearTrim(pLeft, pExpr, nNear);
122860
122861    pExpr = pLeft;
122862    pParent = pExpr->pParent;
122863  }
122864
122865  return rc;
122866}
122867
122868/*
122869** This is an fts3ExprIterate() callback used while loading the doclists
122870** for each phrase into Fts3Expr.aDoclist[]/nDoclist. See also
122871** fts3ExprLoadDoclists().
122872*/
122873static int fts3ExprLoadDoclistsCb(Fts3Expr *pExpr, int iPhrase, void *ctx){
122874  int rc = SQLITE_OK;
122875  LoadDoclistCtx *p = (LoadDoclistCtx *)ctx;
122876
122877  UNUSED_PARAMETER(iPhrase);
122878
122879  p->nPhrase++;
122880  p->nToken += pExpr->pPhrase->nToken;
122881
122882  if( pExpr->isLoaded==0 ){
122883    rc = sqlite3Fts3ExprLoadDoclist(p->pCsr, pExpr);
122884    pExpr->isLoaded = 1;
122885    if( rc==SQLITE_OK ){
122886      rc = fts3ExprNearTrim(pExpr);
122887    }
122888  }
122889
122890  return rc;
122891}
122892
122893/*
122894** Load the doclists for each phrase in the query associated with FTS3 cursor
122895** pCsr.
122896**
122897** If pnPhrase is not NULL, then *pnPhrase is set to the number of matchable
122898** phrases in the expression (all phrases except those directly or
122899** indirectly descended from the right-hand-side of a NOT operator). If
122900** pnToken is not NULL, then it is set to the number of tokens in all
122901** matchable phrases of the expression.
122902*/
122903static int fts3ExprLoadDoclists(
122904  Fts3Cursor *pCsr,               /* Fts3 cursor for current query */
122905  int *pnPhrase,                  /* OUT: Number of phrases in query */
122906  int *pnToken                    /* OUT: Number of tokens in query */
122907){
122908  int rc;                         /* Return Code */
122909  LoadDoclistCtx sCtx = {0,0,0};  /* Context for fts3ExprIterate() */
122910  sCtx.pCsr = pCsr;
122911  rc = fts3ExprIterate(pCsr->pExpr, fts3ExprLoadDoclistsCb, (void *)&sCtx);
122912  if( pnPhrase ) *pnPhrase = sCtx.nPhrase;
122913  if( pnToken ) *pnToken = sCtx.nToken;
122914  return rc;
122915}
122916
122917static int fts3ExprPhraseCountCb(Fts3Expr *pExpr, int iPhrase, void *ctx){
122918  (*(int *)ctx)++;
122919  UNUSED_PARAMETER(pExpr);
122920  UNUSED_PARAMETER(iPhrase);
122921  return SQLITE_OK;
122922}
122923static int fts3ExprPhraseCount(Fts3Expr *pExpr){
122924  int nPhrase = 0;
122925  (void)fts3ExprIterate(pExpr, fts3ExprPhraseCountCb, (void *)&nPhrase);
122926  return nPhrase;
122927}
122928
122929/*
122930** Advance the position list iterator specified by the first two
122931** arguments so that it points to the first element with a value greater
122932** than or equal to parameter iNext.
122933*/
122934static void fts3SnippetAdvance(char **ppIter, int *piIter, int iNext){
122935  char *pIter = *ppIter;
122936  if( pIter ){
122937    int iIter = *piIter;
122938
122939    while( iIter<iNext ){
122940      if( 0==(*pIter & 0xFE) ){
122941        iIter = -1;
122942        pIter = 0;
122943        break;
122944      }
122945      fts3GetDeltaPosition(&pIter, &iIter);
122946    }
122947
122948    *piIter = iIter;
122949    *ppIter = pIter;
122950  }
122951}
122952
122953/*
122954** Advance the snippet iterator to the next candidate snippet.
122955*/
122956static int fts3SnippetNextCandidate(SnippetIter *pIter){
122957  int i;                          /* Loop counter */
122958
122959  if( pIter->iCurrent<0 ){
122960    /* The SnippetIter object has just been initialized. The first snippet
122961    ** candidate always starts at offset 0 (even if this candidate has a
122962    ** score of 0.0).
122963    */
122964    pIter->iCurrent = 0;
122965
122966    /* Advance the 'head' iterator of each phrase to the first offset that
122967    ** is greater than or equal to (iNext+nSnippet).
122968    */
122969    for(i=0; i<pIter->nPhrase; i++){
122970      SnippetPhrase *pPhrase = &pIter->aPhrase[i];
122971      fts3SnippetAdvance(&pPhrase->pHead, &pPhrase->iHead, pIter->nSnippet);
122972    }
122973  }else{
122974    int iStart;
122975    int iEnd = 0x7FFFFFFF;
122976
122977    for(i=0; i<pIter->nPhrase; i++){
122978      SnippetPhrase *pPhrase = &pIter->aPhrase[i];
122979      if( pPhrase->pHead && pPhrase->iHead<iEnd ){
122980        iEnd = pPhrase->iHead;
122981      }
122982    }
122983    if( iEnd==0x7FFFFFFF ){
122984      return 1;
122985    }
122986
122987    pIter->iCurrent = iStart = iEnd - pIter->nSnippet + 1;
122988    for(i=0; i<pIter->nPhrase; i++){
122989      SnippetPhrase *pPhrase = &pIter->aPhrase[i];
122990      fts3SnippetAdvance(&pPhrase->pHead, &pPhrase->iHead, iEnd+1);
122991      fts3SnippetAdvance(&pPhrase->pTail, &pPhrase->iTail, iStart);
122992    }
122993  }
122994
122995  return 0;
122996}
122997
122998/*
122999** Retrieve information about the current candidate snippet of snippet
123000** iterator pIter.
123001*/
123002static void fts3SnippetDetails(
123003  SnippetIter *pIter,             /* Snippet iterator */
123004  u64 mCovered,                   /* Bitmask of phrases already covered */
123005  int *piToken,                   /* OUT: First token of proposed snippet */
123006  int *piScore,                   /* OUT: "Score" for this snippet */
123007  u64 *pmCover,                   /* OUT: Bitmask of phrases covered */
123008  u64 *pmHighlight                /* OUT: Bitmask of terms to highlight */
123009){
123010  int iStart = pIter->iCurrent;   /* First token of snippet */
123011  int iScore = 0;                 /* Score of this snippet */
123012  int i;                          /* Loop counter */
123013  u64 mCover = 0;                 /* Mask of phrases covered by this snippet */
123014  u64 mHighlight = 0;             /* Mask of tokens to highlight in snippet */
123015
123016  for(i=0; i<pIter->nPhrase; i++){
123017    SnippetPhrase *pPhrase = &pIter->aPhrase[i];
123018    if( pPhrase->pTail ){
123019      char *pCsr = pPhrase->pTail;
123020      int iCsr = pPhrase->iTail;
123021
123022      while( iCsr<(iStart+pIter->nSnippet) ){
123023        int j;
123024        u64 mPhrase = (u64)1 << i;
123025        u64 mPos = (u64)1 << (iCsr - iStart);
123026        assert( iCsr>=iStart );
123027        if( (mCover|mCovered)&mPhrase ){
123028          iScore++;
123029        }else{
123030          iScore += 1000;
123031        }
123032        mCover |= mPhrase;
123033
123034        for(j=0; j<pPhrase->nToken; j++){
123035          mHighlight |= (mPos>>j);
123036        }
123037
123038        if( 0==(*pCsr & 0x0FE) ) break;
123039        fts3GetDeltaPosition(&pCsr, &iCsr);
123040      }
123041    }
123042  }
123043
123044  /* Set the output variables before returning. */
123045  *piToken = iStart;
123046  *piScore = iScore;
123047  *pmCover = mCover;
123048  *pmHighlight = mHighlight;
123049}
123050
123051/*
123052** This function is an fts3ExprIterate() callback used by fts3BestSnippet().
123053** Each invocation populates an element of the SnippetIter.aPhrase[] array.
123054*/
123055static int fts3SnippetFindPositions(Fts3Expr *pExpr, int iPhrase, void *ctx){
123056  SnippetIter *p = (SnippetIter *)ctx;
123057  SnippetPhrase *pPhrase = &p->aPhrase[iPhrase];
123058  char *pCsr;
123059
123060  pPhrase->nToken = pExpr->pPhrase->nToken;
123061
123062  pCsr = sqlite3Fts3FindPositions(pExpr, p->pCsr->iPrevId, p->iCol);
123063  if( pCsr ){
123064    int iFirst = 0;
123065    pPhrase->pList = pCsr;
123066    fts3GetDeltaPosition(&pCsr, &iFirst);
123067    pPhrase->pHead = pCsr;
123068    pPhrase->pTail = pCsr;
123069    pPhrase->iHead = iFirst;
123070    pPhrase->iTail = iFirst;
123071  }else{
123072    assert( pPhrase->pList==0 && pPhrase->pHead==0 && pPhrase->pTail==0 );
123073  }
123074
123075  return SQLITE_OK;
123076}
123077
123078/*
123079** Select the fragment of text consisting of nFragment contiguous tokens
123080** from column iCol that represent the "best" snippet. The best snippet
123081** is the snippet with the highest score, where scores are calculated
123082** by adding:
123083**
123084**   (a) +1 point for each occurence of a matchable phrase in the snippet.
123085**
123086**   (b) +1000 points for the first occurence of each matchable phrase in
123087**       the snippet for which the corresponding mCovered bit is not set.
123088**
123089** The selected snippet parameters are stored in structure *pFragment before
123090** returning. The score of the selected snippet is stored in *piScore
123091** before returning.
123092*/
123093static int fts3BestSnippet(
123094  int nSnippet,                   /* Desired snippet length */
123095  Fts3Cursor *pCsr,               /* Cursor to create snippet for */
123096  int iCol,                       /* Index of column to create snippet from */
123097  u64 mCovered,                   /* Mask of phrases already covered */
123098  u64 *pmSeen,                    /* IN/OUT: Mask of phrases seen */
123099  SnippetFragment *pFragment,     /* OUT: Best snippet found */
123100  int *piScore                    /* OUT: Score of snippet pFragment */
123101){
123102  int rc;                         /* Return Code */
123103  int nList;                      /* Number of phrases in expression */
123104  SnippetIter sIter;              /* Iterates through snippet candidates */
123105  int nByte;                      /* Number of bytes of space to allocate */
123106  int iBestScore = -1;            /* Best snippet score found so far */
123107  int i;                          /* Loop counter */
123108
123109  memset(&sIter, 0, sizeof(sIter));
123110
123111  /* Iterate through the phrases in the expression to count them. The same
123112  ** callback makes sure the doclists are loaded for each phrase.
123113  */
123114  rc = fts3ExprLoadDoclists(pCsr, &nList, 0);
123115  if( rc!=SQLITE_OK ){
123116    return rc;
123117  }
123118
123119  /* Now that it is known how many phrases there are, allocate and zero
123120  ** the required space using malloc().
123121  */
123122  nByte = sizeof(SnippetPhrase) * nList;
123123  sIter.aPhrase = (SnippetPhrase *)sqlite3_malloc(nByte);
123124  if( !sIter.aPhrase ){
123125    return SQLITE_NOMEM;
123126  }
123127  memset(sIter.aPhrase, 0, nByte);
123128
123129  /* Initialize the contents of the SnippetIter object. Then iterate through
123130  ** the set of phrases in the expression to populate the aPhrase[] array.
123131  */
123132  sIter.pCsr = pCsr;
123133  sIter.iCol = iCol;
123134  sIter.nSnippet = nSnippet;
123135  sIter.nPhrase = nList;
123136  sIter.iCurrent = -1;
123137  (void)fts3ExprIterate(pCsr->pExpr, fts3SnippetFindPositions, (void *)&sIter);
123138
123139  /* Set the *pmSeen output variable. */
123140  for(i=0; i<nList; i++){
123141    if( sIter.aPhrase[i].pHead ){
123142      *pmSeen |= (u64)1 << i;
123143    }
123144  }
123145
123146  /* Loop through all candidate snippets. Store the best snippet in
123147  ** *pFragment. Store its associated 'score' in iBestScore.
123148  */
123149  pFragment->iCol = iCol;
123150  while( !fts3SnippetNextCandidate(&sIter) ){
123151    int iPos;
123152    int iScore;
123153    u64 mCover;
123154    u64 mHighlight;
123155    fts3SnippetDetails(&sIter, mCovered, &iPos, &iScore, &mCover, &mHighlight);
123156    assert( iScore>=0 );
123157    if( iScore>iBestScore ){
123158      pFragment->iPos = iPos;
123159      pFragment->hlmask = mHighlight;
123160      pFragment->covered = mCover;
123161      iBestScore = iScore;
123162    }
123163  }
123164
123165  sqlite3_free(sIter.aPhrase);
123166  *piScore = iBestScore;
123167  return SQLITE_OK;
123168}
123169
123170
123171/*
123172** Append a string to the string-buffer passed as the first argument.
123173**
123174** If nAppend is negative, then the length of the string zAppend is
123175** determined using strlen().
123176*/
123177static int fts3StringAppend(
123178  StrBuffer *pStr,                /* Buffer to append to */
123179  const char *zAppend,            /* Pointer to data to append to buffer */
123180  int nAppend                     /* Size of zAppend in bytes (or -1) */
123181){
123182  if( nAppend<0 ){
123183    nAppend = (int)strlen(zAppend);
123184  }
123185
123186  /* If there is insufficient space allocated at StrBuffer.z, use realloc()
123187  ** to grow the buffer until so that it is big enough to accomadate the
123188  ** appended data.
123189  */
123190  if( pStr->n+nAppend+1>=pStr->nAlloc ){
123191    int nAlloc = pStr->nAlloc+nAppend+100;
123192    char *zNew = sqlite3_realloc(pStr->z, nAlloc);
123193    if( !zNew ){
123194      return SQLITE_NOMEM;
123195    }
123196    pStr->z = zNew;
123197    pStr->nAlloc = nAlloc;
123198  }
123199
123200  /* Append the data to the string buffer. */
123201  memcpy(&pStr->z[pStr->n], zAppend, nAppend);
123202  pStr->n += nAppend;
123203  pStr->z[pStr->n] = '\0';
123204
123205  return SQLITE_OK;
123206}
123207
123208/*
123209** The fts3BestSnippet() function often selects snippets that end with a
123210** query term. That is, the final term of the snippet is always a term
123211** that requires highlighting. For example, if 'X' is a highlighted term
123212** and '.' is a non-highlighted term, BestSnippet() may select:
123213**
123214**     ........X.....X
123215**
123216** This function "shifts" the beginning of the snippet forward in the
123217** document so that there are approximately the same number of
123218** non-highlighted terms to the right of the final highlighted term as there
123219** are to the left of the first highlighted term. For example, to this:
123220**
123221**     ....X.....X....
123222**
123223** This is done as part of extracting the snippet text, not when selecting
123224** the snippet. Snippet selection is done based on doclists only, so there
123225** is no way for fts3BestSnippet() to know whether or not the document
123226** actually contains terms that follow the final highlighted term.
123227*/
123228static int fts3SnippetShift(
123229  Fts3Table *pTab,                /* FTS3 table snippet comes from */
123230  int nSnippet,                   /* Number of tokens desired for snippet */
123231  const char *zDoc,               /* Document text to extract snippet from */
123232  int nDoc,                       /* Size of buffer zDoc in bytes */
123233  int *piPos,                     /* IN/OUT: First token of snippet */
123234  u64 *pHlmask                    /* IN/OUT: Mask of tokens to highlight */
123235){
123236  u64 hlmask = *pHlmask;          /* Local copy of initial highlight-mask */
123237
123238  if( hlmask ){
123239    int nLeft;                    /* Tokens to the left of first highlight */
123240    int nRight;                   /* Tokens to the right of last highlight */
123241    int nDesired;                 /* Ideal number of tokens to shift forward */
123242
123243    for(nLeft=0; !(hlmask & ((u64)1 << nLeft)); nLeft++);
123244    for(nRight=0; !(hlmask & ((u64)1 << (nSnippet-1-nRight))); nRight++);
123245    nDesired = (nLeft-nRight)/2;
123246
123247    /* Ideally, the start of the snippet should be pushed forward in the
123248    ** document nDesired tokens. This block checks if there are actually
123249    ** nDesired tokens to the right of the snippet. If so, *piPos and
123250    ** *pHlMask are updated to shift the snippet nDesired tokens to the
123251    ** right. Otherwise, the snippet is shifted by the number of tokens
123252    ** available.
123253    */
123254    if( nDesired>0 ){
123255      int nShift;                 /* Number of tokens to shift snippet by */
123256      int iCurrent = 0;           /* Token counter */
123257      int rc;                     /* Return Code */
123258      sqlite3_tokenizer_module *pMod;
123259      sqlite3_tokenizer_cursor *pC;
123260      pMod = (sqlite3_tokenizer_module *)pTab->pTokenizer->pModule;
123261
123262      /* Open a cursor on zDoc/nDoc. Check if there are (nSnippet+nDesired)
123263      ** or more tokens in zDoc/nDoc.
123264      */
123265      rc = pMod->xOpen(pTab->pTokenizer, zDoc, nDoc, &pC);
123266      if( rc!=SQLITE_OK ){
123267        return rc;
123268      }
123269      pC->pTokenizer = pTab->pTokenizer;
123270      while( rc==SQLITE_OK && iCurrent<(nSnippet+nDesired) ){
123271        const char *ZDUMMY; int DUMMY1, DUMMY2, DUMMY3;
123272        rc = pMod->xNext(pC, &ZDUMMY, &DUMMY1, &DUMMY2, &DUMMY3, &iCurrent);
123273      }
123274      pMod->xClose(pC);
123275      if( rc!=SQLITE_OK && rc!=SQLITE_DONE ){ return rc; }
123276
123277      nShift = (rc==SQLITE_DONE)+iCurrent-nSnippet;
123278      assert( nShift<=nDesired );
123279      if( nShift>0 ){
123280        *piPos += nShift;
123281        *pHlmask = hlmask >> nShift;
123282      }
123283    }
123284  }
123285  return SQLITE_OK;
123286}
123287
123288/*
123289** Extract the snippet text for fragment pFragment from cursor pCsr and
123290** append it to string buffer pOut.
123291*/
123292static int fts3SnippetText(
123293  Fts3Cursor *pCsr,               /* FTS3 Cursor */
123294  SnippetFragment *pFragment,     /* Snippet to extract */
123295  int iFragment,                  /* Fragment number */
123296  int isLast,                     /* True for final fragment in snippet */
123297  int nSnippet,                   /* Number of tokens in extracted snippet */
123298  const char *zOpen,              /* String inserted before highlighted term */
123299  const char *zClose,             /* String inserted after highlighted term */
123300  const char *zEllipsis,          /* String inserted between snippets */
123301  StrBuffer *pOut                 /* Write output here */
123302){
123303  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
123304  int rc;                         /* Return code */
123305  const char *zDoc;               /* Document text to extract snippet from */
123306  int nDoc;                       /* Size of zDoc in bytes */
123307  int iCurrent = 0;               /* Current token number of document */
123308  int iEnd = 0;                   /* Byte offset of end of current token */
123309  int isShiftDone = 0;            /* True after snippet is shifted */
123310  int iPos = pFragment->iPos;     /* First token of snippet */
123311  u64 hlmask = pFragment->hlmask; /* Highlight-mask for snippet */
123312  int iCol = pFragment->iCol+1;   /* Query column to extract text from */
123313  sqlite3_tokenizer_module *pMod; /* Tokenizer module methods object */
123314  sqlite3_tokenizer_cursor *pC;   /* Tokenizer cursor open on zDoc/nDoc */
123315  const char *ZDUMMY;             /* Dummy argument used with tokenizer */
123316  int DUMMY1;                     /* Dummy argument used with tokenizer */
123317
123318  zDoc = (const char *)sqlite3_column_text(pCsr->pStmt, iCol);
123319  if( zDoc==0 ){
123320    if( sqlite3_column_type(pCsr->pStmt, iCol)!=SQLITE_NULL ){
123321      return SQLITE_NOMEM;
123322    }
123323    return SQLITE_OK;
123324  }
123325  nDoc = sqlite3_column_bytes(pCsr->pStmt, iCol);
123326
123327  /* Open a token cursor on the document. */
123328  pMod = (sqlite3_tokenizer_module *)pTab->pTokenizer->pModule;
123329  rc = pMod->xOpen(pTab->pTokenizer, zDoc, nDoc, &pC);
123330  if( rc!=SQLITE_OK ){
123331    return rc;
123332  }
123333  pC->pTokenizer = pTab->pTokenizer;
123334
123335  while( rc==SQLITE_OK ){
123336    int iBegin;                   /* Offset in zDoc of start of token */
123337    int iFin;                     /* Offset in zDoc of end of token */
123338    int isHighlight;              /* True for highlighted terms */
123339
123340    rc = pMod->xNext(pC, &ZDUMMY, &DUMMY1, &iBegin, &iFin, &iCurrent);
123341    if( rc!=SQLITE_OK ){
123342      if( rc==SQLITE_DONE ){
123343        /* Special case - the last token of the snippet is also the last token
123344        ** of the column. Append any punctuation that occurred between the end
123345        ** of the previous token and the end of the document to the output.
123346        ** Then break out of the loop. */
123347        rc = fts3StringAppend(pOut, &zDoc[iEnd], -1);
123348      }
123349      break;
123350    }
123351    if( iCurrent<iPos ){ continue; }
123352
123353    if( !isShiftDone ){
123354      int n = nDoc - iBegin;
123355      rc = fts3SnippetShift(pTab, nSnippet, &zDoc[iBegin], n, &iPos, &hlmask);
123356      isShiftDone = 1;
123357
123358      /* Now that the shift has been done, check if the initial "..." are
123359      ** required. They are required if (a) this is not the first fragment,
123360      ** or (b) this fragment does not begin at position 0 of its column.
123361      */
123362      if( rc==SQLITE_OK && (iPos>0 || iFragment>0) ){
123363        rc = fts3StringAppend(pOut, zEllipsis, -1);
123364      }
123365      if( rc!=SQLITE_OK || iCurrent<iPos ) continue;
123366    }
123367
123368    if( iCurrent>=(iPos+nSnippet) ){
123369      if( isLast ){
123370        rc = fts3StringAppend(pOut, zEllipsis, -1);
123371      }
123372      break;
123373    }
123374
123375    /* Set isHighlight to true if this term should be highlighted. */
123376    isHighlight = (hlmask & ((u64)1 << (iCurrent-iPos)))!=0;
123377
123378    if( iCurrent>iPos ) rc = fts3StringAppend(pOut, &zDoc[iEnd], iBegin-iEnd);
123379    if( rc==SQLITE_OK && isHighlight ) rc = fts3StringAppend(pOut, zOpen, -1);
123380    if( rc==SQLITE_OK ) rc = fts3StringAppend(pOut, &zDoc[iBegin], iFin-iBegin);
123381    if( rc==SQLITE_OK && isHighlight ) rc = fts3StringAppend(pOut, zClose, -1);
123382
123383    iEnd = iFin;
123384  }
123385
123386  pMod->xClose(pC);
123387  return rc;
123388}
123389
123390
123391/*
123392** This function is used to count the entries in a column-list (a
123393** delta-encoded list of term offsets within a single column of a single
123394** row). When this function is called, *ppCollist should point to the
123395** beginning of the first varint in the column-list (the varint that
123396** contains the position of the first matching term in the column data).
123397** Before returning, *ppCollist is set to point to the first byte after
123398** the last varint in the column-list (either the 0x00 signifying the end
123399** of the position-list, or the 0x01 that precedes the column number of
123400** the next column in the position-list).
123401**
123402** The number of elements in the column-list is returned.
123403*/
123404static int fts3ColumnlistCount(char **ppCollist){
123405  char *pEnd = *ppCollist;
123406  char c = 0;
123407  int nEntry = 0;
123408
123409  /* A column-list is terminated by either a 0x01 or 0x00. */
123410  while( 0xFE & (*pEnd | c) ){
123411    c = *pEnd++ & 0x80;
123412    if( !c ) nEntry++;
123413  }
123414
123415  *ppCollist = pEnd;
123416  return nEntry;
123417}
123418
123419static void fts3LoadColumnlistCounts(char **pp, u32 *aOut, int isGlobal){
123420  char *pCsr = *pp;
123421  while( *pCsr ){
123422    int nHit;
123423    sqlite3_int64 iCol = 0;
123424    if( *pCsr==0x01 ){
123425      pCsr++;
123426      pCsr += sqlite3Fts3GetVarint(pCsr, &iCol);
123427    }
123428    nHit = fts3ColumnlistCount(&pCsr);
123429    assert( nHit>0 );
123430    if( isGlobal ){
123431      aOut[iCol*3+1]++;
123432    }
123433    aOut[iCol*3] += nHit;
123434  }
123435  pCsr++;
123436  *pp = pCsr;
123437}
123438
123439/*
123440** fts3ExprIterate() callback used to collect the "global" matchinfo stats
123441** for a single query.
123442**
123443** fts3ExprIterate() callback to load the 'global' elements of a
123444** FTS3_MATCHINFO_HITS matchinfo array. The global stats are those elements
123445** of the matchinfo array that are constant for all rows returned by the
123446** current query.
123447**
123448** Argument pCtx is actually a pointer to a struct of type MatchInfo. This
123449** function populates Matchinfo.aMatchinfo[] as follows:
123450**
123451**   for(iCol=0; iCol<nCol; iCol++){
123452**     aMatchinfo[3*iPhrase*nCol + 3*iCol + 1] = X;
123453**     aMatchinfo[3*iPhrase*nCol + 3*iCol + 2] = Y;
123454**   }
123455**
123456** where X is the number of matches for phrase iPhrase is column iCol of all
123457** rows of the table. Y is the number of rows for which column iCol contains
123458** at least one instance of phrase iPhrase.
123459**
123460** If the phrase pExpr consists entirely of deferred tokens, then all X and
123461** Y values are set to nDoc, where nDoc is the number of documents in the
123462** file system. This is done because the full-text index doclist is required
123463** to calculate these values properly, and the full-text index doclist is
123464** not available for deferred tokens.
123465*/
123466static int fts3ExprGlobalHitsCb(
123467  Fts3Expr *pExpr,                /* Phrase expression node */
123468  int iPhrase,                    /* Phrase number (numbered from zero) */
123469  void *pCtx                      /* Pointer to MatchInfo structure */
123470){
123471  MatchInfo *p = (MatchInfo *)pCtx;
123472  Fts3Cursor *pCsr = p->pCursor;
123473  char *pIter;
123474  char *pEnd;
123475  char *pFree = 0;
123476  u32 *aOut = &p->aMatchinfo[3*iPhrase*p->nCol];
123477
123478  assert( pExpr->isLoaded );
123479  assert( pExpr->eType==FTSQUERY_PHRASE );
123480
123481  if( pCsr->pDeferred ){
123482    Fts3Phrase *pPhrase = pExpr->pPhrase;
123483    int ii;
123484    for(ii=0; ii<pPhrase->nToken; ii++){
123485      if( pPhrase->aToken[ii].bFulltext ) break;
123486    }
123487    if( ii<pPhrase->nToken ){
123488      int nFree = 0;
123489      int rc = sqlite3Fts3ExprLoadFtDoclist(pCsr, pExpr, &pFree, &nFree);
123490      if( rc!=SQLITE_OK ) return rc;
123491      pIter = pFree;
123492      pEnd = &pFree[nFree];
123493    }else{
123494      int iCol;                   /* Column index */
123495      for(iCol=0; iCol<p->nCol; iCol++){
123496        aOut[iCol*3 + 1] = (u32)p->nDoc;
123497        aOut[iCol*3 + 2] = (u32)p->nDoc;
123498      }
123499      return SQLITE_OK;
123500    }
123501  }else{
123502    pIter = pExpr->aDoclist;
123503    pEnd = &pExpr->aDoclist[pExpr->nDoclist];
123504  }
123505
123506  /* Fill in the global hit count matrix row for this phrase. */
123507  while( pIter<pEnd ){
123508    while( *pIter++ & 0x80 );      /* Skip past docid. */
123509    fts3LoadColumnlistCounts(&pIter, &aOut[1], 1);
123510  }
123511
123512  sqlite3_free(pFree);
123513  return SQLITE_OK;
123514}
123515
123516/*
123517** fts3ExprIterate() callback used to collect the "local" part of the
123518** FTS3_MATCHINFO_HITS array. The local stats are those elements of the
123519** array that are different for each row returned by the query.
123520*/
123521static int fts3ExprLocalHitsCb(
123522  Fts3Expr *pExpr,                /* Phrase expression node */
123523  int iPhrase,                    /* Phrase number */
123524  void *pCtx                      /* Pointer to MatchInfo structure */
123525){
123526  MatchInfo *p = (MatchInfo *)pCtx;
123527  int iStart = iPhrase * p->nCol * 3;
123528  int i;
123529
123530  for(i=0; i<p->nCol; i++) p->aMatchinfo[iStart+i*3] = 0;
123531
123532  if( pExpr->aDoclist ){
123533    char *pCsr;
123534
123535    pCsr = sqlite3Fts3FindPositions(pExpr, p->pCursor->iPrevId, -1);
123536    if( pCsr ){
123537      fts3LoadColumnlistCounts(&pCsr, &p->aMatchinfo[iStart], 0);
123538    }
123539  }
123540
123541  return SQLITE_OK;
123542}
123543
123544static int fts3MatchinfoCheck(
123545  Fts3Table *pTab,
123546  char cArg,
123547  char **pzErr
123548){
123549  if( (cArg==FTS3_MATCHINFO_NPHRASE)
123550   || (cArg==FTS3_MATCHINFO_NCOL)
123551   || (cArg==FTS3_MATCHINFO_NDOC && pTab->bHasStat)
123552   || (cArg==FTS3_MATCHINFO_AVGLENGTH && pTab->bHasStat)
123553   || (cArg==FTS3_MATCHINFO_LENGTH && pTab->bHasDocsize)
123554   || (cArg==FTS3_MATCHINFO_LCS)
123555   || (cArg==FTS3_MATCHINFO_HITS)
123556  ){
123557    return SQLITE_OK;
123558  }
123559  *pzErr = sqlite3_mprintf("unrecognized matchinfo request: %c", cArg);
123560  return SQLITE_ERROR;
123561}
123562
123563static int fts3MatchinfoSize(MatchInfo *pInfo, char cArg){
123564  int nVal;                       /* Number of integers output by cArg */
123565
123566  switch( cArg ){
123567    case FTS3_MATCHINFO_NDOC:
123568    case FTS3_MATCHINFO_NPHRASE:
123569    case FTS3_MATCHINFO_NCOL:
123570      nVal = 1;
123571      break;
123572
123573    case FTS3_MATCHINFO_AVGLENGTH:
123574    case FTS3_MATCHINFO_LENGTH:
123575    case FTS3_MATCHINFO_LCS:
123576      nVal = pInfo->nCol;
123577      break;
123578
123579    default:
123580      assert( cArg==FTS3_MATCHINFO_HITS );
123581      nVal = pInfo->nCol * pInfo->nPhrase * 3;
123582      break;
123583  }
123584
123585  return nVal;
123586}
123587
123588static int fts3MatchinfoSelectDoctotal(
123589  Fts3Table *pTab,
123590  sqlite3_stmt **ppStmt,
123591  sqlite3_int64 *pnDoc,
123592  const char **paLen
123593){
123594  sqlite3_stmt *pStmt;
123595  const char *a;
123596  sqlite3_int64 nDoc;
123597
123598  if( !*ppStmt ){
123599    int rc = sqlite3Fts3SelectDoctotal(pTab, ppStmt);
123600    if( rc!=SQLITE_OK ) return rc;
123601  }
123602  pStmt = *ppStmt;
123603  assert( sqlite3_data_count(pStmt)==1 );
123604
123605  a = sqlite3_column_blob(pStmt, 0);
123606  a += sqlite3Fts3GetVarint(a, &nDoc);
123607  if( nDoc==0 ) return SQLITE_CORRUPT;
123608  *pnDoc = (u32)nDoc;
123609
123610  if( paLen ) *paLen = a;
123611  return SQLITE_OK;
123612}
123613
123614/*
123615** An instance of the following structure is used to store state while
123616** iterating through a multi-column position-list corresponding to the
123617** hits for a single phrase on a single row in order to calculate the
123618** values for a matchinfo() FTS3_MATCHINFO_LCS request.
123619*/
123620typedef struct LcsIterator LcsIterator;
123621struct LcsIterator {
123622  Fts3Expr *pExpr;                /* Pointer to phrase expression */
123623  char *pRead;                    /* Cursor used to iterate through aDoclist */
123624  int iPosOffset;                 /* Tokens count up to end of this phrase */
123625  int iCol;                       /* Current column number */
123626  int iPos;                       /* Current position */
123627};
123628
123629/*
123630** If LcsIterator.iCol is set to the following value, the iterator has
123631** finished iterating through all offsets for all columns.
123632*/
123633#define LCS_ITERATOR_FINISHED 0x7FFFFFFF;
123634
123635static int fts3MatchinfoLcsCb(
123636  Fts3Expr *pExpr,                /* Phrase expression node */
123637  int iPhrase,                    /* Phrase number (numbered from zero) */
123638  void *pCtx                      /* Pointer to MatchInfo structure */
123639){
123640  LcsIterator *aIter = (LcsIterator *)pCtx;
123641  aIter[iPhrase].pExpr = pExpr;
123642  return SQLITE_OK;
123643}
123644
123645/*
123646** Advance the iterator passed as an argument to the next position. Return
123647** 1 if the iterator is at EOF or if it now points to the start of the
123648** position list for the next column.
123649*/
123650static int fts3LcsIteratorAdvance(LcsIterator *pIter){
123651  char *pRead = pIter->pRead;
123652  sqlite3_int64 iRead;
123653  int rc = 0;
123654
123655  pRead += sqlite3Fts3GetVarint(pRead, &iRead);
123656  if( iRead==0 ){
123657    pIter->iCol = LCS_ITERATOR_FINISHED;
123658    rc = 1;
123659  }else{
123660    if( iRead==1 ){
123661      pRead += sqlite3Fts3GetVarint(pRead, &iRead);
123662      pIter->iCol = (int)iRead;
123663      pIter->iPos = pIter->iPosOffset;
123664      pRead += sqlite3Fts3GetVarint(pRead, &iRead);
123665      rc = 1;
123666    }
123667    pIter->iPos += (int)(iRead-2);
123668  }
123669
123670  pIter->pRead = pRead;
123671  return rc;
123672}
123673
123674/*
123675** This function implements the FTS3_MATCHINFO_LCS matchinfo() flag.
123676**
123677** If the call is successful, the longest-common-substring lengths for each
123678** column are written into the first nCol elements of the pInfo->aMatchinfo[]
123679** array before returning. SQLITE_OK is returned in this case.
123680**
123681** Otherwise, if an error occurs, an SQLite error code is returned and the
123682** data written to the first nCol elements of pInfo->aMatchinfo[] is
123683** undefined.
123684*/
123685static int fts3MatchinfoLcs(Fts3Cursor *pCsr, MatchInfo *pInfo){
123686  LcsIterator *aIter;
123687  int i;
123688  int iCol;
123689  int nToken = 0;
123690
123691  /* Allocate and populate the array of LcsIterator objects. The array
123692  ** contains one element for each matchable phrase in the query.
123693  **/
123694  aIter = sqlite3_malloc(sizeof(LcsIterator) * pCsr->nPhrase);
123695  if( !aIter ) return SQLITE_NOMEM;
123696  memset(aIter, 0, sizeof(LcsIterator) * pCsr->nPhrase);
123697  (void)fts3ExprIterate(pCsr->pExpr, fts3MatchinfoLcsCb, (void*)aIter);
123698  for(i=0; i<pInfo->nPhrase; i++){
123699    LcsIterator *pIter = &aIter[i];
123700    nToken -= pIter->pExpr->pPhrase->nToken;
123701    pIter->iPosOffset = nToken;
123702    pIter->pRead = sqlite3Fts3FindPositions(pIter->pExpr, pCsr->iPrevId, -1);
123703    if( pIter->pRead ){
123704      pIter->iPos = pIter->iPosOffset;
123705      fts3LcsIteratorAdvance(&aIter[i]);
123706    }else{
123707      pIter->iCol = LCS_ITERATOR_FINISHED;
123708    }
123709  }
123710
123711  for(iCol=0; iCol<pInfo->nCol; iCol++){
123712    int nLcs = 0;                 /* LCS value for this column */
123713    int nLive = 0;                /* Number of iterators in aIter not at EOF */
123714
123715    /* Loop through the iterators in aIter[]. Set nLive to the number of
123716    ** iterators that point to a position-list corresponding to column iCol.
123717    */
123718    for(i=0; i<pInfo->nPhrase; i++){
123719      assert( aIter[i].iCol>=iCol );
123720      if( aIter[i].iCol==iCol ) nLive++;
123721    }
123722
123723    /* The following loop runs until all iterators in aIter[] have finished
123724    ** iterating through positions in column iCol. Exactly one of the
123725    ** iterators is advanced each time the body of the loop is run.
123726    */
123727    while( nLive>0 ){
123728      LcsIterator *pAdv = 0;      /* The iterator to advance by one position */
123729      int nThisLcs = 0;           /* LCS for the current iterator positions */
123730
123731      for(i=0; i<pInfo->nPhrase; i++){
123732        LcsIterator *pIter = &aIter[i];
123733        if( iCol!=pIter->iCol ){
123734          /* This iterator is already at EOF for this column. */
123735          nThisLcs = 0;
123736        }else{
123737          if( pAdv==0 || pIter->iPos<pAdv->iPos ){
123738            pAdv = pIter;
123739          }
123740          if( nThisLcs==0 || pIter->iPos==pIter[-1].iPos ){
123741            nThisLcs++;
123742          }else{
123743            nThisLcs = 1;
123744          }
123745          if( nThisLcs>nLcs ) nLcs = nThisLcs;
123746        }
123747      }
123748      if( fts3LcsIteratorAdvance(pAdv) ) nLive--;
123749    }
123750
123751    pInfo->aMatchinfo[iCol] = nLcs;
123752  }
123753
123754  sqlite3_free(aIter);
123755  return SQLITE_OK;
123756}
123757
123758/*
123759** Populate the buffer pInfo->aMatchinfo[] with an array of integers to
123760** be returned by the matchinfo() function. Argument zArg contains the
123761** format string passed as the second argument to matchinfo (or the
123762** default value "pcx" if no second argument was specified). The format
123763** string has already been validated and the pInfo->aMatchinfo[] array
123764** is guaranteed to be large enough for the output.
123765**
123766** If bGlobal is true, then populate all fields of the matchinfo() output.
123767** If it is false, then assume that those fields that do not change between
123768** rows (i.e. FTS3_MATCHINFO_NPHRASE, NCOL, NDOC, AVGLENGTH and part of HITS)
123769** have already been populated.
123770**
123771** Return SQLITE_OK if successful, or an SQLite error code if an error
123772** occurs. If a value other than SQLITE_OK is returned, the state the
123773** pInfo->aMatchinfo[] buffer is left in is undefined.
123774*/
123775static int fts3MatchinfoValues(
123776  Fts3Cursor *pCsr,               /* FTS3 cursor object */
123777  int bGlobal,                    /* True to grab the global stats */
123778  MatchInfo *pInfo,               /* Matchinfo context object */
123779  const char *zArg                /* Matchinfo format string */
123780){
123781  int rc = SQLITE_OK;
123782  int i;
123783  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
123784  sqlite3_stmt *pSelect = 0;
123785
123786  for(i=0; rc==SQLITE_OK && zArg[i]; i++){
123787
123788    switch( zArg[i] ){
123789      case FTS3_MATCHINFO_NPHRASE:
123790        if( bGlobal ) pInfo->aMatchinfo[0] = pInfo->nPhrase;
123791        break;
123792
123793      case FTS3_MATCHINFO_NCOL:
123794        if( bGlobal ) pInfo->aMatchinfo[0] = pInfo->nCol;
123795        break;
123796
123797      case FTS3_MATCHINFO_NDOC:
123798        if( bGlobal ){
123799          sqlite3_int64 nDoc;
123800          rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &nDoc, 0);
123801          pInfo->aMatchinfo[0] = (u32)nDoc;
123802        }
123803        break;
123804
123805      case FTS3_MATCHINFO_AVGLENGTH:
123806        if( bGlobal ){
123807          sqlite3_int64 nDoc;     /* Number of rows in table */
123808          const char *a;          /* Aggregate column length array */
123809
123810          rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &nDoc, &a);
123811          if( rc==SQLITE_OK ){
123812            int iCol;
123813            for(iCol=0; iCol<pInfo->nCol; iCol++){
123814              u32 iVal;
123815              sqlite3_int64 nToken;
123816              a += sqlite3Fts3GetVarint(a, &nToken);
123817              iVal = (u32)(((u32)(nToken&0xffffffff)+nDoc/2)/nDoc);
123818              pInfo->aMatchinfo[iCol] = iVal;
123819            }
123820          }
123821        }
123822        break;
123823
123824      case FTS3_MATCHINFO_LENGTH: {
123825        sqlite3_stmt *pSelectDocsize = 0;
123826        rc = sqlite3Fts3SelectDocsize(pTab, pCsr->iPrevId, &pSelectDocsize);
123827        if( rc==SQLITE_OK ){
123828          int iCol;
123829          const char *a = sqlite3_column_blob(pSelectDocsize, 0);
123830          for(iCol=0; iCol<pInfo->nCol; iCol++){
123831            sqlite3_int64 nToken;
123832            a += sqlite3Fts3GetVarint(a, &nToken);
123833            pInfo->aMatchinfo[iCol] = (u32)nToken;
123834          }
123835        }
123836        sqlite3_reset(pSelectDocsize);
123837        break;
123838      }
123839
123840      case FTS3_MATCHINFO_LCS:
123841        rc = fts3ExprLoadDoclists(pCsr, 0, 0);
123842        if( rc==SQLITE_OK ){
123843          rc = fts3MatchinfoLcs(pCsr, pInfo);
123844        }
123845        break;
123846
123847      default: {
123848        Fts3Expr *pExpr;
123849        assert( zArg[i]==FTS3_MATCHINFO_HITS );
123850        pExpr = pCsr->pExpr;
123851        rc = fts3ExprLoadDoclists(pCsr, 0, 0);
123852        if( rc!=SQLITE_OK ) break;
123853        if( bGlobal ){
123854          if( pCsr->pDeferred ){
123855            rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &pInfo->nDoc, 0);
123856            if( rc!=SQLITE_OK ) break;
123857          }
123858          rc = fts3ExprIterate(pExpr, fts3ExprGlobalHitsCb,(void*)pInfo);
123859          if( rc!=SQLITE_OK ) break;
123860        }
123861        (void)fts3ExprIterate(pExpr, fts3ExprLocalHitsCb,(void*)pInfo);
123862        break;
123863      }
123864    }
123865
123866    pInfo->aMatchinfo += fts3MatchinfoSize(pInfo, zArg[i]);
123867  }
123868
123869  sqlite3_reset(pSelect);
123870  return rc;
123871}
123872
123873
123874/*
123875** Populate pCsr->aMatchinfo[] with data for the current row. The
123876** 'matchinfo' data is an array of 32-bit unsigned integers (C type u32).
123877*/
123878static int fts3GetMatchinfo(
123879  Fts3Cursor *pCsr,               /* FTS3 Cursor object */
123880  const char *zArg                /* Second argument to matchinfo() function */
123881){
123882  MatchInfo sInfo;
123883  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
123884  int rc = SQLITE_OK;
123885  int bGlobal = 0;                /* Collect 'global' stats as well as local */
123886
123887  memset(&sInfo, 0, sizeof(MatchInfo));
123888  sInfo.pCursor = pCsr;
123889  sInfo.nCol = pTab->nColumn;
123890
123891  /* If there is cached matchinfo() data, but the format string for the
123892  ** cache does not match the format string for this request, discard
123893  ** the cached data. */
123894  if( pCsr->zMatchinfo && strcmp(pCsr->zMatchinfo, zArg) ){
123895    assert( pCsr->aMatchinfo );
123896    sqlite3_free(pCsr->aMatchinfo);
123897    pCsr->zMatchinfo = 0;
123898    pCsr->aMatchinfo = 0;
123899  }
123900
123901  /* If Fts3Cursor.aMatchinfo[] is NULL, then this is the first time the
123902  ** matchinfo function has been called for this query. In this case
123903  ** allocate the array used to accumulate the matchinfo data and
123904  ** initialize those elements that are constant for every row.
123905  */
123906  if( pCsr->aMatchinfo==0 ){
123907    int nMatchinfo = 0;           /* Number of u32 elements in match-info */
123908    int nArg;                     /* Bytes in zArg */
123909    int i;                        /* Used to iterate through zArg */
123910
123911    /* Determine the number of phrases in the query */
123912    pCsr->nPhrase = fts3ExprPhraseCount(pCsr->pExpr);
123913    sInfo.nPhrase = pCsr->nPhrase;
123914
123915    /* Determine the number of integers in the buffer returned by this call. */
123916    for(i=0; zArg[i]; i++){
123917      nMatchinfo += fts3MatchinfoSize(&sInfo, zArg[i]);
123918    }
123919
123920    /* Allocate space for Fts3Cursor.aMatchinfo[] and Fts3Cursor.zMatchinfo. */
123921    nArg = (int)strlen(zArg);
123922    pCsr->aMatchinfo = (u32 *)sqlite3_malloc(sizeof(u32)*nMatchinfo + nArg + 1);
123923    if( !pCsr->aMatchinfo ) return SQLITE_NOMEM;
123924
123925    pCsr->zMatchinfo = (char *)&pCsr->aMatchinfo[nMatchinfo];
123926    pCsr->nMatchinfo = nMatchinfo;
123927    memcpy(pCsr->zMatchinfo, zArg, nArg+1);
123928    memset(pCsr->aMatchinfo, 0, sizeof(u32)*nMatchinfo);
123929    pCsr->isMatchinfoNeeded = 1;
123930    bGlobal = 1;
123931  }
123932
123933  sInfo.aMatchinfo = pCsr->aMatchinfo;
123934  sInfo.nPhrase = pCsr->nPhrase;
123935  if( pCsr->isMatchinfoNeeded ){
123936    rc = fts3MatchinfoValues(pCsr, bGlobal, &sInfo, zArg);
123937    pCsr->isMatchinfoNeeded = 0;
123938  }
123939
123940  return rc;
123941}
123942
123943/*
123944** Implementation of snippet() function.
123945*/
123946SQLITE_PRIVATE void sqlite3Fts3Snippet(
123947  sqlite3_context *pCtx,          /* SQLite function call context */
123948  Fts3Cursor *pCsr,               /* Cursor object */
123949  const char *zStart,             /* Snippet start text - "<b>" */
123950  const char *zEnd,               /* Snippet end text - "</b>" */
123951  const char *zEllipsis,          /* Snippet ellipsis text - "<b>...</b>" */
123952  int iCol,                       /* Extract snippet from this column */
123953  int nToken                      /* Approximate number of tokens in snippet */
123954){
123955  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
123956  int rc = SQLITE_OK;
123957  int i;
123958  StrBuffer res = {0, 0, 0};
123959
123960  /* The returned text includes up to four fragments of text extracted from
123961  ** the data in the current row. The first iteration of the for(...) loop
123962  ** below attempts to locate a single fragment of text nToken tokens in
123963  ** size that contains at least one instance of all phrases in the query
123964  ** expression that appear in the current row. If such a fragment of text
123965  ** cannot be found, the second iteration of the loop attempts to locate
123966  ** a pair of fragments, and so on.
123967  */
123968  int nSnippet = 0;               /* Number of fragments in this snippet */
123969  SnippetFragment aSnippet[4];    /* Maximum of 4 fragments per snippet */
123970  int nFToken = -1;               /* Number of tokens in each fragment */
123971
123972  if( !pCsr->pExpr ){
123973    sqlite3_result_text(pCtx, "", 0, SQLITE_STATIC);
123974    return;
123975  }
123976
123977  for(nSnippet=1; 1; nSnippet++){
123978
123979    int iSnip;                    /* Loop counter 0..nSnippet-1 */
123980    u64 mCovered = 0;             /* Bitmask of phrases covered by snippet */
123981    u64 mSeen = 0;                /* Bitmask of phrases seen by BestSnippet() */
123982
123983    if( nToken>=0 ){
123984      nFToken = (nToken+nSnippet-1) / nSnippet;
123985    }else{
123986      nFToken = -1 * nToken;
123987    }
123988
123989    for(iSnip=0; iSnip<nSnippet; iSnip++){
123990      int iBestScore = -1;        /* Best score of columns checked so far */
123991      int iRead;                  /* Used to iterate through columns */
123992      SnippetFragment *pFragment = &aSnippet[iSnip];
123993
123994      memset(pFragment, 0, sizeof(*pFragment));
123995
123996      /* Loop through all columns of the table being considered for snippets.
123997      ** If the iCol argument to this function was negative, this means all
123998      ** columns of the FTS3 table. Otherwise, only column iCol is considered.
123999      */
124000      for(iRead=0; iRead<pTab->nColumn; iRead++){
124001        SnippetFragment sF = {0, 0, 0, 0};
124002        int iS;
124003        if( iCol>=0 && iRead!=iCol ) continue;
124004
124005        /* Find the best snippet of nFToken tokens in column iRead. */
124006        rc = fts3BestSnippet(nFToken, pCsr, iRead, mCovered, &mSeen, &sF, &iS);
124007        if( rc!=SQLITE_OK ){
124008          goto snippet_out;
124009        }
124010        if( iS>iBestScore ){
124011          *pFragment = sF;
124012          iBestScore = iS;
124013        }
124014      }
124015
124016      mCovered |= pFragment->covered;
124017    }
124018
124019    /* If all query phrases seen by fts3BestSnippet() are present in at least
124020    ** one of the nSnippet snippet fragments, break out of the loop.
124021    */
124022    assert( (mCovered&mSeen)==mCovered );
124023    if( mSeen==mCovered || nSnippet==SizeofArray(aSnippet) ) break;
124024  }
124025
124026  assert( nFToken>0 );
124027
124028  for(i=0; i<nSnippet && rc==SQLITE_OK; i++){
124029    rc = fts3SnippetText(pCsr, &aSnippet[i],
124030        i, (i==nSnippet-1), nFToken, zStart, zEnd, zEllipsis, &res
124031    );
124032  }
124033
124034 snippet_out:
124035  sqlite3Fts3SegmentsClose(pTab);
124036  if( rc!=SQLITE_OK ){
124037    sqlite3_result_error_code(pCtx, rc);
124038    sqlite3_free(res.z);
124039  }else{
124040    sqlite3_result_text(pCtx, res.z, -1, sqlite3_free);
124041  }
124042}
124043
124044
124045typedef struct TermOffset TermOffset;
124046typedef struct TermOffsetCtx TermOffsetCtx;
124047
124048struct TermOffset {
124049  char *pList;                    /* Position-list */
124050  int iPos;                       /* Position just read from pList */
124051  int iOff;                       /* Offset of this term from read positions */
124052};
124053
124054struct TermOffsetCtx {
124055  int iCol;                       /* Column of table to populate aTerm for */
124056  int iTerm;
124057  sqlite3_int64 iDocid;
124058  TermOffset *aTerm;
124059};
124060
124061/*
124062** This function is an fts3ExprIterate() callback used by sqlite3Fts3Offsets().
124063*/
124064static int fts3ExprTermOffsetInit(Fts3Expr *pExpr, int iPhrase, void *ctx){
124065  TermOffsetCtx *p = (TermOffsetCtx *)ctx;
124066  int nTerm;                      /* Number of tokens in phrase */
124067  int iTerm;                      /* For looping through nTerm phrase terms */
124068  char *pList;                    /* Pointer to position list for phrase */
124069  int iPos = 0;                   /* First position in position-list */
124070
124071  UNUSED_PARAMETER(iPhrase);
124072  pList = sqlite3Fts3FindPositions(pExpr, p->iDocid, p->iCol);
124073  nTerm = pExpr->pPhrase->nToken;
124074  if( pList ){
124075    fts3GetDeltaPosition(&pList, &iPos);
124076    assert( iPos>=0 );
124077  }
124078
124079  for(iTerm=0; iTerm<nTerm; iTerm++){
124080    TermOffset *pT = &p->aTerm[p->iTerm++];
124081    pT->iOff = nTerm-iTerm-1;
124082    pT->pList = pList;
124083    pT->iPos = iPos;
124084  }
124085
124086  return SQLITE_OK;
124087}
124088
124089/*
124090** Implementation of offsets() function.
124091*/
124092SQLITE_PRIVATE void sqlite3Fts3Offsets(
124093  sqlite3_context *pCtx,          /* SQLite function call context */
124094  Fts3Cursor *pCsr                /* Cursor object */
124095){
124096  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
124097  sqlite3_tokenizer_module const *pMod = pTab->pTokenizer->pModule;
124098  const char *ZDUMMY;             /* Dummy argument used with xNext() */
124099  int NDUMMY;                     /* Dummy argument used with xNext() */
124100  int rc;                         /* Return Code */
124101  int nToken;                     /* Number of tokens in query */
124102  int iCol;                       /* Column currently being processed */
124103  StrBuffer res = {0, 0, 0};      /* Result string */
124104  TermOffsetCtx sCtx;             /* Context for fts3ExprTermOffsetInit() */
124105
124106  if( !pCsr->pExpr ){
124107    sqlite3_result_text(pCtx, "", 0, SQLITE_STATIC);
124108    return;
124109  }
124110
124111  memset(&sCtx, 0, sizeof(sCtx));
124112  assert( pCsr->isRequireSeek==0 );
124113
124114  /* Count the number of terms in the query */
124115  rc = fts3ExprLoadDoclists(pCsr, 0, &nToken);
124116  if( rc!=SQLITE_OK ) goto offsets_out;
124117
124118  /* Allocate the array of TermOffset iterators. */
124119  sCtx.aTerm = (TermOffset *)sqlite3_malloc(sizeof(TermOffset)*nToken);
124120  if( 0==sCtx.aTerm ){
124121    rc = SQLITE_NOMEM;
124122    goto offsets_out;
124123  }
124124  sCtx.iDocid = pCsr->iPrevId;
124125
124126  /* Loop through the table columns, appending offset information to
124127  ** string-buffer res for each column.
124128  */
124129  for(iCol=0; iCol<pTab->nColumn; iCol++){
124130    sqlite3_tokenizer_cursor *pC; /* Tokenizer cursor */
124131    int iStart;
124132    int iEnd;
124133    int iCurrent;
124134    const char *zDoc;
124135    int nDoc;
124136
124137    /* Initialize the contents of sCtx.aTerm[] for column iCol. There is
124138    ** no way that this operation can fail, so the return code from
124139    ** fts3ExprIterate() can be discarded.
124140    */
124141    sCtx.iCol = iCol;
124142    sCtx.iTerm = 0;
124143    (void)fts3ExprIterate(pCsr->pExpr, fts3ExprTermOffsetInit, (void *)&sCtx);
124144
124145    /* Retreive the text stored in column iCol. If an SQL NULL is stored
124146    ** in column iCol, jump immediately to the next iteration of the loop.
124147    ** If an OOM occurs while retrieving the data (this can happen if SQLite
124148    ** needs to transform the data from utf-16 to utf-8), return SQLITE_NOMEM
124149    ** to the caller.
124150    */
124151    zDoc = (const char *)sqlite3_column_text(pCsr->pStmt, iCol+1);
124152    nDoc = sqlite3_column_bytes(pCsr->pStmt, iCol+1);
124153    if( zDoc==0 ){
124154      if( sqlite3_column_type(pCsr->pStmt, iCol+1)==SQLITE_NULL ){
124155        continue;
124156      }
124157      rc = SQLITE_NOMEM;
124158      goto offsets_out;
124159    }
124160
124161    /* Initialize a tokenizer iterator to iterate through column iCol. */
124162    rc = pMod->xOpen(pTab->pTokenizer, zDoc, nDoc, &pC);
124163    if( rc!=SQLITE_OK ) goto offsets_out;
124164    pC->pTokenizer = pTab->pTokenizer;
124165
124166    rc = pMod->xNext(pC, &ZDUMMY, &NDUMMY, &iStart, &iEnd, &iCurrent);
124167    while( rc==SQLITE_OK ){
124168      int i;                      /* Used to loop through terms */
124169      int iMinPos = 0x7FFFFFFF;   /* Position of next token */
124170      TermOffset *pTerm = 0;      /* TermOffset associated with next token */
124171
124172      for(i=0; i<nToken; i++){
124173        TermOffset *pT = &sCtx.aTerm[i];
124174        if( pT->pList && (pT->iPos-pT->iOff)<iMinPos ){
124175          iMinPos = pT->iPos-pT->iOff;
124176          pTerm = pT;
124177        }
124178      }
124179
124180      if( !pTerm ){
124181        /* All offsets for this column have been gathered. */
124182        break;
124183      }else{
124184        assert( iCurrent<=iMinPos );
124185        if( 0==(0xFE&*pTerm->pList) ){
124186          pTerm->pList = 0;
124187        }else{
124188          fts3GetDeltaPosition(&pTerm->pList, &pTerm->iPos);
124189        }
124190        while( rc==SQLITE_OK && iCurrent<iMinPos ){
124191          rc = pMod->xNext(pC, &ZDUMMY, &NDUMMY, &iStart, &iEnd, &iCurrent);
124192        }
124193        if( rc==SQLITE_OK ){
124194          char aBuffer[64];
124195          sqlite3_snprintf(sizeof(aBuffer), aBuffer,
124196              "%d %d %d %d ", iCol, pTerm-sCtx.aTerm, iStart, iEnd-iStart
124197          );
124198          rc = fts3StringAppend(&res, aBuffer, -1);
124199        }else if( rc==SQLITE_DONE ){
124200          rc = SQLITE_CORRUPT;
124201        }
124202      }
124203    }
124204    if( rc==SQLITE_DONE ){
124205      rc = SQLITE_OK;
124206    }
124207
124208    pMod->xClose(pC);
124209    if( rc!=SQLITE_OK ) goto offsets_out;
124210  }
124211
124212 offsets_out:
124213  sqlite3_free(sCtx.aTerm);
124214  assert( rc!=SQLITE_DONE );
124215  sqlite3Fts3SegmentsClose(pTab);
124216  if( rc!=SQLITE_OK ){
124217    sqlite3_result_error_code(pCtx,  rc);
124218    sqlite3_free(res.z);
124219  }else{
124220    sqlite3_result_text(pCtx, res.z, res.n-1, sqlite3_free);
124221  }
124222  return;
124223}
124224
124225/*
124226** Implementation of matchinfo() function.
124227*/
124228SQLITE_PRIVATE void sqlite3Fts3Matchinfo(
124229  sqlite3_context *pContext,      /* Function call context */
124230  Fts3Cursor *pCsr,               /* FTS3 table cursor */
124231  const char *zArg                /* Second arg to matchinfo() function */
124232){
124233  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
124234  int rc;
124235  int i;
124236  const char *zFormat;
124237
124238  if( zArg ){
124239    for(i=0; zArg[i]; i++){
124240      char *zErr = 0;
124241      if( fts3MatchinfoCheck(pTab, zArg[i], &zErr) ){
124242        sqlite3_result_error(pContext, zErr, -1);
124243        sqlite3_free(zErr);
124244        return;
124245      }
124246    }
124247    zFormat = zArg;
124248  }else{
124249    zFormat = FTS3_MATCHINFO_DEFAULT;
124250  }
124251
124252  if( !pCsr->pExpr ){
124253    sqlite3_result_blob(pContext, "", 0, SQLITE_STATIC);
124254    return;
124255  }
124256
124257  /* Retrieve matchinfo() data. */
124258  rc = fts3GetMatchinfo(pCsr, zFormat);
124259  sqlite3Fts3SegmentsClose(pTab);
124260
124261  if( rc!=SQLITE_OK ){
124262    sqlite3_result_error_code(pContext, rc);
124263  }else{
124264    int n = pCsr->nMatchinfo * sizeof(u32);
124265    sqlite3_result_blob(pContext, pCsr->aMatchinfo, n, SQLITE_TRANSIENT);
124266  }
124267}
124268
124269#endif
124270
124271/************** End of fts3_snippet.c ****************************************/
124272/************** Begin file rtree.c *******************************************/
124273/*
124274** 2001 September 15
124275**
124276** The author disclaims copyright to this source code.  In place of
124277** a legal notice, here is a blessing:
124278**
124279**    May you do good and not evil.
124280**    May you find forgiveness for yourself and forgive others.
124281**    May you share freely, never taking more than you give.
124282**
124283*************************************************************************
124284** This file contains code for implementations of the r-tree and r*-tree
124285** algorithms packaged as an SQLite virtual table module.
124286*/
124287
124288/*
124289** Database Format of R-Tree Tables
124290** --------------------------------
124291**
124292** The data structure for a single virtual r-tree table is stored in three
124293** native SQLite tables declared as follows. In each case, the '%' character
124294** in the table name is replaced with the user-supplied name of the r-tree
124295** table.
124296**
124297**   CREATE TABLE %_node(nodeno INTEGER PRIMARY KEY, data BLOB)
124298**   CREATE TABLE %_parent(nodeno INTEGER PRIMARY KEY, parentnode INTEGER)
124299**   CREATE TABLE %_rowid(rowid INTEGER PRIMARY KEY, nodeno INTEGER)
124300**
124301** The data for each node of the r-tree structure is stored in the %_node
124302** table. For each node that is not the root node of the r-tree, there is
124303** an entry in the %_parent table associating the node with its parent.
124304** And for each row of data in the table, there is an entry in the %_rowid
124305** table that maps from the entries rowid to the id of the node that it
124306** is stored on.
124307**
124308** The root node of an r-tree always exists, even if the r-tree table is
124309** empty. The nodeno of the root node is always 1. All other nodes in the
124310** table must be the same size as the root node. The content of each node
124311** is formatted as follows:
124312**
124313**   1. If the node is the root node (node 1), then the first 2 bytes
124314**      of the node contain the tree depth as a big-endian integer.
124315**      For non-root nodes, the first 2 bytes are left unused.
124316**
124317**   2. The next 2 bytes contain the number of entries currently
124318**      stored in the node.
124319**
124320**   3. The remainder of the node contains the node entries. Each entry
124321**      consists of a single 8-byte integer followed by an even number
124322**      of 4-byte coordinates. For leaf nodes the integer is the rowid
124323**      of a record. For internal nodes it is the node number of a
124324**      child page.
124325*/
124326
124327#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_RTREE)
124328
124329/*
124330** This file contains an implementation of a couple of different variants
124331** of the r-tree algorithm. See the README file for further details. The
124332** same data-structure is used for all, but the algorithms for insert and
124333** delete operations vary. The variants used are selected at compile time
124334** by defining the following symbols:
124335*/
124336
124337/* Either, both or none of the following may be set to activate
124338** r*tree variant algorithms.
124339*/
124340#define VARIANT_RSTARTREE_CHOOSESUBTREE 0
124341#define VARIANT_RSTARTREE_REINSERT      1
124342
124343/*
124344** Exactly one of the following must be set to 1.
124345*/
124346#define VARIANT_GUTTMAN_QUADRATIC_SPLIT 0
124347#define VARIANT_GUTTMAN_LINEAR_SPLIT    0
124348#define VARIANT_RSTARTREE_SPLIT         1
124349
124350#define VARIANT_GUTTMAN_SPLIT \
124351        (VARIANT_GUTTMAN_LINEAR_SPLIT||VARIANT_GUTTMAN_QUADRATIC_SPLIT)
124352
124353#if VARIANT_GUTTMAN_QUADRATIC_SPLIT
124354  #define PickNext QuadraticPickNext
124355  #define PickSeeds QuadraticPickSeeds
124356  #define AssignCells splitNodeGuttman
124357#endif
124358#if VARIANT_GUTTMAN_LINEAR_SPLIT
124359  #define PickNext LinearPickNext
124360  #define PickSeeds LinearPickSeeds
124361  #define AssignCells splitNodeGuttman
124362#endif
124363#if VARIANT_RSTARTREE_SPLIT
124364  #define AssignCells splitNodeStartree
124365#endif
124366
124367#if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
124368# define NDEBUG 1
124369#endif
124370
124371#ifndef SQLITE_CORE
124372  SQLITE_EXTENSION_INIT1
124373#else
124374#endif
124375
124376
124377#ifndef SQLITE_AMALGAMATION
124378#include "sqlite3rtree.h"
124379typedef sqlite3_int64 i64;
124380typedef unsigned char u8;
124381typedef unsigned int u32;
124382#endif
124383
124384/*  The following macro is used to suppress compiler warnings.
124385*/
124386#ifndef UNUSED_PARAMETER
124387# define UNUSED_PARAMETER(x) (void)(x)
124388#endif
124389
124390typedef struct Rtree Rtree;
124391typedef struct RtreeCursor RtreeCursor;
124392typedef struct RtreeNode RtreeNode;
124393typedef struct RtreeCell RtreeCell;
124394typedef struct RtreeConstraint RtreeConstraint;
124395typedef struct RtreeMatchArg RtreeMatchArg;
124396typedef struct RtreeGeomCallback RtreeGeomCallback;
124397typedef union RtreeCoord RtreeCoord;
124398
124399/* The rtree may have between 1 and RTREE_MAX_DIMENSIONS dimensions. */
124400#define RTREE_MAX_DIMENSIONS 5
124401
124402/* Size of hash table Rtree.aHash. This hash table is not expected to
124403** ever contain very many entries, so a fixed number of buckets is
124404** used.
124405*/
124406#define HASHSIZE 128
124407
124408/*
124409** An rtree virtual-table object.
124410*/
124411struct Rtree {
124412  sqlite3_vtab base;
124413  sqlite3 *db;                /* Host database connection */
124414  int iNodeSize;              /* Size in bytes of each node in the node table */
124415  int nDim;                   /* Number of dimensions */
124416  int nBytesPerCell;          /* Bytes consumed per cell */
124417  int iDepth;                 /* Current depth of the r-tree structure */
124418  char *zDb;                  /* Name of database containing r-tree table */
124419  char *zName;                /* Name of r-tree table */
124420  RtreeNode *aHash[HASHSIZE]; /* Hash table of in-memory nodes. */
124421  int nBusy;                  /* Current number of users of this structure */
124422
124423  /* List of nodes removed during a CondenseTree operation. List is
124424  ** linked together via the pointer normally used for hash chains -
124425  ** RtreeNode.pNext. RtreeNode.iNode stores the depth of the sub-tree
124426  ** headed by the node (leaf nodes have RtreeNode.iNode==0).
124427  */
124428  RtreeNode *pDeleted;
124429  int iReinsertHeight;        /* Height of sub-trees Reinsert() has run on */
124430
124431  /* Statements to read/write/delete a record from xxx_node */
124432  sqlite3_stmt *pReadNode;
124433  sqlite3_stmt *pWriteNode;
124434  sqlite3_stmt *pDeleteNode;
124435
124436  /* Statements to read/write/delete a record from xxx_rowid */
124437  sqlite3_stmt *pReadRowid;
124438  sqlite3_stmt *pWriteRowid;
124439  sqlite3_stmt *pDeleteRowid;
124440
124441  /* Statements to read/write/delete a record from xxx_parent */
124442  sqlite3_stmt *pReadParent;
124443  sqlite3_stmt *pWriteParent;
124444  sqlite3_stmt *pDeleteParent;
124445
124446  int eCoordType;
124447};
124448
124449/* Possible values for eCoordType: */
124450#define RTREE_COORD_REAL32 0
124451#define RTREE_COORD_INT32  1
124452
124453/*
124454** The minimum number of cells allowed for a node is a third of the
124455** maximum. In Gutman's notation:
124456**
124457**     m = M/3
124458**
124459** If an R*-tree "Reinsert" operation is required, the same number of
124460** cells are removed from the overfull node and reinserted into the tree.
124461*/
124462#define RTREE_MINCELLS(p) ((((p)->iNodeSize-4)/(p)->nBytesPerCell)/3)
124463#define RTREE_REINSERT(p) RTREE_MINCELLS(p)
124464#define RTREE_MAXCELLS 51
124465
124466/*
124467** The smallest possible node-size is (512-64)==448 bytes. And the largest
124468** supported cell size is 48 bytes (8 byte rowid + ten 4 byte coordinates).
124469** Therefore all non-root nodes must contain at least 3 entries. Since
124470** 2^40 is greater than 2^64, an r-tree structure always has a depth of
124471** 40 or less.
124472*/
124473#define RTREE_MAX_DEPTH 40
124474
124475/*
124476** An rtree cursor object.
124477*/
124478struct RtreeCursor {
124479  sqlite3_vtab_cursor base;
124480  RtreeNode *pNode;                 /* Node cursor is currently pointing at */
124481  int iCell;                        /* Index of current cell in pNode */
124482  int iStrategy;                    /* Copy of idxNum search parameter */
124483  int nConstraint;                  /* Number of entries in aConstraint */
124484  RtreeConstraint *aConstraint;     /* Search constraints. */
124485};
124486
124487union RtreeCoord {
124488  float f;
124489  int i;
124490};
124491
124492/*
124493** The argument is an RtreeCoord. Return the value stored within the RtreeCoord
124494** formatted as a double. This macro assumes that local variable pRtree points
124495** to the Rtree structure associated with the RtreeCoord.
124496*/
124497#define DCOORD(coord) (                           \
124498  (pRtree->eCoordType==RTREE_COORD_REAL32) ?      \
124499    ((double)coord.f) :                           \
124500    ((double)coord.i)                             \
124501)
124502
124503/*
124504** A search constraint.
124505*/
124506struct RtreeConstraint {
124507  int iCoord;                     /* Index of constrained coordinate */
124508  int op;                         /* Constraining operation */
124509  double rValue;                  /* Constraint value. */
124510  int (*xGeom)(sqlite3_rtree_geometry *, int, double *, int *);
124511  sqlite3_rtree_geometry *pGeom;  /* Constraint callback argument for a MATCH */
124512};
124513
124514/* Possible values for RtreeConstraint.op */
124515#define RTREE_EQ    0x41
124516#define RTREE_LE    0x42
124517#define RTREE_LT    0x43
124518#define RTREE_GE    0x44
124519#define RTREE_GT    0x45
124520#define RTREE_MATCH 0x46
124521
124522/*
124523** An rtree structure node.
124524*/
124525struct RtreeNode {
124526  RtreeNode *pParent;               /* Parent node */
124527  i64 iNode;
124528  int nRef;
124529  int isDirty;
124530  u8 *zData;
124531  RtreeNode *pNext;                 /* Next node in this hash chain */
124532};
124533#define NCELL(pNode) readInt16(&(pNode)->zData[2])
124534
124535/*
124536** Structure to store a deserialized rtree record.
124537*/
124538struct RtreeCell {
124539  i64 iRowid;
124540  RtreeCoord aCoord[RTREE_MAX_DIMENSIONS*2];
124541};
124542
124543
124544/*
124545** Value for the first field of every RtreeMatchArg object. The MATCH
124546** operator tests that the first field of a blob operand matches this
124547** value to avoid operating on invalid blobs (which could cause a segfault).
124548*/
124549#define RTREE_GEOMETRY_MAGIC 0x891245AB
124550
124551/*
124552** An instance of this structure must be supplied as a blob argument to
124553** the right-hand-side of an SQL MATCH operator used to constrain an
124554** r-tree query.
124555*/
124556struct RtreeMatchArg {
124557  u32 magic;                      /* Always RTREE_GEOMETRY_MAGIC */
124558  int (*xGeom)(sqlite3_rtree_geometry *, int, double *, int *);
124559  void *pContext;
124560  int nParam;
124561  double aParam[1];
124562};
124563
124564/*
124565** When a geometry callback is created (see sqlite3_rtree_geometry_callback),
124566** a single instance of the following structure is allocated. It is used
124567** as the context for the user-function created by by s_r_g_c(). The object
124568** is eventually deleted by the destructor mechanism provided by
124569** sqlite3_create_function_v2() (which is called by s_r_g_c() to create
124570** the geometry callback function).
124571*/
124572struct RtreeGeomCallback {
124573  int (*xGeom)(sqlite3_rtree_geometry *, int, double *, int *);
124574  void *pContext;
124575};
124576
124577#ifndef MAX
124578# define MAX(x,y) ((x) < (y) ? (y) : (x))
124579#endif
124580#ifndef MIN
124581# define MIN(x,y) ((x) > (y) ? (y) : (x))
124582#endif
124583
124584/*
124585** Functions to deserialize a 16 bit integer, 32 bit real number and
124586** 64 bit integer. The deserialized value is returned.
124587*/
124588static int readInt16(u8 *p){
124589  return (p[0]<<8) + p[1];
124590}
124591static void readCoord(u8 *p, RtreeCoord *pCoord){
124592  u32 i = (
124593    (((u32)p[0]) << 24) +
124594    (((u32)p[1]) << 16) +
124595    (((u32)p[2]) <<  8) +
124596    (((u32)p[3]) <<  0)
124597  );
124598  *(u32 *)pCoord = i;
124599}
124600static i64 readInt64(u8 *p){
124601  return (
124602    (((i64)p[0]) << 56) +
124603    (((i64)p[1]) << 48) +
124604    (((i64)p[2]) << 40) +
124605    (((i64)p[3]) << 32) +
124606    (((i64)p[4]) << 24) +
124607    (((i64)p[5]) << 16) +
124608    (((i64)p[6]) <<  8) +
124609    (((i64)p[7]) <<  0)
124610  );
124611}
124612
124613/*
124614** Functions to serialize a 16 bit integer, 32 bit real number and
124615** 64 bit integer. The value returned is the number of bytes written
124616** to the argument buffer (always 2, 4 and 8 respectively).
124617*/
124618static int writeInt16(u8 *p, int i){
124619  p[0] = (i>> 8)&0xFF;
124620  p[1] = (i>> 0)&0xFF;
124621  return 2;
124622}
124623static int writeCoord(u8 *p, RtreeCoord *pCoord){
124624  u32 i;
124625  assert( sizeof(RtreeCoord)==4 );
124626  assert( sizeof(u32)==4 );
124627  i = *(u32 *)pCoord;
124628  p[0] = (i>>24)&0xFF;
124629  p[1] = (i>>16)&0xFF;
124630  p[2] = (i>> 8)&0xFF;
124631  p[3] = (i>> 0)&0xFF;
124632  return 4;
124633}
124634static int writeInt64(u8 *p, i64 i){
124635  p[0] = (i>>56)&0xFF;
124636  p[1] = (i>>48)&0xFF;
124637  p[2] = (i>>40)&0xFF;
124638  p[3] = (i>>32)&0xFF;
124639  p[4] = (i>>24)&0xFF;
124640  p[5] = (i>>16)&0xFF;
124641  p[6] = (i>> 8)&0xFF;
124642  p[7] = (i>> 0)&0xFF;
124643  return 8;
124644}
124645
124646/*
124647** Increment the reference count of node p.
124648*/
124649static void nodeReference(RtreeNode *p){
124650  if( p ){
124651    p->nRef++;
124652  }
124653}
124654
124655/*
124656** Clear the content of node p (set all bytes to 0x00).
124657*/
124658static void nodeZero(Rtree *pRtree, RtreeNode *p){
124659  memset(&p->zData[2], 0, pRtree->iNodeSize-2);
124660  p->isDirty = 1;
124661}
124662
124663/*
124664** Given a node number iNode, return the corresponding key to use
124665** in the Rtree.aHash table.
124666*/
124667static int nodeHash(i64 iNode){
124668  return (
124669    (iNode>>56) ^ (iNode>>48) ^ (iNode>>40) ^ (iNode>>32) ^
124670    (iNode>>24) ^ (iNode>>16) ^ (iNode>> 8) ^ (iNode>> 0)
124671  ) % HASHSIZE;
124672}
124673
124674/*
124675** Search the node hash table for node iNode. If found, return a pointer
124676** to it. Otherwise, return 0.
124677*/
124678static RtreeNode *nodeHashLookup(Rtree *pRtree, i64 iNode){
124679  RtreeNode *p;
124680  for(p=pRtree->aHash[nodeHash(iNode)]; p && p->iNode!=iNode; p=p->pNext);
124681  return p;
124682}
124683
124684/*
124685** Add node pNode to the node hash table.
124686*/
124687static void nodeHashInsert(Rtree *pRtree, RtreeNode *pNode){
124688  int iHash;
124689  assert( pNode->pNext==0 );
124690  iHash = nodeHash(pNode->iNode);
124691  pNode->pNext = pRtree->aHash[iHash];
124692  pRtree->aHash[iHash] = pNode;
124693}
124694
124695/*
124696** Remove node pNode from the node hash table.
124697*/
124698static void nodeHashDelete(Rtree *pRtree, RtreeNode *pNode){
124699  RtreeNode **pp;
124700  if( pNode->iNode!=0 ){
124701    pp = &pRtree->aHash[nodeHash(pNode->iNode)];
124702    for( ; (*pp)!=pNode; pp = &(*pp)->pNext){ assert(*pp); }
124703    *pp = pNode->pNext;
124704    pNode->pNext = 0;
124705  }
124706}
124707
124708/*
124709** Allocate and return new r-tree node. Initially, (RtreeNode.iNode==0),
124710** indicating that node has not yet been assigned a node number. It is
124711** assigned a node number when nodeWrite() is called to write the
124712** node contents out to the database.
124713*/
124714static RtreeNode *nodeNew(Rtree *pRtree, RtreeNode *pParent){
124715  RtreeNode *pNode;
124716  pNode = (RtreeNode *)sqlite3_malloc(sizeof(RtreeNode) + pRtree->iNodeSize);
124717  if( pNode ){
124718    memset(pNode, 0, sizeof(RtreeNode) + pRtree->iNodeSize);
124719    pNode->zData = (u8 *)&pNode[1];
124720    pNode->nRef = 1;
124721    pNode->pParent = pParent;
124722    pNode->isDirty = 1;
124723    nodeReference(pParent);
124724  }
124725  return pNode;
124726}
124727
124728/*
124729** Obtain a reference to an r-tree node.
124730*/
124731static int
124732nodeAcquire(
124733  Rtree *pRtree,             /* R-tree structure */
124734  i64 iNode,                 /* Node number to load */
124735  RtreeNode *pParent,        /* Either the parent node or NULL */
124736  RtreeNode **ppNode         /* OUT: Acquired node */
124737){
124738  int rc;
124739  int rc2 = SQLITE_OK;
124740  RtreeNode *pNode;
124741
124742  /* Check if the requested node is already in the hash table. If so,
124743  ** increase its reference count and return it.
124744  */
124745  if( (pNode = nodeHashLookup(pRtree, iNode)) ){
124746    assert( !pParent || !pNode->pParent || pNode->pParent==pParent );
124747    if( pParent && !pNode->pParent ){
124748      nodeReference(pParent);
124749      pNode->pParent = pParent;
124750    }
124751    pNode->nRef++;
124752    *ppNode = pNode;
124753    return SQLITE_OK;
124754  }
124755
124756  sqlite3_bind_int64(pRtree->pReadNode, 1, iNode);
124757  rc = sqlite3_step(pRtree->pReadNode);
124758  if( rc==SQLITE_ROW ){
124759    const u8 *zBlob = sqlite3_column_blob(pRtree->pReadNode, 0);
124760    if( pRtree->iNodeSize==sqlite3_column_bytes(pRtree->pReadNode, 0) ){
124761      pNode = (RtreeNode *)sqlite3_malloc(sizeof(RtreeNode)+pRtree->iNodeSize);
124762      if( !pNode ){
124763        rc2 = SQLITE_NOMEM;
124764      }else{
124765        pNode->pParent = pParent;
124766        pNode->zData = (u8 *)&pNode[1];
124767        pNode->nRef = 1;
124768        pNode->iNode = iNode;
124769        pNode->isDirty = 0;
124770        pNode->pNext = 0;
124771        memcpy(pNode->zData, zBlob, pRtree->iNodeSize);
124772        nodeReference(pParent);
124773      }
124774    }
124775  }
124776  rc = sqlite3_reset(pRtree->pReadNode);
124777  if( rc==SQLITE_OK ) rc = rc2;
124778
124779  /* If the root node was just loaded, set pRtree->iDepth to the height
124780  ** of the r-tree structure. A height of zero means all data is stored on
124781  ** the root node. A height of one means the children of the root node
124782  ** are the leaves, and so on. If the depth as specified on the root node
124783  ** is greater than RTREE_MAX_DEPTH, the r-tree structure must be corrupt.
124784  */
124785  if( pNode && iNode==1 ){
124786    pRtree->iDepth = readInt16(pNode->zData);
124787    if( pRtree->iDepth>RTREE_MAX_DEPTH ){
124788      rc = SQLITE_CORRUPT;
124789    }
124790  }
124791
124792  /* If no error has occurred so far, check if the "number of entries"
124793  ** field on the node is too large. If so, set the return code to
124794  ** SQLITE_CORRUPT.
124795  */
124796  if( pNode && rc==SQLITE_OK ){
124797    if( NCELL(pNode)>((pRtree->iNodeSize-4)/pRtree->nBytesPerCell) ){
124798      rc = SQLITE_CORRUPT;
124799    }
124800  }
124801
124802  if( rc==SQLITE_OK ){
124803    if( pNode!=0 ){
124804      nodeHashInsert(pRtree, pNode);
124805    }else{
124806      rc = SQLITE_CORRUPT;
124807    }
124808    *ppNode = pNode;
124809  }else{
124810    sqlite3_free(pNode);
124811    *ppNode = 0;
124812  }
124813
124814  return rc;
124815}
124816
124817/*
124818** Overwrite cell iCell of node pNode with the contents of pCell.
124819*/
124820static void nodeOverwriteCell(
124821  Rtree *pRtree,
124822  RtreeNode *pNode,
124823  RtreeCell *pCell,
124824  int iCell
124825){
124826  int ii;
124827  u8 *p = &pNode->zData[4 + pRtree->nBytesPerCell*iCell];
124828  p += writeInt64(p, pCell->iRowid);
124829  for(ii=0; ii<(pRtree->nDim*2); ii++){
124830    p += writeCoord(p, &pCell->aCoord[ii]);
124831  }
124832  pNode->isDirty = 1;
124833}
124834
124835/*
124836** Remove cell the cell with index iCell from node pNode.
124837*/
124838static void nodeDeleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell){
124839  u8 *pDst = &pNode->zData[4 + pRtree->nBytesPerCell*iCell];
124840  u8 *pSrc = &pDst[pRtree->nBytesPerCell];
124841  int nByte = (NCELL(pNode) - iCell - 1) * pRtree->nBytesPerCell;
124842  memmove(pDst, pSrc, nByte);
124843  writeInt16(&pNode->zData[2], NCELL(pNode)-1);
124844  pNode->isDirty = 1;
124845}
124846
124847/*
124848** Insert the contents of cell pCell into node pNode. If the insert
124849** is successful, return SQLITE_OK.
124850**
124851** If there is not enough free space in pNode, return SQLITE_FULL.
124852*/
124853static int
124854nodeInsertCell(
124855  Rtree *pRtree,
124856  RtreeNode *pNode,
124857  RtreeCell *pCell
124858){
124859  int nCell;                    /* Current number of cells in pNode */
124860  int nMaxCell;                 /* Maximum number of cells for pNode */
124861
124862  nMaxCell = (pRtree->iNodeSize-4)/pRtree->nBytesPerCell;
124863  nCell = NCELL(pNode);
124864
124865  assert( nCell<=nMaxCell );
124866  if( nCell<nMaxCell ){
124867    nodeOverwriteCell(pRtree, pNode, pCell, nCell);
124868    writeInt16(&pNode->zData[2], nCell+1);
124869    pNode->isDirty = 1;
124870  }
124871
124872  return (nCell==nMaxCell);
124873}
124874
124875/*
124876** If the node is dirty, write it out to the database.
124877*/
124878static int
124879nodeWrite(Rtree *pRtree, RtreeNode *pNode){
124880  int rc = SQLITE_OK;
124881  if( pNode->isDirty ){
124882    sqlite3_stmt *p = pRtree->pWriteNode;
124883    if( pNode->iNode ){
124884      sqlite3_bind_int64(p, 1, pNode->iNode);
124885    }else{
124886      sqlite3_bind_null(p, 1);
124887    }
124888    sqlite3_bind_blob(p, 2, pNode->zData, pRtree->iNodeSize, SQLITE_STATIC);
124889    sqlite3_step(p);
124890    pNode->isDirty = 0;
124891    rc = sqlite3_reset(p);
124892    if( pNode->iNode==0 && rc==SQLITE_OK ){
124893      pNode->iNode = sqlite3_last_insert_rowid(pRtree->db);
124894      nodeHashInsert(pRtree, pNode);
124895    }
124896  }
124897  return rc;
124898}
124899
124900/*
124901** Release a reference to a node. If the node is dirty and the reference
124902** count drops to zero, the node data is written to the database.
124903*/
124904static int
124905nodeRelease(Rtree *pRtree, RtreeNode *pNode){
124906  int rc = SQLITE_OK;
124907  if( pNode ){
124908    assert( pNode->nRef>0 );
124909    pNode->nRef--;
124910    if( pNode->nRef==0 ){
124911      if( pNode->iNode==1 ){
124912        pRtree->iDepth = -1;
124913      }
124914      if( pNode->pParent ){
124915        rc = nodeRelease(pRtree, pNode->pParent);
124916      }
124917      if( rc==SQLITE_OK ){
124918        rc = nodeWrite(pRtree, pNode);
124919      }
124920      nodeHashDelete(pRtree, pNode);
124921      sqlite3_free(pNode);
124922    }
124923  }
124924  return rc;
124925}
124926
124927/*
124928** Return the 64-bit integer value associated with cell iCell of
124929** node pNode. If pNode is a leaf node, this is a rowid. If it is
124930** an internal node, then the 64-bit integer is a child page number.
124931*/
124932static i64 nodeGetRowid(
124933  Rtree *pRtree,
124934  RtreeNode *pNode,
124935  int iCell
124936){
124937  assert( iCell<NCELL(pNode) );
124938  return readInt64(&pNode->zData[4 + pRtree->nBytesPerCell*iCell]);
124939}
124940
124941/*
124942** Return coordinate iCoord from cell iCell in node pNode.
124943*/
124944static void nodeGetCoord(
124945  Rtree *pRtree,
124946  RtreeNode *pNode,
124947  int iCell,
124948  int iCoord,
124949  RtreeCoord *pCoord           /* Space to write result to */
124950){
124951  readCoord(&pNode->zData[12 + pRtree->nBytesPerCell*iCell + 4*iCoord], pCoord);
124952}
124953
124954/*
124955** Deserialize cell iCell of node pNode. Populate the structure pointed
124956** to by pCell with the results.
124957*/
124958static void nodeGetCell(
124959  Rtree *pRtree,
124960  RtreeNode *pNode,
124961  int iCell,
124962  RtreeCell *pCell
124963){
124964  int ii;
124965  pCell->iRowid = nodeGetRowid(pRtree, pNode, iCell);
124966  for(ii=0; ii<pRtree->nDim*2; ii++){
124967    nodeGetCoord(pRtree, pNode, iCell, ii, &pCell->aCoord[ii]);
124968  }
124969}
124970
124971
124972/* Forward declaration for the function that does the work of
124973** the virtual table module xCreate() and xConnect() methods.
124974*/
124975static int rtreeInit(
124976  sqlite3 *, void *, int, const char *const*, sqlite3_vtab **, char **, int
124977);
124978
124979/*
124980** Rtree virtual table module xCreate method.
124981*/
124982static int rtreeCreate(
124983  sqlite3 *db,
124984  void *pAux,
124985  int argc, const char *const*argv,
124986  sqlite3_vtab **ppVtab,
124987  char **pzErr
124988){
124989  return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 1);
124990}
124991
124992/*
124993** Rtree virtual table module xConnect method.
124994*/
124995static int rtreeConnect(
124996  sqlite3 *db,
124997  void *pAux,
124998  int argc, const char *const*argv,
124999  sqlite3_vtab **ppVtab,
125000  char **pzErr
125001){
125002  return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 0);
125003}
125004
125005/*
125006** Increment the r-tree reference count.
125007*/
125008static void rtreeReference(Rtree *pRtree){
125009  pRtree->nBusy++;
125010}
125011
125012/*
125013** Decrement the r-tree reference count. When the reference count reaches
125014** zero the structure is deleted.
125015*/
125016static void rtreeRelease(Rtree *pRtree){
125017  pRtree->nBusy--;
125018  if( pRtree->nBusy==0 ){
125019    sqlite3_finalize(pRtree->pReadNode);
125020    sqlite3_finalize(pRtree->pWriteNode);
125021    sqlite3_finalize(pRtree->pDeleteNode);
125022    sqlite3_finalize(pRtree->pReadRowid);
125023    sqlite3_finalize(pRtree->pWriteRowid);
125024    sqlite3_finalize(pRtree->pDeleteRowid);
125025    sqlite3_finalize(pRtree->pReadParent);
125026    sqlite3_finalize(pRtree->pWriteParent);
125027    sqlite3_finalize(pRtree->pDeleteParent);
125028    sqlite3_free(pRtree);
125029  }
125030}
125031
125032/*
125033** Rtree virtual table module xDisconnect method.
125034*/
125035static int rtreeDisconnect(sqlite3_vtab *pVtab){
125036  rtreeRelease((Rtree *)pVtab);
125037  return SQLITE_OK;
125038}
125039
125040/*
125041** Rtree virtual table module xDestroy method.
125042*/
125043static int rtreeDestroy(sqlite3_vtab *pVtab){
125044  Rtree *pRtree = (Rtree *)pVtab;
125045  int rc;
125046  char *zCreate = sqlite3_mprintf(
125047    "DROP TABLE '%q'.'%q_node';"
125048    "DROP TABLE '%q'.'%q_rowid';"
125049    "DROP TABLE '%q'.'%q_parent';",
125050    pRtree->zDb, pRtree->zName,
125051    pRtree->zDb, pRtree->zName,
125052    pRtree->zDb, pRtree->zName
125053  );
125054  if( !zCreate ){
125055    rc = SQLITE_NOMEM;
125056  }else{
125057    rc = sqlite3_exec(pRtree->db, zCreate, 0, 0, 0);
125058    sqlite3_free(zCreate);
125059  }
125060  if( rc==SQLITE_OK ){
125061    rtreeRelease(pRtree);
125062  }
125063
125064  return rc;
125065}
125066
125067/*
125068** Rtree virtual table module xOpen method.
125069*/
125070static int rtreeOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
125071  int rc = SQLITE_NOMEM;
125072  RtreeCursor *pCsr;
125073
125074  pCsr = (RtreeCursor *)sqlite3_malloc(sizeof(RtreeCursor));
125075  if( pCsr ){
125076    memset(pCsr, 0, sizeof(RtreeCursor));
125077    pCsr->base.pVtab = pVTab;
125078    rc = SQLITE_OK;
125079  }
125080  *ppCursor = (sqlite3_vtab_cursor *)pCsr;
125081
125082  return rc;
125083}
125084
125085
125086/*
125087** Free the RtreeCursor.aConstraint[] array and its contents.
125088*/
125089static void freeCursorConstraints(RtreeCursor *pCsr){
125090  if( pCsr->aConstraint ){
125091    int i;                        /* Used to iterate through constraint array */
125092    for(i=0; i<pCsr->nConstraint; i++){
125093      sqlite3_rtree_geometry *pGeom = pCsr->aConstraint[i].pGeom;
125094      if( pGeom ){
125095        if( pGeom->xDelUser ) pGeom->xDelUser(pGeom->pUser);
125096        sqlite3_free(pGeom);
125097      }
125098    }
125099    sqlite3_free(pCsr->aConstraint);
125100    pCsr->aConstraint = 0;
125101  }
125102}
125103
125104/*
125105** Rtree virtual table module xClose method.
125106*/
125107static int rtreeClose(sqlite3_vtab_cursor *cur){
125108  Rtree *pRtree = (Rtree *)(cur->pVtab);
125109  int rc;
125110  RtreeCursor *pCsr = (RtreeCursor *)cur;
125111  freeCursorConstraints(pCsr);
125112  rc = nodeRelease(pRtree, pCsr->pNode);
125113  sqlite3_free(pCsr);
125114  return rc;
125115}
125116
125117/*
125118** Rtree virtual table module xEof method.
125119**
125120** Return non-zero if the cursor does not currently point to a valid
125121** record (i.e if the scan has finished), or zero otherwise.
125122*/
125123static int rtreeEof(sqlite3_vtab_cursor *cur){
125124  RtreeCursor *pCsr = (RtreeCursor *)cur;
125125  return (pCsr->pNode==0);
125126}
125127
125128/*
125129** The r-tree constraint passed as the second argument to this function is
125130** guaranteed to be a MATCH constraint.
125131*/
125132static int testRtreeGeom(
125133  Rtree *pRtree,                  /* R-Tree object */
125134  RtreeConstraint *pConstraint,   /* MATCH constraint to test */
125135  RtreeCell *pCell,               /* Cell to test */
125136  int *pbRes                      /* OUT: Test result */
125137){
125138  int i;
125139  double aCoord[RTREE_MAX_DIMENSIONS*2];
125140  int nCoord = pRtree->nDim*2;
125141
125142  assert( pConstraint->op==RTREE_MATCH );
125143  assert( pConstraint->pGeom );
125144
125145  for(i=0; i<nCoord; i++){
125146    aCoord[i] = DCOORD(pCell->aCoord[i]);
125147  }
125148  return pConstraint->xGeom(pConstraint->pGeom, nCoord, aCoord, pbRes);
125149}
125150
125151/*
125152** Cursor pCursor currently points to a cell in a non-leaf page.
125153** Set *pbEof to true if the sub-tree headed by the cell is filtered
125154** (excluded) by the constraints in the pCursor->aConstraint[]
125155** array, or false otherwise.
125156**
125157** Return SQLITE_OK if successful or an SQLite error code if an error
125158** occurs within a geometry callback.
125159*/
125160static int testRtreeCell(Rtree *pRtree, RtreeCursor *pCursor, int *pbEof){
125161  RtreeCell cell;
125162  int ii;
125163  int bRes = 0;
125164  int rc = SQLITE_OK;
125165
125166  nodeGetCell(pRtree, pCursor->pNode, pCursor->iCell, &cell);
125167  for(ii=0; bRes==0 && ii<pCursor->nConstraint; ii++){
125168    RtreeConstraint *p = &pCursor->aConstraint[ii];
125169    double cell_min = DCOORD(cell.aCoord[(p->iCoord>>1)*2]);
125170    double cell_max = DCOORD(cell.aCoord[(p->iCoord>>1)*2+1]);
125171
125172    assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE
125173        || p->op==RTREE_GT || p->op==RTREE_EQ || p->op==RTREE_MATCH
125174    );
125175
125176    switch( p->op ){
125177      case RTREE_LE: case RTREE_LT:
125178        bRes = p->rValue<cell_min;
125179        break;
125180
125181      case RTREE_GE: case RTREE_GT:
125182        bRes = p->rValue>cell_max;
125183        break;
125184
125185      case RTREE_EQ:
125186        bRes = (p->rValue>cell_max || p->rValue<cell_min);
125187        break;
125188
125189      default: {
125190        assert( p->op==RTREE_MATCH );
125191        rc = testRtreeGeom(pRtree, p, &cell, &bRes);
125192        bRes = !bRes;
125193        break;
125194      }
125195    }
125196  }
125197
125198  *pbEof = bRes;
125199  return rc;
125200}
125201
125202/*
125203** Test if the cell that cursor pCursor currently points to
125204** would be filtered (excluded) by the constraints in the
125205** pCursor->aConstraint[] array. If so, set *pbEof to true before
125206** returning. If the cell is not filtered (excluded) by the constraints,
125207** set pbEof to zero.
125208**
125209** Return SQLITE_OK if successful or an SQLite error code if an error
125210** occurs within a geometry callback.
125211**
125212** This function assumes that the cell is part of a leaf node.
125213*/
125214static int testRtreeEntry(Rtree *pRtree, RtreeCursor *pCursor, int *pbEof){
125215  RtreeCell cell;
125216  int ii;
125217  *pbEof = 0;
125218
125219  nodeGetCell(pRtree, pCursor->pNode, pCursor->iCell, &cell);
125220  for(ii=0; ii<pCursor->nConstraint; ii++){
125221    RtreeConstraint *p = &pCursor->aConstraint[ii];
125222    double coord = DCOORD(cell.aCoord[p->iCoord]);
125223    int res;
125224    assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE
125225        || p->op==RTREE_GT || p->op==RTREE_EQ || p->op==RTREE_MATCH
125226    );
125227    switch( p->op ){
125228      case RTREE_LE: res = (coord<=p->rValue); break;
125229      case RTREE_LT: res = (coord<p->rValue);  break;
125230      case RTREE_GE: res = (coord>=p->rValue); break;
125231      case RTREE_GT: res = (coord>p->rValue);  break;
125232      case RTREE_EQ: res = (coord==p->rValue); break;
125233      default: {
125234        int rc;
125235        assert( p->op==RTREE_MATCH );
125236        rc = testRtreeGeom(pRtree, p, &cell, &res);
125237        if( rc!=SQLITE_OK ){
125238          return rc;
125239        }
125240        break;
125241      }
125242    }
125243
125244    if( !res ){
125245      *pbEof = 1;
125246      return SQLITE_OK;
125247    }
125248  }
125249
125250  return SQLITE_OK;
125251}
125252
125253/*
125254** Cursor pCursor currently points at a node that heads a sub-tree of
125255** height iHeight (if iHeight==0, then the node is a leaf). Descend
125256** to point to the left-most cell of the sub-tree that matches the
125257** configured constraints.
125258*/
125259static int descendToCell(
125260  Rtree *pRtree,
125261  RtreeCursor *pCursor,
125262  int iHeight,
125263  int *pEof                 /* OUT: Set to true if cannot descend */
125264){
125265  int isEof;
125266  int rc;
125267  int ii;
125268  RtreeNode *pChild;
125269  sqlite3_int64 iRowid;
125270
125271  RtreeNode *pSavedNode = pCursor->pNode;
125272  int iSavedCell = pCursor->iCell;
125273
125274  assert( iHeight>=0 );
125275
125276  if( iHeight==0 ){
125277    rc = testRtreeEntry(pRtree, pCursor, &isEof);
125278  }else{
125279    rc = testRtreeCell(pRtree, pCursor, &isEof);
125280  }
125281  if( rc!=SQLITE_OK || isEof || iHeight==0 ){
125282    goto descend_to_cell_out;
125283  }
125284
125285  iRowid = nodeGetRowid(pRtree, pCursor->pNode, pCursor->iCell);
125286  rc = nodeAcquire(pRtree, iRowid, pCursor->pNode, &pChild);
125287  if( rc!=SQLITE_OK ){
125288    goto descend_to_cell_out;
125289  }
125290
125291  nodeRelease(pRtree, pCursor->pNode);
125292  pCursor->pNode = pChild;
125293  isEof = 1;
125294  for(ii=0; isEof && ii<NCELL(pChild); ii++){
125295    pCursor->iCell = ii;
125296    rc = descendToCell(pRtree, pCursor, iHeight-1, &isEof);
125297    if( rc!=SQLITE_OK ){
125298      goto descend_to_cell_out;
125299    }
125300  }
125301
125302  if( isEof ){
125303    assert( pCursor->pNode==pChild );
125304    nodeReference(pSavedNode);
125305    nodeRelease(pRtree, pChild);
125306    pCursor->pNode = pSavedNode;
125307    pCursor->iCell = iSavedCell;
125308  }
125309
125310descend_to_cell_out:
125311  *pEof = isEof;
125312  return rc;
125313}
125314
125315/*
125316** One of the cells in node pNode is guaranteed to have a 64-bit
125317** integer value equal to iRowid. Return the index of this cell.
125318*/
125319static int nodeRowidIndex(
125320  Rtree *pRtree,
125321  RtreeNode *pNode,
125322  i64 iRowid,
125323  int *piIndex
125324){
125325  int ii;
125326  int nCell = NCELL(pNode);
125327  for(ii=0; ii<nCell; ii++){
125328    if( nodeGetRowid(pRtree, pNode, ii)==iRowid ){
125329      *piIndex = ii;
125330      return SQLITE_OK;
125331    }
125332  }
125333  return SQLITE_CORRUPT;
125334}
125335
125336/*
125337** Return the index of the cell containing a pointer to node pNode
125338** in its parent. If pNode is the root node, return -1.
125339*/
125340static int nodeParentIndex(Rtree *pRtree, RtreeNode *pNode, int *piIndex){
125341  RtreeNode *pParent = pNode->pParent;
125342  if( pParent ){
125343    return nodeRowidIndex(pRtree, pParent, pNode->iNode, piIndex);
125344  }
125345  *piIndex = -1;
125346  return SQLITE_OK;
125347}
125348
125349/*
125350** Rtree virtual table module xNext method.
125351*/
125352static int rtreeNext(sqlite3_vtab_cursor *pVtabCursor){
125353  Rtree *pRtree = (Rtree *)(pVtabCursor->pVtab);
125354  RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
125355  int rc = SQLITE_OK;
125356
125357  /* RtreeCursor.pNode must not be NULL. If is is NULL, then this cursor is
125358  ** already at EOF. It is against the rules to call the xNext() method of
125359  ** a cursor that has already reached EOF.
125360  */
125361  assert( pCsr->pNode );
125362
125363  if( pCsr->iStrategy==1 ){
125364    /* This "scan" is a direct lookup by rowid. There is no next entry. */
125365    nodeRelease(pRtree, pCsr->pNode);
125366    pCsr->pNode = 0;
125367  }else{
125368    /* Move to the next entry that matches the configured constraints. */
125369    int iHeight = 0;
125370    while( pCsr->pNode ){
125371      RtreeNode *pNode = pCsr->pNode;
125372      int nCell = NCELL(pNode);
125373      for(pCsr->iCell++; pCsr->iCell<nCell; pCsr->iCell++){
125374        int isEof;
125375        rc = descendToCell(pRtree, pCsr, iHeight, &isEof);
125376        if( rc!=SQLITE_OK || !isEof ){
125377          return rc;
125378        }
125379      }
125380      pCsr->pNode = pNode->pParent;
125381      rc = nodeParentIndex(pRtree, pNode, &pCsr->iCell);
125382      if( rc!=SQLITE_OK ){
125383        return rc;
125384      }
125385      nodeReference(pCsr->pNode);
125386      nodeRelease(pRtree, pNode);
125387      iHeight++;
125388    }
125389  }
125390
125391  return rc;
125392}
125393
125394/*
125395** Rtree virtual table module xRowid method.
125396*/
125397static int rtreeRowid(sqlite3_vtab_cursor *pVtabCursor, sqlite_int64 *pRowid){
125398  Rtree *pRtree = (Rtree *)pVtabCursor->pVtab;
125399  RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
125400
125401  assert(pCsr->pNode);
125402  *pRowid = nodeGetRowid(pRtree, pCsr->pNode, pCsr->iCell);
125403
125404  return SQLITE_OK;
125405}
125406
125407/*
125408** Rtree virtual table module xColumn method.
125409*/
125410static int rtreeColumn(sqlite3_vtab_cursor *cur, sqlite3_context *ctx, int i){
125411  Rtree *pRtree = (Rtree *)cur->pVtab;
125412  RtreeCursor *pCsr = (RtreeCursor *)cur;
125413
125414  if( i==0 ){
125415    i64 iRowid = nodeGetRowid(pRtree, pCsr->pNode, pCsr->iCell);
125416    sqlite3_result_int64(ctx, iRowid);
125417  }else{
125418    RtreeCoord c;
125419    nodeGetCoord(pRtree, pCsr->pNode, pCsr->iCell, i-1, &c);
125420    if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
125421      sqlite3_result_double(ctx, c.f);
125422    }else{
125423      assert( pRtree->eCoordType==RTREE_COORD_INT32 );
125424      sqlite3_result_int(ctx, c.i);
125425    }
125426  }
125427
125428  return SQLITE_OK;
125429}
125430
125431/*
125432** Use nodeAcquire() to obtain the leaf node containing the record with
125433** rowid iRowid. If successful, set *ppLeaf to point to the node and
125434** return SQLITE_OK. If there is no such record in the table, set
125435** *ppLeaf to 0 and return SQLITE_OK. If an error occurs, set *ppLeaf
125436** to zero and return an SQLite error code.
125437*/
125438static int findLeafNode(Rtree *pRtree, i64 iRowid, RtreeNode **ppLeaf){
125439  int rc;
125440  *ppLeaf = 0;
125441  sqlite3_bind_int64(pRtree->pReadRowid, 1, iRowid);
125442  if( sqlite3_step(pRtree->pReadRowid)==SQLITE_ROW ){
125443    i64 iNode = sqlite3_column_int64(pRtree->pReadRowid, 0);
125444    rc = nodeAcquire(pRtree, iNode, 0, ppLeaf);
125445    sqlite3_reset(pRtree->pReadRowid);
125446  }else{
125447    rc = sqlite3_reset(pRtree->pReadRowid);
125448  }
125449  return rc;
125450}
125451
125452/*
125453** This function is called to configure the RtreeConstraint object passed
125454** as the second argument for a MATCH constraint. The value passed as the
125455** first argument to this function is the right-hand operand to the MATCH
125456** operator.
125457*/
125458static int deserializeGeometry(sqlite3_value *pValue, RtreeConstraint *pCons){
125459  RtreeMatchArg *p;
125460  sqlite3_rtree_geometry *pGeom;
125461  int nBlob;
125462
125463  /* Check that value is actually a blob. */
125464  if( !sqlite3_value_type(pValue)==SQLITE_BLOB ) return SQLITE_ERROR;
125465
125466  /* Check that the blob is roughly the right size. */
125467  nBlob = sqlite3_value_bytes(pValue);
125468  if( nBlob<(int)sizeof(RtreeMatchArg)
125469   || ((nBlob-sizeof(RtreeMatchArg))%sizeof(double))!=0
125470  ){
125471    return SQLITE_ERROR;
125472  }
125473
125474  pGeom = (sqlite3_rtree_geometry *)sqlite3_malloc(
125475      sizeof(sqlite3_rtree_geometry) + nBlob
125476  );
125477  if( !pGeom ) return SQLITE_NOMEM;
125478  memset(pGeom, 0, sizeof(sqlite3_rtree_geometry));
125479  p = (RtreeMatchArg *)&pGeom[1];
125480
125481  memcpy(p, sqlite3_value_blob(pValue), nBlob);
125482  if( p->magic!=RTREE_GEOMETRY_MAGIC
125483   || nBlob!=(int)(sizeof(RtreeMatchArg) + (p->nParam-1)*sizeof(double))
125484  ){
125485    sqlite3_free(pGeom);
125486    return SQLITE_ERROR;
125487  }
125488
125489  pGeom->pContext = p->pContext;
125490  pGeom->nParam = p->nParam;
125491  pGeom->aParam = p->aParam;
125492
125493  pCons->xGeom = p->xGeom;
125494  pCons->pGeom = pGeom;
125495  return SQLITE_OK;
125496}
125497
125498/*
125499** Rtree virtual table module xFilter method.
125500*/
125501static int rtreeFilter(
125502  sqlite3_vtab_cursor *pVtabCursor,
125503  int idxNum, const char *idxStr,
125504  int argc, sqlite3_value **argv
125505){
125506  Rtree *pRtree = (Rtree *)pVtabCursor->pVtab;
125507  RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
125508
125509  RtreeNode *pRoot = 0;
125510  int ii;
125511  int rc = SQLITE_OK;
125512
125513  rtreeReference(pRtree);
125514
125515  freeCursorConstraints(pCsr);
125516  pCsr->iStrategy = idxNum;
125517
125518  if( idxNum==1 ){
125519    /* Special case - lookup by rowid. */
125520    RtreeNode *pLeaf;        /* Leaf on which the required cell resides */
125521    i64 iRowid = sqlite3_value_int64(argv[0]);
125522    rc = findLeafNode(pRtree, iRowid, &pLeaf);
125523    pCsr->pNode = pLeaf;
125524    if( pLeaf ){
125525      assert( rc==SQLITE_OK );
125526      rc = nodeRowidIndex(pRtree, pLeaf, iRowid, &pCsr->iCell);
125527    }
125528  }else{
125529    /* Normal case - r-tree scan. Set up the RtreeCursor.aConstraint array
125530    ** with the configured constraints.
125531    */
125532    if( argc>0 ){
125533      pCsr->aConstraint = sqlite3_malloc(sizeof(RtreeConstraint)*argc);
125534      pCsr->nConstraint = argc;
125535      if( !pCsr->aConstraint ){
125536        rc = SQLITE_NOMEM;
125537      }else{
125538        memset(pCsr->aConstraint, 0, sizeof(RtreeConstraint)*argc);
125539        assert( (idxStr==0 && argc==0) || (int)strlen(idxStr)==argc*2 );
125540        for(ii=0; ii<argc; ii++){
125541          RtreeConstraint *p = &pCsr->aConstraint[ii];
125542          p->op = idxStr[ii*2];
125543          p->iCoord = idxStr[ii*2+1]-'a';
125544          if( p->op==RTREE_MATCH ){
125545            /* A MATCH operator. The right-hand-side must be a blob that
125546            ** can be cast into an RtreeMatchArg object. One created using
125547            ** an sqlite3_rtree_geometry_callback() SQL user function.
125548            */
125549            rc = deserializeGeometry(argv[ii], p);
125550            if( rc!=SQLITE_OK ){
125551              break;
125552            }
125553          }else{
125554            p->rValue = sqlite3_value_double(argv[ii]);
125555          }
125556        }
125557      }
125558    }
125559
125560    if( rc==SQLITE_OK ){
125561      pCsr->pNode = 0;
125562      rc = nodeAcquire(pRtree, 1, 0, &pRoot);
125563    }
125564    if( rc==SQLITE_OK ){
125565      int isEof = 1;
125566      int nCell = NCELL(pRoot);
125567      pCsr->pNode = pRoot;
125568      for(pCsr->iCell=0; rc==SQLITE_OK && pCsr->iCell<nCell; pCsr->iCell++){
125569        assert( pCsr->pNode==pRoot );
125570        rc = descendToCell(pRtree, pCsr, pRtree->iDepth, &isEof);
125571        if( !isEof ){
125572          break;
125573        }
125574      }
125575      if( rc==SQLITE_OK && isEof ){
125576        assert( pCsr->pNode==pRoot );
125577        nodeRelease(pRtree, pRoot);
125578        pCsr->pNode = 0;
125579      }
125580      assert( rc!=SQLITE_OK || !pCsr->pNode || pCsr->iCell<NCELL(pCsr->pNode) );
125581    }
125582  }
125583
125584  rtreeRelease(pRtree);
125585  return rc;
125586}
125587
125588/*
125589** Rtree virtual table module xBestIndex method. There are three
125590** table scan strategies to choose from (in order from most to
125591** least desirable):
125592**
125593**   idxNum     idxStr        Strategy
125594**   ------------------------------------------------
125595**     1        Unused        Direct lookup by rowid.
125596**     2        See below     R-tree query or full-table scan.
125597**   ------------------------------------------------
125598**
125599** If strategy 1 is used, then idxStr is not meaningful. If strategy
125600** 2 is used, idxStr is formatted to contain 2 bytes for each
125601** constraint used. The first two bytes of idxStr correspond to
125602** the constraint in sqlite3_index_info.aConstraintUsage[] with
125603** (argvIndex==1) etc.
125604**
125605** The first of each pair of bytes in idxStr identifies the constraint
125606** operator as follows:
125607**
125608**   Operator    Byte Value
125609**   ----------------------
125610**      =        0x41 ('A')
125611**     <=        0x42 ('B')
125612**      <        0x43 ('C')
125613**     >=        0x44 ('D')
125614**      >        0x45 ('E')
125615**   MATCH       0x46 ('F')
125616**   ----------------------
125617**
125618** The second of each pair of bytes identifies the coordinate column
125619** to which the constraint applies. The leftmost coordinate column
125620** is 'a', the second from the left 'b' etc.
125621*/
125622static int rtreeBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){
125623  int rc = SQLITE_OK;
125624  int ii;
125625
125626  int iIdx = 0;
125627  char zIdxStr[RTREE_MAX_DIMENSIONS*8+1];
125628  memset(zIdxStr, 0, sizeof(zIdxStr));
125629  UNUSED_PARAMETER(tab);
125630
125631  assert( pIdxInfo->idxStr==0 );
125632  for(ii=0; ii<pIdxInfo->nConstraint && iIdx<(int)(sizeof(zIdxStr)-1); ii++){
125633    struct sqlite3_index_constraint *p = &pIdxInfo->aConstraint[ii];
125634
125635    if( p->usable && p->iColumn==0 && p->op==SQLITE_INDEX_CONSTRAINT_EQ ){
125636      /* We have an equality constraint on the rowid. Use strategy 1. */
125637      int jj;
125638      for(jj=0; jj<ii; jj++){
125639        pIdxInfo->aConstraintUsage[jj].argvIndex = 0;
125640        pIdxInfo->aConstraintUsage[jj].omit = 0;
125641      }
125642      pIdxInfo->idxNum = 1;
125643      pIdxInfo->aConstraintUsage[ii].argvIndex = 1;
125644      pIdxInfo->aConstraintUsage[jj].omit = 1;
125645
125646      /* This strategy involves a two rowid lookups on an B-Tree structures
125647      ** and then a linear search of an R-Tree node. This should be
125648      ** considered almost as quick as a direct rowid lookup (for which
125649      ** sqlite uses an internal cost of 0.0).
125650      */
125651      pIdxInfo->estimatedCost = 10.0;
125652      return SQLITE_OK;
125653    }
125654
125655    if( p->usable && (p->iColumn>0 || p->op==SQLITE_INDEX_CONSTRAINT_MATCH) ){
125656      u8 op;
125657      switch( p->op ){
125658        case SQLITE_INDEX_CONSTRAINT_EQ: op = RTREE_EQ; break;
125659        case SQLITE_INDEX_CONSTRAINT_GT: op = RTREE_GT; break;
125660        case SQLITE_INDEX_CONSTRAINT_LE: op = RTREE_LE; break;
125661        case SQLITE_INDEX_CONSTRAINT_LT: op = RTREE_LT; break;
125662        case SQLITE_INDEX_CONSTRAINT_GE: op = RTREE_GE; break;
125663        default:
125664          assert( p->op==SQLITE_INDEX_CONSTRAINT_MATCH );
125665          op = RTREE_MATCH;
125666          break;
125667      }
125668      zIdxStr[iIdx++] = op;
125669      zIdxStr[iIdx++] = p->iColumn - 1 + 'a';
125670      pIdxInfo->aConstraintUsage[ii].argvIndex = (iIdx/2);
125671      pIdxInfo->aConstraintUsage[ii].omit = 1;
125672    }
125673  }
125674
125675  pIdxInfo->idxNum = 2;
125676  pIdxInfo->needToFreeIdxStr = 1;
125677  if( iIdx>0 && 0==(pIdxInfo->idxStr = sqlite3_mprintf("%s", zIdxStr)) ){
125678    return SQLITE_NOMEM;
125679  }
125680  assert( iIdx>=0 );
125681  pIdxInfo->estimatedCost = (2000000.0 / (double)(iIdx + 1));
125682  return rc;
125683}
125684
125685/*
125686** Return the N-dimensional volumn of the cell stored in *p.
125687*/
125688static float cellArea(Rtree *pRtree, RtreeCell *p){
125689  float area = 1.0;
125690  int ii;
125691  for(ii=0; ii<(pRtree->nDim*2); ii+=2){
125692    area = area * (DCOORD(p->aCoord[ii+1]) - DCOORD(p->aCoord[ii]));
125693  }
125694  return area;
125695}
125696
125697/*
125698** Return the margin length of cell p. The margin length is the sum
125699** of the objects size in each dimension.
125700*/
125701static float cellMargin(Rtree *pRtree, RtreeCell *p){
125702  float margin = 0.0;
125703  int ii;
125704  for(ii=0; ii<(pRtree->nDim*2); ii+=2){
125705    margin += (DCOORD(p->aCoord[ii+1]) - DCOORD(p->aCoord[ii]));
125706  }
125707  return margin;
125708}
125709
125710/*
125711** Store the union of cells p1 and p2 in p1.
125712*/
125713static void cellUnion(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){
125714  int ii;
125715  if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
125716    for(ii=0; ii<(pRtree->nDim*2); ii+=2){
125717      p1->aCoord[ii].f = MIN(p1->aCoord[ii].f, p2->aCoord[ii].f);
125718      p1->aCoord[ii+1].f = MAX(p1->aCoord[ii+1].f, p2->aCoord[ii+1].f);
125719    }
125720  }else{
125721    for(ii=0; ii<(pRtree->nDim*2); ii+=2){
125722      p1->aCoord[ii].i = MIN(p1->aCoord[ii].i, p2->aCoord[ii].i);
125723      p1->aCoord[ii+1].i = MAX(p1->aCoord[ii+1].i, p2->aCoord[ii+1].i);
125724    }
125725  }
125726}
125727
125728/*
125729** Return true if the area covered by p2 is a subset of the area covered
125730** by p1. False otherwise.
125731*/
125732static int cellContains(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){
125733  int ii;
125734  int isInt = (pRtree->eCoordType==RTREE_COORD_INT32);
125735  for(ii=0; ii<(pRtree->nDim*2); ii+=2){
125736    RtreeCoord *a1 = &p1->aCoord[ii];
125737    RtreeCoord *a2 = &p2->aCoord[ii];
125738    if( (!isInt && (a2[0].f<a1[0].f || a2[1].f>a1[1].f))
125739     || ( isInt && (a2[0].i<a1[0].i || a2[1].i>a1[1].i))
125740    ){
125741      return 0;
125742    }
125743  }
125744  return 1;
125745}
125746
125747/*
125748** Return the amount cell p would grow by if it were unioned with pCell.
125749*/
125750static float cellGrowth(Rtree *pRtree, RtreeCell *p, RtreeCell *pCell){
125751  float area;
125752  RtreeCell cell;
125753  memcpy(&cell, p, sizeof(RtreeCell));
125754  area = cellArea(pRtree, &cell);
125755  cellUnion(pRtree, &cell, pCell);
125756  return (cellArea(pRtree, &cell)-area);
125757}
125758
125759#if VARIANT_RSTARTREE_CHOOSESUBTREE || VARIANT_RSTARTREE_SPLIT
125760static float cellOverlap(
125761  Rtree *pRtree,
125762  RtreeCell *p,
125763  RtreeCell *aCell,
125764  int nCell,
125765  int iExclude
125766){
125767  int ii;
125768  float overlap = 0.0;
125769  for(ii=0; ii<nCell; ii++){
125770#if VARIANT_RSTARTREE_CHOOSESUBTREE
125771    if( ii!=iExclude )
125772#else
125773    assert( iExclude==-1 );
125774    UNUSED_PARAMETER(iExclude);
125775#endif
125776    {
125777      int jj;
125778      float o = 1.0;
125779      for(jj=0; jj<(pRtree->nDim*2); jj+=2){
125780        double x1;
125781        double x2;
125782
125783        x1 = MAX(DCOORD(p->aCoord[jj]), DCOORD(aCell[ii].aCoord[jj]));
125784        x2 = MIN(DCOORD(p->aCoord[jj+1]), DCOORD(aCell[ii].aCoord[jj+1]));
125785
125786        if( x2<x1 ){
125787          o = 0.0;
125788          break;
125789        }else{
125790          o = o * (x2-x1);
125791        }
125792      }
125793      overlap += o;
125794    }
125795  }
125796  return overlap;
125797}
125798#endif
125799
125800#if VARIANT_RSTARTREE_CHOOSESUBTREE
125801static float cellOverlapEnlargement(
125802  Rtree *pRtree,
125803  RtreeCell *p,
125804  RtreeCell *pInsert,
125805  RtreeCell *aCell,
125806  int nCell,
125807  int iExclude
125808){
125809  float before;
125810  float after;
125811  before = cellOverlap(pRtree, p, aCell, nCell, iExclude);
125812  cellUnion(pRtree, p, pInsert);
125813  after = cellOverlap(pRtree, p, aCell, nCell, iExclude);
125814  return after-before;
125815}
125816#endif
125817
125818
125819/*
125820** This function implements the ChooseLeaf algorithm from Gutman[84].
125821** ChooseSubTree in r*tree terminology.
125822*/
125823static int ChooseLeaf(
125824  Rtree *pRtree,               /* Rtree table */
125825  RtreeCell *pCell,            /* Cell to insert into rtree */
125826  int iHeight,                 /* Height of sub-tree rooted at pCell */
125827  RtreeNode **ppLeaf           /* OUT: Selected leaf page */
125828){
125829  int rc;
125830  int ii;
125831  RtreeNode *pNode;
125832  rc = nodeAcquire(pRtree, 1, 0, &pNode);
125833
125834  for(ii=0; rc==SQLITE_OK && ii<(pRtree->iDepth-iHeight); ii++){
125835    int iCell;
125836    sqlite3_int64 iBest;
125837
125838    float fMinGrowth;
125839    float fMinArea;
125840    float fMinOverlap;
125841
125842    int nCell = NCELL(pNode);
125843    RtreeCell cell;
125844    RtreeNode *pChild;
125845
125846    RtreeCell *aCell = 0;
125847
125848#if VARIANT_RSTARTREE_CHOOSESUBTREE
125849    if( ii==(pRtree->iDepth-1) ){
125850      int jj;
125851      aCell = sqlite3_malloc(sizeof(RtreeCell)*nCell);
125852      if( !aCell ){
125853        rc = SQLITE_NOMEM;
125854        nodeRelease(pRtree, pNode);
125855        pNode = 0;
125856        continue;
125857      }
125858      for(jj=0; jj<nCell; jj++){
125859        nodeGetCell(pRtree, pNode, jj, &aCell[jj]);
125860      }
125861    }
125862#endif
125863
125864    /* Select the child node which will be enlarged the least if pCell
125865    ** is inserted into it. Resolve ties by choosing the entry with
125866    ** the smallest area.
125867    */
125868    for(iCell=0; iCell<nCell; iCell++){
125869      int bBest = 0;
125870      float growth;
125871      float area;
125872      float overlap = 0.0;
125873      nodeGetCell(pRtree, pNode, iCell, &cell);
125874      growth = cellGrowth(pRtree, &cell, pCell);
125875      area = cellArea(pRtree, &cell);
125876
125877#if VARIANT_RSTARTREE_CHOOSESUBTREE
125878      if( ii==(pRtree->iDepth-1) ){
125879        overlap = cellOverlapEnlargement(pRtree,&cell,pCell,aCell,nCell,iCell);
125880      }
125881      if( (iCell==0)
125882       || (overlap<fMinOverlap)
125883       || (overlap==fMinOverlap && growth<fMinGrowth)
125884       || (overlap==fMinOverlap && growth==fMinGrowth && area<fMinArea)
125885      ){
125886        bBest = 1;
125887      }
125888#else
125889      if( iCell==0||growth<fMinGrowth||(growth==fMinGrowth && area<fMinArea) ){
125890        bBest = 1;
125891      }
125892#endif
125893      if( bBest ){
125894        fMinOverlap = overlap;
125895        fMinGrowth = growth;
125896        fMinArea = area;
125897        iBest = cell.iRowid;
125898      }
125899    }
125900
125901    sqlite3_free(aCell);
125902    rc = nodeAcquire(pRtree, iBest, pNode, &pChild);
125903    nodeRelease(pRtree, pNode);
125904    pNode = pChild;
125905  }
125906
125907  *ppLeaf = pNode;
125908  return rc;
125909}
125910
125911/*
125912** A cell with the same content as pCell has just been inserted into
125913** the node pNode. This function updates the bounding box cells in
125914** all ancestor elements.
125915*/
125916static int AdjustTree(
125917  Rtree *pRtree,                    /* Rtree table */
125918  RtreeNode *pNode,                 /* Adjust ancestry of this node. */
125919  RtreeCell *pCell                  /* This cell was just inserted */
125920){
125921  RtreeNode *p = pNode;
125922  while( p->pParent ){
125923    RtreeNode *pParent = p->pParent;
125924    RtreeCell cell;
125925    int iCell;
125926
125927    if( nodeParentIndex(pRtree, p, &iCell) ){
125928      return SQLITE_CORRUPT;
125929    }
125930
125931    nodeGetCell(pRtree, pParent, iCell, &cell);
125932    if( !cellContains(pRtree, &cell, pCell) ){
125933      cellUnion(pRtree, &cell, pCell);
125934      nodeOverwriteCell(pRtree, pParent, &cell, iCell);
125935    }
125936
125937    p = pParent;
125938  }
125939  return SQLITE_OK;
125940}
125941
125942/*
125943** Write mapping (iRowid->iNode) to the <rtree>_rowid table.
125944*/
125945static int rowidWrite(Rtree *pRtree, sqlite3_int64 iRowid, sqlite3_int64 iNode){
125946  sqlite3_bind_int64(pRtree->pWriteRowid, 1, iRowid);
125947  sqlite3_bind_int64(pRtree->pWriteRowid, 2, iNode);
125948  sqlite3_step(pRtree->pWriteRowid);
125949  return sqlite3_reset(pRtree->pWriteRowid);
125950}
125951
125952/*
125953** Write mapping (iNode->iPar) to the <rtree>_parent table.
125954*/
125955static int parentWrite(Rtree *pRtree, sqlite3_int64 iNode, sqlite3_int64 iPar){
125956  sqlite3_bind_int64(pRtree->pWriteParent, 1, iNode);
125957  sqlite3_bind_int64(pRtree->pWriteParent, 2, iPar);
125958  sqlite3_step(pRtree->pWriteParent);
125959  return sqlite3_reset(pRtree->pWriteParent);
125960}
125961
125962static int rtreeInsertCell(Rtree *, RtreeNode *, RtreeCell *, int);
125963
125964#if VARIANT_GUTTMAN_LINEAR_SPLIT
125965/*
125966** Implementation of the linear variant of the PickNext() function from
125967** Guttman[84].
125968*/
125969static RtreeCell *LinearPickNext(
125970  Rtree *pRtree,
125971  RtreeCell *aCell,
125972  int nCell,
125973  RtreeCell *pLeftBox,
125974  RtreeCell *pRightBox,
125975  int *aiUsed
125976){
125977  int ii;
125978  for(ii=0; aiUsed[ii]; ii++);
125979  aiUsed[ii] = 1;
125980  return &aCell[ii];
125981}
125982
125983/*
125984** Implementation of the linear variant of the PickSeeds() function from
125985** Guttman[84].
125986*/
125987static void LinearPickSeeds(
125988  Rtree *pRtree,
125989  RtreeCell *aCell,
125990  int nCell,
125991  int *piLeftSeed,
125992  int *piRightSeed
125993){
125994  int i;
125995  int iLeftSeed = 0;
125996  int iRightSeed = 1;
125997  float maxNormalInnerWidth = 0.0;
125998
125999  /* Pick two "seed" cells from the array of cells. The algorithm used
126000  ** here is the LinearPickSeeds algorithm from Gutman[1984]. The
126001  ** indices of the two seed cells in the array are stored in local
126002  ** variables iLeftSeek and iRightSeed.
126003  */
126004  for(i=0; i<pRtree->nDim; i++){
126005    float x1 = DCOORD(aCell[0].aCoord[i*2]);
126006    float x2 = DCOORD(aCell[0].aCoord[i*2+1]);
126007    float x3 = x1;
126008    float x4 = x2;
126009    int jj;
126010
126011    int iCellLeft = 0;
126012    int iCellRight = 0;
126013
126014    for(jj=1; jj<nCell; jj++){
126015      float left = DCOORD(aCell[jj].aCoord[i*2]);
126016      float right = DCOORD(aCell[jj].aCoord[i*2+1]);
126017
126018      if( left<x1 ) x1 = left;
126019      if( right>x4 ) x4 = right;
126020      if( left>x3 ){
126021        x3 = left;
126022        iCellRight = jj;
126023      }
126024      if( right<x2 ){
126025        x2 = right;
126026        iCellLeft = jj;
126027      }
126028    }
126029
126030    if( x4!=x1 ){
126031      float normalwidth = (x3 - x2) / (x4 - x1);
126032      if( normalwidth>maxNormalInnerWidth ){
126033        iLeftSeed = iCellLeft;
126034        iRightSeed = iCellRight;
126035      }
126036    }
126037  }
126038
126039  *piLeftSeed = iLeftSeed;
126040  *piRightSeed = iRightSeed;
126041}
126042#endif /* VARIANT_GUTTMAN_LINEAR_SPLIT */
126043
126044#if VARIANT_GUTTMAN_QUADRATIC_SPLIT
126045/*
126046** Implementation of the quadratic variant of the PickNext() function from
126047** Guttman[84].
126048*/
126049static RtreeCell *QuadraticPickNext(
126050  Rtree *pRtree,
126051  RtreeCell *aCell,
126052  int nCell,
126053  RtreeCell *pLeftBox,
126054  RtreeCell *pRightBox,
126055  int *aiUsed
126056){
126057  #define FABS(a) ((a)<0.0?-1.0*(a):(a))
126058
126059  int iSelect = -1;
126060  float fDiff;
126061  int ii;
126062  for(ii=0; ii<nCell; ii++){
126063    if( aiUsed[ii]==0 ){
126064      float left = cellGrowth(pRtree, pLeftBox, &aCell[ii]);
126065      float right = cellGrowth(pRtree, pLeftBox, &aCell[ii]);
126066      float diff = FABS(right-left);
126067      if( iSelect<0 || diff>fDiff ){
126068        fDiff = diff;
126069        iSelect = ii;
126070      }
126071    }
126072  }
126073  aiUsed[iSelect] = 1;
126074  return &aCell[iSelect];
126075}
126076
126077/*
126078** Implementation of the quadratic variant of the PickSeeds() function from
126079** Guttman[84].
126080*/
126081static void QuadraticPickSeeds(
126082  Rtree *pRtree,
126083  RtreeCell *aCell,
126084  int nCell,
126085  int *piLeftSeed,
126086  int *piRightSeed
126087){
126088  int ii;
126089  int jj;
126090
126091  int iLeftSeed = 0;
126092  int iRightSeed = 1;
126093  float fWaste = 0.0;
126094
126095  for(ii=0; ii<nCell; ii++){
126096    for(jj=ii+1; jj<nCell; jj++){
126097      float right = cellArea(pRtree, &aCell[jj]);
126098      float growth = cellGrowth(pRtree, &aCell[ii], &aCell[jj]);
126099      float waste = growth - right;
126100
126101      if( waste>fWaste ){
126102        iLeftSeed = ii;
126103        iRightSeed = jj;
126104        fWaste = waste;
126105      }
126106    }
126107  }
126108
126109  *piLeftSeed = iLeftSeed;
126110  *piRightSeed = iRightSeed;
126111}
126112#endif /* VARIANT_GUTTMAN_QUADRATIC_SPLIT */
126113
126114/*
126115** Arguments aIdx, aDistance and aSpare all point to arrays of size
126116** nIdx. The aIdx array contains the set of integers from 0 to
126117** (nIdx-1) in no particular order. This function sorts the values
126118** in aIdx according to the indexed values in aDistance. For
126119** example, assuming the inputs:
126120**
126121**   aIdx      = { 0,   1,   2,   3 }
126122**   aDistance = { 5.0, 2.0, 7.0, 6.0 }
126123**
126124** this function sets the aIdx array to contain:
126125**
126126**   aIdx      = { 0,   1,   2,   3 }
126127**
126128** The aSpare array is used as temporary working space by the
126129** sorting algorithm.
126130*/
126131static void SortByDistance(
126132  int *aIdx,
126133  int nIdx,
126134  float *aDistance,
126135  int *aSpare
126136){
126137  if( nIdx>1 ){
126138    int iLeft = 0;
126139    int iRight = 0;
126140
126141    int nLeft = nIdx/2;
126142    int nRight = nIdx-nLeft;
126143    int *aLeft = aIdx;
126144    int *aRight = &aIdx[nLeft];
126145
126146    SortByDistance(aLeft, nLeft, aDistance, aSpare);
126147    SortByDistance(aRight, nRight, aDistance, aSpare);
126148
126149    memcpy(aSpare, aLeft, sizeof(int)*nLeft);
126150    aLeft = aSpare;
126151
126152    while( iLeft<nLeft || iRight<nRight ){
126153      if( iLeft==nLeft ){
126154        aIdx[iLeft+iRight] = aRight[iRight];
126155        iRight++;
126156      }else if( iRight==nRight ){
126157        aIdx[iLeft+iRight] = aLeft[iLeft];
126158        iLeft++;
126159      }else{
126160        float fLeft = aDistance[aLeft[iLeft]];
126161        float fRight = aDistance[aRight[iRight]];
126162        if( fLeft<fRight ){
126163          aIdx[iLeft+iRight] = aLeft[iLeft];
126164          iLeft++;
126165        }else{
126166          aIdx[iLeft+iRight] = aRight[iRight];
126167          iRight++;
126168        }
126169      }
126170    }
126171
126172#if 0
126173    /* Check that the sort worked */
126174    {
126175      int jj;
126176      for(jj=1; jj<nIdx; jj++){
126177        float left = aDistance[aIdx[jj-1]];
126178        float right = aDistance[aIdx[jj]];
126179        assert( left<=right );
126180      }
126181    }
126182#endif
126183  }
126184}
126185
126186/*
126187** Arguments aIdx, aCell and aSpare all point to arrays of size
126188** nIdx. The aIdx array contains the set of integers from 0 to
126189** (nIdx-1) in no particular order. This function sorts the values
126190** in aIdx according to dimension iDim of the cells in aCell. The
126191** minimum value of dimension iDim is considered first, the
126192** maximum used to break ties.
126193**
126194** The aSpare array is used as temporary working space by the
126195** sorting algorithm.
126196*/
126197static void SortByDimension(
126198  Rtree *pRtree,
126199  int *aIdx,
126200  int nIdx,
126201  int iDim,
126202  RtreeCell *aCell,
126203  int *aSpare
126204){
126205  if( nIdx>1 ){
126206
126207    int iLeft = 0;
126208    int iRight = 0;
126209
126210    int nLeft = nIdx/2;
126211    int nRight = nIdx-nLeft;
126212    int *aLeft = aIdx;
126213    int *aRight = &aIdx[nLeft];
126214
126215    SortByDimension(pRtree, aLeft, nLeft, iDim, aCell, aSpare);
126216    SortByDimension(pRtree, aRight, nRight, iDim, aCell, aSpare);
126217
126218    memcpy(aSpare, aLeft, sizeof(int)*nLeft);
126219    aLeft = aSpare;
126220    while( iLeft<nLeft || iRight<nRight ){
126221      double xleft1 = DCOORD(aCell[aLeft[iLeft]].aCoord[iDim*2]);
126222      double xleft2 = DCOORD(aCell[aLeft[iLeft]].aCoord[iDim*2+1]);
126223      double xright1 = DCOORD(aCell[aRight[iRight]].aCoord[iDim*2]);
126224      double xright2 = DCOORD(aCell[aRight[iRight]].aCoord[iDim*2+1]);
126225      if( (iLeft!=nLeft) && ((iRight==nRight)
126226       || (xleft1<xright1)
126227       || (xleft1==xright1 && xleft2<xright2)
126228      )){
126229        aIdx[iLeft+iRight] = aLeft[iLeft];
126230        iLeft++;
126231      }else{
126232        aIdx[iLeft+iRight] = aRight[iRight];
126233        iRight++;
126234      }
126235    }
126236
126237#if 0
126238    /* Check that the sort worked */
126239    {
126240      int jj;
126241      for(jj=1; jj<nIdx; jj++){
126242        float xleft1 = aCell[aIdx[jj-1]].aCoord[iDim*2];
126243        float xleft2 = aCell[aIdx[jj-1]].aCoord[iDim*2+1];
126244        float xright1 = aCell[aIdx[jj]].aCoord[iDim*2];
126245        float xright2 = aCell[aIdx[jj]].aCoord[iDim*2+1];
126246        assert( xleft1<=xright1 && (xleft1<xright1 || xleft2<=xright2) );
126247      }
126248    }
126249#endif
126250  }
126251}
126252
126253#if VARIANT_RSTARTREE_SPLIT
126254/*
126255** Implementation of the R*-tree variant of SplitNode from Beckman[1990].
126256*/
126257static int splitNodeStartree(
126258  Rtree *pRtree,
126259  RtreeCell *aCell,
126260  int nCell,
126261  RtreeNode *pLeft,
126262  RtreeNode *pRight,
126263  RtreeCell *pBboxLeft,
126264  RtreeCell *pBboxRight
126265){
126266  int **aaSorted;
126267  int *aSpare;
126268  int ii;
126269
126270  int iBestDim;
126271  int iBestSplit;
126272  float fBestMargin;
126273
126274  int nByte = (pRtree->nDim+1)*(sizeof(int*)+nCell*sizeof(int));
126275
126276  aaSorted = (int **)sqlite3_malloc(nByte);
126277  if( !aaSorted ){
126278    return SQLITE_NOMEM;
126279  }
126280
126281  aSpare = &((int *)&aaSorted[pRtree->nDim])[pRtree->nDim*nCell];
126282  memset(aaSorted, 0, nByte);
126283  for(ii=0; ii<pRtree->nDim; ii++){
126284    int jj;
126285    aaSorted[ii] = &((int *)&aaSorted[pRtree->nDim])[ii*nCell];
126286    for(jj=0; jj<nCell; jj++){
126287      aaSorted[ii][jj] = jj;
126288    }
126289    SortByDimension(pRtree, aaSorted[ii], nCell, ii, aCell, aSpare);
126290  }
126291
126292  for(ii=0; ii<pRtree->nDim; ii++){
126293    float margin = 0.0;
126294    float fBestOverlap;
126295    float fBestArea;
126296    int iBestLeft;
126297    int nLeft;
126298
126299    for(
126300      nLeft=RTREE_MINCELLS(pRtree);
126301      nLeft<=(nCell-RTREE_MINCELLS(pRtree));
126302      nLeft++
126303    ){
126304      RtreeCell left;
126305      RtreeCell right;
126306      int kk;
126307      float overlap;
126308      float area;
126309
126310      memcpy(&left, &aCell[aaSorted[ii][0]], sizeof(RtreeCell));
126311      memcpy(&right, &aCell[aaSorted[ii][nCell-1]], sizeof(RtreeCell));
126312      for(kk=1; kk<(nCell-1); kk++){
126313        if( kk<nLeft ){
126314          cellUnion(pRtree, &left, &aCell[aaSorted[ii][kk]]);
126315        }else{
126316          cellUnion(pRtree, &right, &aCell[aaSorted[ii][kk]]);
126317        }
126318      }
126319      margin += cellMargin(pRtree, &left);
126320      margin += cellMargin(pRtree, &right);
126321      overlap = cellOverlap(pRtree, &left, &right, 1, -1);
126322      area = cellArea(pRtree, &left) + cellArea(pRtree, &right);
126323      if( (nLeft==RTREE_MINCELLS(pRtree))
126324       || (overlap<fBestOverlap)
126325       || (overlap==fBestOverlap && area<fBestArea)
126326      ){
126327        iBestLeft = nLeft;
126328        fBestOverlap = overlap;
126329        fBestArea = area;
126330      }
126331    }
126332
126333    if( ii==0 || margin<fBestMargin ){
126334      iBestDim = ii;
126335      fBestMargin = margin;
126336      iBestSplit = iBestLeft;
126337    }
126338  }
126339
126340  memcpy(pBboxLeft, &aCell[aaSorted[iBestDim][0]], sizeof(RtreeCell));
126341  memcpy(pBboxRight, &aCell[aaSorted[iBestDim][iBestSplit]], sizeof(RtreeCell));
126342  for(ii=0; ii<nCell; ii++){
126343    RtreeNode *pTarget = (ii<iBestSplit)?pLeft:pRight;
126344    RtreeCell *pBbox = (ii<iBestSplit)?pBboxLeft:pBboxRight;
126345    RtreeCell *pCell = &aCell[aaSorted[iBestDim][ii]];
126346    nodeInsertCell(pRtree, pTarget, pCell);
126347    cellUnion(pRtree, pBbox, pCell);
126348  }
126349
126350  sqlite3_free(aaSorted);
126351  return SQLITE_OK;
126352}
126353#endif
126354
126355#if VARIANT_GUTTMAN_SPLIT
126356/*
126357** Implementation of the regular R-tree SplitNode from Guttman[1984].
126358*/
126359static int splitNodeGuttman(
126360  Rtree *pRtree,
126361  RtreeCell *aCell,
126362  int nCell,
126363  RtreeNode *pLeft,
126364  RtreeNode *pRight,
126365  RtreeCell *pBboxLeft,
126366  RtreeCell *pBboxRight
126367){
126368  int iLeftSeed = 0;
126369  int iRightSeed = 1;
126370  int *aiUsed;
126371  int i;
126372
126373  aiUsed = sqlite3_malloc(sizeof(int)*nCell);
126374  if( !aiUsed ){
126375    return SQLITE_NOMEM;
126376  }
126377  memset(aiUsed, 0, sizeof(int)*nCell);
126378
126379  PickSeeds(pRtree, aCell, nCell, &iLeftSeed, &iRightSeed);
126380
126381  memcpy(pBboxLeft, &aCell[iLeftSeed], sizeof(RtreeCell));
126382  memcpy(pBboxRight, &aCell[iRightSeed], sizeof(RtreeCell));
126383  nodeInsertCell(pRtree, pLeft, &aCell[iLeftSeed]);
126384  nodeInsertCell(pRtree, pRight, &aCell[iRightSeed]);
126385  aiUsed[iLeftSeed] = 1;
126386  aiUsed[iRightSeed] = 1;
126387
126388  for(i=nCell-2; i>0; i--){
126389    RtreeCell *pNext;
126390    pNext = PickNext(pRtree, aCell, nCell, pBboxLeft, pBboxRight, aiUsed);
126391    float diff =
126392      cellGrowth(pRtree, pBboxLeft, pNext) -
126393      cellGrowth(pRtree, pBboxRight, pNext)
126394    ;
126395    if( (RTREE_MINCELLS(pRtree)-NCELL(pRight)==i)
126396     || (diff>0.0 && (RTREE_MINCELLS(pRtree)-NCELL(pLeft)!=i))
126397    ){
126398      nodeInsertCell(pRtree, pRight, pNext);
126399      cellUnion(pRtree, pBboxRight, pNext);
126400    }else{
126401      nodeInsertCell(pRtree, pLeft, pNext);
126402      cellUnion(pRtree, pBboxLeft, pNext);
126403    }
126404  }
126405
126406  sqlite3_free(aiUsed);
126407  return SQLITE_OK;
126408}
126409#endif
126410
126411static int updateMapping(
126412  Rtree *pRtree,
126413  i64 iRowid,
126414  RtreeNode *pNode,
126415  int iHeight
126416){
126417  int (*xSetMapping)(Rtree *, sqlite3_int64, sqlite3_int64);
126418  xSetMapping = ((iHeight==0)?rowidWrite:parentWrite);
126419  if( iHeight>0 ){
126420    RtreeNode *pChild = nodeHashLookup(pRtree, iRowid);
126421    if( pChild ){
126422      nodeRelease(pRtree, pChild->pParent);
126423      nodeReference(pNode);
126424      pChild->pParent = pNode;
126425    }
126426  }
126427  return xSetMapping(pRtree, iRowid, pNode->iNode);
126428}
126429
126430static int SplitNode(
126431  Rtree *pRtree,
126432  RtreeNode *pNode,
126433  RtreeCell *pCell,
126434  int iHeight
126435){
126436  int i;
126437  int newCellIsRight = 0;
126438
126439  int rc = SQLITE_OK;
126440  int nCell = NCELL(pNode);
126441  RtreeCell *aCell;
126442  int *aiUsed;
126443
126444  RtreeNode *pLeft = 0;
126445  RtreeNode *pRight = 0;
126446
126447  RtreeCell leftbbox;
126448  RtreeCell rightbbox;
126449
126450  /* Allocate an array and populate it with a copy of pCell and
126451  ** all cells from node pLeft. Then zero the original node.
126452  */
126453  aCell = sqlite3_malloc((sizeof(RtreeCell)+sizeof(int))*(nCell+1));
126454  if( !aCell ){
126455    rc = SQLITE_NOMEM;
126456    goto splitnode_out;
126457  }
126458  aiUsed = (int *)&aCell[nCell+1];
126459  memset(aiUsed, 0, sizeof(int)*(nCell+1));
126460  for(i=0; i<nCell; i++){
126461    nodeGetCell(pRtree, pNode, i, &aCell[i]);
126462  }
126463  nodeZero(pRtree, pNode);
126464  memcpy(&aCell[nCell], pCell, sizeof(RtreeCell));
126465  nCell++;
126466
126467  if( pNode->iNode==1 ){
126468    pRight = nodeNew(pRtree, pNode);
126469    pLeft = nodeNew(pRtree, pNode);
126470    pRtree->iDepth++;
126471    pNode->isDirty = 1;
126472    writeInt16(pNode->zData, pRtree->iDepth);
126473  }else{
126474    pLeft = pNode;
126475    pRight = nodeNew(pRtree, pLeft->pParent);
126476    nodeReference(pLeft);
126477  }
126478
126479  if( !pLeft || !pRight ){
126480    rc = SQLITE_NOMEM;
126481    goto splitnode_out;
126482  }
126483
126484  memset(pLeft->zData, 0, pRtree->iNodeSize);
126485  memset(pRight->zData, 0, pRtree->iNodeSize);
126486
126487  rc = AssignCells(pRtree, aCell, nCell, pLeft, pRight, &leftbbox, &rightbbox);
126488  if( rc!=SQLITE_OK ){
126489    goto splitnode_out;
126490  }
126491
126492  /* Ensure both child nodes have node numbers assigned to them by calling
126493  ** nodeWrite(). Node pRight always needs a node number, as it was created
126494  ** by nodeNew() above. But node pLeft sometimes already has a node number.
126495  ** In this case avoid the all to nodeWrite().
126496  */
126497  if( SQLITE_OK!=(rc = nodeWrite(pRtree, pRight))
126498   || (0==pLeft->iNode && SQLITE_OK!=(rc = nodeWrite(pRtree, pLeft)))
126499  ){
126500    goto splitnode_out;
126501  }
126502
126503  rightbbox.iRowid = pRight->iNode;
126504  leftbbox.iRowid = pLeft->iNode;
126505
126506  if( pNode->iNode==1 ){
126507    rc = rtreeInsertCell(pRtree, pLeft->pParent, &leftbbox, iHeight+1);
126508    if( rc!=SQLITE_OK ){
126509      goto splitnode_out;
126510    }
126511  }else{
126512    RtreeNode *pParent = pLeft->pParent;
126513    int iCell;
126514    rc = nodeParentIndex(pRtree, pLeft, &iCell);
126515    if( rc==SQLITE_OK ){
126516      nodeOverwriteCell(pRtree, pParent, &leftbbox, iCell);
126517      rc = AdjustTree(pRtree, pParent, &leftbbox);
126518    }
126519    if( rc!=SQLITE_OK ){
126520      goto splitnode_out;
126521    }
126522  }
126523  if( (rc = rtreeInsertCell(pRtree, pRight->pParent, &rightbbox, iHeight+1)) ){
126524    goto splitnode_out;
126525  }
126526
126527  for(i=0; i<NCELL(pRight); i++){
126528    i64 iRowid = nodeGetRowid(pRtree, pRight, i);
126529    rc = updateMapping(pRtree, iRowid, pRight, iHeight);
126530    if( iRowid==pCell->iRowid ){
126531      newCellIsRight = 1;
126532    }
126533    if( rc!=SQLITE_OK ){
126534      goto splitnode_out;
126535    }
126536  }
126537  if( pNode->iNode==1 ){
126538    for(i=0; i<NCELL(pLeft); i++){
126539      i64 iRowid = nodeGetRowid(pRtree, pLeft, i);
126540      rc = updateMapping(pRtree, iRowid, pLeft, iHeight);
126541      if( rc!=SQLITE_OK ){
126542        goto splitnode_out;
126543      }
126544    }
126545  }else if( newCellIsRight==0 ){
126546    rc = updateMapping(pRtree, pCell->iRowid, pLeft, iHeight);
126547  }
126548
126549  if( rc==SQLITE_OK ){
126550    rc = nodeRelease(pRtree, pRight);
126551    pRight = 0;
126552  }
126553  if( rc==SQLITE_OK ){
126554    rc = nodeRelease(pRtree, pLeft);
126555    pLeft = 0;
126556  }
126557
126558splitnode_out:
126559  nodeRelease(pRtree, pRight);
126560  nodeRelease(pRtree, pLeft);
126561  sqlite3_free(aCell);
126562  return rc;
126563}
126564
126565/*
126566** If node pLeaf is not the root of the r-tree and its pParent pointer is
126567** still NULL, load all ancestor nodes of pLeaf into memory and populate
126568** the pLeaf->pParent chain all the way up to the root node.
126569**
126570** This operation is required when a row is deleted (or updated - an update
126571** is implemented as a delete followed by an insert). SQLite provides the
126572** rowid of the row to delete, which can be used to find the leaf on which
126573** the entry resides (argument pLeaf). Once the leaf is located, this
126574** function is called to determine its ancestry.
126575*/
126576static int fixLeafParent(Rtree *pRtree, RtreeNode *pLeaf){
126577  int rc = SQLITE_OK;
126578  RtreeNode *pChild = pLeaf;
126579  while( rc==SQLITE_OK && pChild->iNode!=1 && pChild->pParent==0 ){
126580    int rc2 = SQLITE_OK;          /* sqlite3_reset() return code */
126581    sqlite3_bind_int64(pRtree->pReadParent, 1, pChild->iNode);
126582    rc = sqlite3_step(pRtree->pReadParent);
126583    if( rc==SQLITE_ROW ){
126584      RtreeNode *pTest;           /* Used to test for reference loops */
126585      i64 iNode;                  /* Node number of parent node */
126586
126587      /* Before setting pChild->pParent, test that we are not creating a
126588      ** loop of references (as we would if, say, pChild==pParent). We don't
126589      ** want to do this as it leads to a memory leak when trying to delete
126590      ** the referenced counted node structures.
126591      */
126592      iNode = sqlite3_column_int64(pRtree->pReadParent, 0);
126593      for(pTest=pLeaf; pTest && pTest->iNode!=iNode; pTest=pTest->pParent);
126594      if( !pTest ){
126595        rc2 = nodeAcquire(pRtree, iNode, 0, &pChild->pParent);
126596      }
126597    }
126598    rc = sqlite3_reset(pRtree->pReadParent);
126599    if( rc==SQLITE_OK ) rc = rc2;
126600    if( rc==SQLITE_OK && !pChild->pParent ) rc = SQLITE_CORRUPT;
126601    pChild = pChild->pParent;
126602  }
126603  return rc;
126604}
126605
126606static int deleteCell(Rtree *, RtreeNode *, int, int);
126607
126608static int removeNode(Rtree *pRtree, RtreeNode *pNode, int iHeight){
126609  int rc;
126610  int rc2;
126611  RtreeNode *pParent;
126612  int iCell;
126613
126614  assert( pNode->nRef==1 );
126615
126616  /* Remove the entry in the parent cell. */
126617  rc = nodeParentIndex(pRtree, pNode, &iCell);
126618  if( rc==SQLITE_OK ){
126619    pParent = pNode->pParent;
126620    pNode->pParent = 0;
126621    rc = deleteCell(pRtree, pParent, iCell, iHeight+1);
126622  }
126623  rc2 = nodeRelease(pRtree, pParent);
126624  if( rc==SQLITE_OK ){
126625    rc = rc2;
126626  }
126627  if( rc!=SQLITE_OK ){
126628    return rc;
126629  }
126630
126631  /* Remove the xxx_node entry. */
126632  sqlite3_bind_int64(pRtree->pDeleteNode, 1, pNode->iNode);
126633  sqlite3_step(pRtree->pDeleteNode);
126634  if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteNode)) ){
126635    return rc;
126636  }
126637
126638  /* Remove the xxx_parent entry. */
126639  sqlite3_bind_int64(pRtree->pDeleteParent, 1, pNode->iNode);
126640  sqlite3_step(pRtree->pDeleteParent);
126641  if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteParent)) ){
126642    return rc;
126643  }
126644
126645  /* Remove the node from the in-memory hash table and link it into
126646  ** the Rtree.pDeleted list. Its contents will be re-inserted later on.
126647  */
126648  nodeHashDelete(pRtree, pNode);
126649  pNode->iNode = iHeight;
126650  pNode->pNext = pRtree->pDeleted;
126651  pNode->nRef++;
126652  pRtree->pDeleted = pNode;
126653
126654  return SQLITE_OK;
126655}
126656
126657static int fixBoundingBox(Rtree *pRtree, RtreeNode *pNode){
126658  RtreeNode *pParent = pNode->pParent;
126659  int rc = SQLITE_OK;
126660  if( pParent ){
126661    int ii;
126662    int nCell = NCELL(pNode);
126663    RtreeCell box;                            /* Bounding box for pNode */
126664    nodeGetCell(pRtree, pNode, 0, &box);
126665    for(ii=1; ii<nCell; ii++){
126666      RtreeCell cell;
126667      nodeGetCell(pRtree, pNode, ii, &cell);
126668      cellUnion(pRtree, &box, &cell);
126669    }
126670    box.iRowid = pNode->iNode;
126671    rc = nodeParentIndex(pRtree, pNode, &ii);
126672    if( rc==SQLITE_OK ){
126673      nodeOverwriteCell(pRtree, pParent, &box, ii);
126674      rc = fixBoundingBox(pRtree, pParent);
126675    }
126676  }
126677  return rc;
126678}
126679
126680/*
126681** Delete the cell at index iCell of node pNode. After removing the
126682** cell, adjust the r-tree data structure if required.
126683*/
126684static int deleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell, int iHeight){
126685  RtreeNode *pParent;
126686  int rc;
126687
126688  if( SQLITE_OK!=(rc = fixLeafParent(pRtree, pNode)) ){
126689    return rc;
126690  }
126691
126692  /* Remove the cell from the node. This call just moves bytes around
126693  ** the in-memory node image, so it cannot fail.
126694  */
126695  nodeDeleteCell(pRtree, pNode, iCell);
126696
126697  /* If the node is not the tree root and now has less than the minimum
126698  ** number of cells, remove it from the tree. Otherwise, update the
126699  ** cell in the parent node so that it tightly contains the updated
126700  ** node.
126701  */
126702  pParent = pNode->pParent;
126703  assert( pParent || pNode->iNode==1 );
126704  if( pParent ){
126705    if( NCELL(pNode)<RTREE_MINCELLS(pRtree) ){
126706      rc = removeNode(pRtree, pNode, iHeight);
126707    }else{
126708      rc = fixBoundingBox(pRtree, pNode);
126709    }
126710  }
126711
126712  return rc;
126713}
126714
126715static int Reinsert(
126716  Rtree *pRtree,
126717  RtreeNode *pNode,
126718  RtreeCell *pCell,
126719  int iHeight
126720){
126721  int *aOrder;
126722  int *aSpare;
126723  RtreeCell *aCell;
126724  float *aDistance;
126725  int nCell;
126726  float aCenterCoord[RTREE_MAX_DIMENSIONS];
126727  int iDim;
126728  int ii;
126729  int rc = SQLITE_OK;
126730
126731  memset(aCenterCoord, 0, sizeof(float)*RTREE_MAX_DIMENSIONS);
126732
126733  nCell = NCELL(pNode)+1;
126734
126735  /* Allocate the buffers used by this operation. The allocation is
126736  ** relinquished before this function returns.
126737  */
126738  aCell = (RtreeCell *)sqlite3_malloc(nCell * (
126739    sizeof(RtreeCell) +         /* aCell array */
126740    sizeof(int)       +         /* aOrder array */
126741    sizeof(int)       +         /* aSpare array */
126742    sizeof(float)               /* aDistance array */
126743  ));
126744  if( !aCell ){
126745    return SQLITE_NOMEM;
126746  }
126747  aOrder    = (int *)&aCell[nCell];
126748  aSpare    = (int *)&aOrder[nCell];
126749  aDistance = (float *)&aSpare[nCell];
126750
126751  for(ii=0; ii<nCell; ii++){
126752    if( ii==(nCell-1) ){
126753      memcpy(&aCell[ii], pCell, sizeof(RtreeCell));
126754    }else{
126755      nodeGetCell(pRtree, pNode, ii, &aCell[ii]);
126756    }
126757    aOrder[ii] = ii;
126758    for(iDim=0; iDim<pRtree->nDim; iDim++){
126759      aCenterCoord[iDim] += DCOORD(aCell[ii].aCoord[iDim*2]);
126760      aCenterCoord[iDim] += DCOORD(aCell[ii].aCoord[iDim*2+1]);
126761    }
126762  }
126763  for(iDim=0; iDim<pRtree->nDim; iDim++){
126764    aCenterCoord[iDim] = aCenterCoord[iDim]/((float)nCell*2.0);
126765  }
126766
126767  for(ii=0; ii<nCell; ii++){
126768    aDistance[ii] = 0.0;
126769    for(iDim=0; iDim<pRtree->nDim; iDim++){
126770      float coord = DCOORD(aCell[ii].aCoord[iDim*2+1]) -
126771          DCOORD(aCell[ii].aCoord[iDim*2]);
126772      aDistance[ii] += (coord-aCenterCoord[iDim])*(coord-aCenterCoord[iDim]);
126773    }
126774  }
126775
126776  SortByDistance(aOrder, nCell, aDistance, aSpare);
126777  nodeZero(pRtree, pNode);
126778
126779  for(ii=0; rc==SQLITE_OK && ii<(nCell-(RTREE_MINCELLS(pRtree)+1)); ii++){
126780    RtreeCell *p = &aCell[aOrder[ii]];
126781    nodeInsertCell(pRtree, pNode, p);
126782    if( p->iRowid==pCell->iRowid ){
126783      if( iHeight==0 ){
126784        rc = rowidWrite(pRtree, p->iRowid, pNode->iNode);
126785      }else{
126786        rc = parentWrite(pRtree, p->iRowid, pNode->iNode);
126787      }
126788    }
126789  }
126790  if( rc==SQLITE_OK ){
126791    rc = fixBoundingBox(pRtree, pNode);
126792  }
126793  for(; rc==SQLITE_OK && ii<nCell; ii++){
126794    /* Find a node to store this cell in. pNode->iNode currently contains
126795    ** the height of the sub-tree headed by the cell.
126796    */
126797    RtreeNode *pInsert;
126798    RtreeCell *p = &aCell[aOrder[ii]];
126799    rc = ChooseLeaf(pRtree, p, iHeight, &pInsert);
126800    if( rc==SQLITE_OK ){
126801      int rc2;
126802      rc = rtreeInsertCell(pRtree, pInsert, p, iHeight);
126803      rc2 = nodeRelease(pRtree, pInsert);
126804      if( rc==SQLITE_OK ){
126805        rc = rc2;
126806      }
126807    }
126808  }
126809
126810  sqlite3_free(aCell);
126811  return rc;
126812}
126813
126814/*
126815** Insert cell pCell into node pNode. Node pNode is the head of a
126816** subtree iHeight high (leaf nodes have iHeight==0).
126817*/
126818static int rtreeInsertCell(
126819  Rtree *pRtree,
126820  RtreeNode *pNode,
126821  RtreeCell *pCell,
126822  int iHeight
126823){
126824  int rc = SQLITE_OK;
126825  if( iHeight>0 ){
126826    RtreeNode *pChild = nodeHashLookup(pRtree, pCell->iRowid);
126827    if( pChild ){
126828      nodeRelease(pRtree, pChild->pParent);
126829      nodeReference(pNode);
126830      pChild->pParent = pNode;
126831    }
126832  }
126833  if( nodeInsertCell(pRtree, pNode, pCell) ){
126834#if VARIANT_RSTARTREE_REINSERT
126835    if( iHeight<=pRtree->iReinsertHeight || pNode->iNode==1){
126836      rc = SplitNode(pRtree, pNode, pCell, iHeight);
126837    }else{
126838      pRtree->iReinsertHeight = iHeight;
126839      rc = Reinsert(pRtree, pNode, pCell, iHeight);
126840    }
126841#else
126842    rc = SplitNode(pRtree, pNode, pCell, iHeight);
126843#endif
126844  }else{
126845    rc = AdjustTree(pRtree, pNode, pCell);
126846    if( rc==SQLITE_OK ){
126847      if( iHeight==0 ){
126848        rc = rowidWrite(pRtree, pCell->iRowid, pNode->iNode);
126849      }else{
126850        rc = parentWrite(pRtree, pCell->iRowid, pNode->iNode);
126851      }
126852    }
126853  }
126854  return rc;
126855}
126856
126857static int reinsertNodeContent(Rtree *pRtree, RtreeNode *pNode){
126858  int ii;
126859  int rc = SQLITE_OK;
126860  int nCell = NCELL(pNode);
126861
126862  for(ii=0; rc==SQLITE_OK && ii<nCell; ii++){
126863    RtreeNode *pInsert;
126864    RtreeCell cell;
126865    nodeGetCell(pRtree, pNode, ii, &cell);
126866
126867    /* Find a node to store this cell in. pNode->iNode currently contains
126868    ** the height of the sub-tree headed by the cell.
126869    */
126870    rc = ChooseLeaf(pRtree, &cell, pNode->iNode, &pInsert);
126871    if( rc==SQLITE_OK ){
126872      int rc2;
126873      rc = rtreeInsertCell(pRtree, pInsert, &cell, pNode->iNode);
126874      rc2 = nodeRelease(pRtree, pInsert);
126875      if( rc==SQLITE_OK ){
126876        rc = rc2;
126877      }
126878    }
126879  }
126880  return rc;
126881}
126882
126883/*
126884** Select a currently unused rowid for a new r-tree record.
126885*/
126886static int newRowid(Rtree *pRtree, i64 *piRowid){
126887  int rc;
126888  sqlite3_bind_null(pRtree->pWriteRowid, 1);
126889  sqlite3_bind_null(pRtree->pWriteRowid, 2);
126890  sqlite3_step(pRtree->pWriteRowid);
126891  rc = sqlite3_reset(pRtree->pWriteRowid);
126892  *piRowid = sqlite3_last_insert_rowid(pRtree->db);
126893  return rc;
126894}
126895
126896/*
126897** The xUpdate method for rtree module virtual tables.
126898*/
126899static int rtreeUpdate(
126900  sqlite3_vtab *pVtab,
126901  int nData,
126902  sqlite3_value **azData,
126903  sqlite_int64 *pRowid
126904){
126905  Rtree *pRtree = (Rtree *)pVtab;
126906  int rc = SQLITE_OK;
126907
126908  rtreeReference(pRtree);
126909
126910  assert(nData>=1);
126911
126912  /* If azData[0] is not an SQL NULL value, it is the rowid of a
126913  ** record to delete from the r-tree table. The following block does
126914  ** just that.
126915  */
126916  if( sqlite3_value_type(azData[0])!=SQLITE_NULL ){
126917    i64 iDelete;                /* The rowid to delete */
126918    RtreeNode *pLeaf;           /* Leaf node containing record iDelete */
126919    int iCell;                  /* Index of iDelete cell in pLeaf */
126920    RtreeNode *pRoot;
126921
126922    /* Obtain a reference to the root node to initialise Rtree.iDepth */
126923    rc = nodeAcquire(pRtree, 1, 0, &pRoot);
126924
126925    /* Obtain a reference to the leaf node that contains the entry
126926    ** about to be deleted.
126927    */
126928    if( rc==SQLITE_OK ){
126929      iDelete = sqlite3_value_int64(azData[0]);
126930      rc = findLeafNode(pRtree, iDelete, &pLeaf);
126931    }
126932
126933    /* Delete the cell in question from the leaf node. */
126934    if( rc==SQLITE_OK ){
126935      int rc2;
126936      rc = nodeRowidIndex(pRtree, pLeaf, iDelete, &iCell);
126937      if( rc==SQLITE_OK ){
126938        rc = deleteCell(pRtree, pLeaf, iCell, 0);
126939      }
126940      rc2 = nodeRelease(pRtree, pLeaf);
126941      if( rc==SQLITE_OK ){
126942        rc = rc2;
126943      }
126944    }
126945
126946    /* Delete the corresponding entry in the <rtree>_rowid table. */
126947    if( rc==SQLITE_OK ){
126948      sqlite3_bind_int64(pRtree->pDeleteRowid, 1, iDelete);
126949      sqlite3_step(pRtree->pDeleteRowid);
126950      rc = sqlite3_reset(pRtree->pDeleteRowid);
126951    }
126952
126953    /* Check if the root node now has exactly one child. If so, remove
126954    ** it, schedule the contents of the child for reinsertion and
126955    ** reduce the tree height by one.
126956    **
126957    ** This is equivalent to copying the contents of the child into
126958    ** the root node (the operation that Gutman's paper says to perform
126959    ** in this scenario).
126960    */
126961    if( rc==SQLITE_OK && pRtree->iDepth>0 && NCELL(pRoot)==1 ){
126962      int rc2;
126963      RtreeNode *pChild;
126964      i64 iChild = nodeGetRowid(pRtree, pRoot, 0);
126965      rc = nodeAcquire(pRtree, iChild, pRoot, &pChild);
126966      if( rc==SQLITE_OK ){
126967        rc = removeNode(pRtree, pChild, pRtree->iDepth-1);
126968      }
126969      rc2 = nodeRelease(pRtree, pChild);
126970      if( rc==SQLITE_OK ) rc = rc2;
126971      if( rc==SQLITE_OK ){
126972        pRtree->iDepth--;
126973        writeInt16(pRoot->zData, pRtree->iDepth);
126974        pRoot->isDirty = 1;
126975      }
126976    }
126977
126978    /* Re-insert the contents of any underfull nodes removed from the tree. */
126979    for(pLeaf=pRtree->pDeleted; pLeaf; pLeaf=pRtree->pDeleted){
126980      if( rc==SQLITE_OK ){
126981        rc = reinsertNodeContent(pRtree, pLeaf);
126982      }
126983      pRtree->pDeleted = pLeaf->pNext;
126984      sqlite3_free(pLeaf);
126985    }
126986
126987    /* Release the reference to the root node. */
126988    if( rc==SQLITE_OK ){
126989      rc = nodeRelease(pRtree, pRoot);
126990    }else{
126991      nodeRelease(pRtree, pRoot);
126992    }
126993  }
126994
126995  /* If the azData[] array contains more than one element, elements
126996  ** (azData[2]..azData[argc-1]) contain a new record to insert into
126997  ** the r-tree structure.
126998  */
126999  if( rc==SQLITE_OK && nData>1 ){
127000    /* Insert a new record into the r-tree */
127001    RtreeCell cell;
127002    int ii;
127003    RtreeNode *pLeaf;
127004
127005    /* Populate the cell.aCoord[] array. The first coordinate is azData[3]. */
127006    assert( nData==(pRtree->nDim*2 + 3) );
127007    if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
127008      for(ii=0; ii<(pRtree->nDim*2); ii+=2){
127009        cell.aCoord[ii].f = (float)sqlite3_value_double(azData[ii+3]);
127010        cell.aCoord[ii+1].f = (float)sqlite3_value_double(azData[ii+4]);
127011        if( cell.aCoord[ii].f>cell.aCoord[ii+1].f ){
127012          rc = SQLITE_CONSTRAINT;
127013          goto constraint;
127014        }
127015      }
127016    }else{
127017      for(ii=0; ii<(pRtree->nDim*2); ii+=2){
127018        cell.aCoord[ii].i = sqlite3_value_int(azData[ii+3]);
127019        cell.aCoord[ii+1].i = sqlite3_value_int(azData[ii+4]);
127020        if( cell.aCoord[ii].i>cell.aCoord[ii+1].i ){
127021          rc = SQLITE_CONSTRAINT;
127022          goto constraint;
127023        }
127024      }
127025    }
127026
127027    /* Figure out the rowid of the new row. */
127028    if( sqlite3_value_type(azData[2])==SQLITE_NULL ){
127029      rc = newRowid(pRtree, &cell.iRowid);
127030    }else{
127031      cell.iRowid = sqlite3_value_int64(azData[2]);
127032      sqlite3_bind_int64(pRtree->pReadRowid, 1, cell.iRowid);
127033      if( SQLITE_ROW==sqlite3_step(pRtree->pReadRowid) ){
127034        sqlite3_reset(pRtree->pReadRowid);
127035        rc = SQLITE_CONSTRAINT;
127036        goto constraint;
127037      }
127038      rc = sqlite3_reset(pRtree->pReadRowid);
127039    }
127040    *pRowid = cell.iRowid;
127041
127042    if( rc==SQLITE_OK ){
127043      rc = ChooseLeaf(pRtree, &cell, 0, &pLeaf);
127044    }
127045    if( rc==SQLITE_OK ){
127046      int rc2;
127047      pRtree->iReinsertHeight = -1;
127048      rc = rtreeInsertCell(pRtree, pLeaf, &cell, 0);
127049      rc2 = nodeRelease(pRtree, pLeaf);
127050      if( rc==SQLITE_OK ){
127051        rc = rc2;
127052      }
127053    }
127054  }
127055
127056constraint:
127057  rtreeRelease(pRtree);
127058  return rc;
127059}
127060
127061/*
127062** The xRename method for rtree module virtual tables.
127063*/
127064static int rtreeRename(sqlite3_vtab *pVtab, const char *zNewName){
127065  Rtree *pRtree = (Rtree *)pVtab;
127066  int rc = SQLITE_NOMEM;
127067  char *zSql = sqlite3_mprintf(
127068    "ALTER TABLE %Q.'%q_node'   RENAME TO \"%w_node\";"
127069    "ALTER TABLE %Q.'%q_parent' RENAME TO \"%w_parent\";"
127070    "ALTER TABLE %Q.'%q_rowid'  RENAME TO \"%w_rowid\";"
127071    , pRtree->zDb, pRtree->zName, zNewName
127072    , pRtree->zDb, pRtree->zName, zNewName
127073    , pRtree->zDb, pRtree->zName, zNewName
127074  );
127075  if( zSql ){
127076    rc = sqlite3_exec(pRtree->db, zSql, 0, 0, 0);
127077    sqlite3_free(zSql);
127078  }
127079  return rc;
127080}
127081
127082static sqlite3_module rtreeModule = {
127083  0,                         /* iVersion */
127084  rtreeCreate,                /* xCreate - create a table */
127085  rtreeConnect,               /* xConnect - connect to an existing table */
127086  rtreeBestIndex,             /* xBestIndex - Determine search strategy */
127087  rtreeDisconnect,            /* xDisconnect - Disconnect from a table */
127088  rtreeDestroy,               /* xDestroy - Drop a table */
127089  rtreeOpen,                  /* xOpen - open a cursor */
127090  rtreeClose,                 /* xClose - close a cursor */
127091  rtreeFilter,                /* xFilter - configure scan constraints */
127092  rtreeNext,                  /* xNext - advance a cursor */
127093  rtreeEof,                   /* xEof */
127094  rtreeColumn,                /* xColumn - read data */
127095  rtreeRowid,                 /* xRowid - read data */
127096  rtreeUpdate,                /* xUpdate - write data */
127097  0,                          /* xBegin - begin transaction */
127098  0,                          /* xSync - sync transaction */
127099  0,                          /* xCommit - commit transaction */
127100  0,                          /* xRollback - rollback transaction */
127101  0,                          /* xFindFunction - function overloading */
127102  rtreeRename                 /* xRename - rename the table */
127103};
127104
127105static int rtreeSqlInit(
127106  Rtree *pRtree,
127107  sqlite3 *db,
127108  const char *zDb,
127109  const char *zPrefix,
127110  int isCreate
127111){
127112  int rc = SQLITE_OK;
127113
127114  #define N_STATEMENT 9
127115  static const char *azSql[N_STATEMENT] = {
127116    /* Read and write the xxx_node table */
127117    "SELECT data FROM '%q'.'%q_node' WHERE nodeno = :1",
127118    "INSERT OR REPLACE INTO '%q'.'%q_node' VALUES(:1, :2)",
127119    "DELETE FROM '%q'.'%q_node' WHERE nodeno = :1",
127120
127121    /* Read and write the xxx_rowid table */
127122    "SELECT nodeno FROM '%q'.'%q_rowid' WHERE rowid = :1",
127123    "INSERT OR REPLACE INTO '%q'.'%q_rowid' VALUES(:1, :2)",
127124    "DELETE FROM '%q'.'%q_rowid' WHERE rowid = :1",
127125
127126    /* Read and write the xxx_parent table */
127127    "SELECT parentnode FROM '%q'.'%q_parent' WHERE nodeno = :1",
127128    "INSERT OR REPLACE INTO '%q'.'%q_parent' VALUES(:1, :2)",
127129    "DELETE FROM '%q'.'%q_parent' WHERE nodeno = :1"
127130  };
127131  sqlite3_stmt **appStmt[N_STATEMENT];
127132  int i;
127133
127134  pRtree->db = db;
127135
127136  if( isCreate ){
127137    char *zCreate = sqlite3_mprintf(
127138"CREATE TABLE \"%w\".\"%w_node\"(nodeno INTEGER PRIMARY KEY, data BLOB);"
127139"CREATE TABLE \"%w\".\"%w_rowid\"(rowid INTEGER PRIMARY KEY, nodeno INTEGER);"
127140"CREATE TABLE \"%w\".\"%w_parent\"(nodeno INTEGER PRIMARY KEY, parentnode INTEGER);"
127141"INSERT INTO '%q'.'%q_node' VALUES(1, zeroblob(%d))",
127142      zDb, zPrefix, zDb, zPrefix, zDb, zPrefix, zDb, zPrefix, pRtree->iNodeSize
127143    );
127144    if( !zCreate ){
127145      return SQLITE_NOMEM;
127146    }
127147    rc = sqlite3_exec(db, zCreate, 0, 0, 0);
127148    sqlite3_free(zCreate);
127149    if( rc!=SQLITE_OK ){
127150      return rc;
127151    }
127152  }
127153
127154  appStmt[0] = &pRtree->pReadNode;
127155  appStmt[1] = &pRtree->pWriteNode;
127156  appStmt[2] = &pRtree->pDeleteNode;
127157  appStmt[3] = &pRtree->pReadRowid;
127158  appStmt[4] = &pRtree->pWriteRowid;
127159  appStmt[5] = &pRtree->pDeleteRowid;
127160  appStmt[6] = &pRtree->pReadParent;
127161  appStmt[7] = &pRtree->pWriteParent;
127162  appStmt[8] = &pRtree->pDeleteParent;
127163
127164  for(i=0; i<N_STATEMENT && rc==SQLITE_OK; i++){
127165    char *zSql = sqlite3_mprintf(azSql[i], zDb, zPrefix);
127166    if( zSql ){
127167      rc = sqlite3_prepare_v2(db, zSql, -1, appStmt[i], 0);
127168    }else{
127169      rc = SQLITE_NOMEM;
127170    }
127171    sqlite3_free(zSql);
127172  }
127173
127174  return rc;
127175}
127176
127177/*
127178** The second argument to this function contains the text of an SQL statement
127179** that returns a single integer value. The statement is compiled and executed
127180** using database connection db. If successful, the integer value returned
127181** is written to *piVal and SQLITE_OK returned. Otherwise, an SQLite error
127182** code is returned and the value of *piVal after returning is not defined.
127183*/
127184static int getIntFromStmt(sqlite3 *db, const char *zSql, int *piVal){
127185  int rc = SQLITE_NOMEM;
127186  if( zSql ){
127187    sqlite3_stmt *pStmt = 0;
127188    rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
127189    if( rc==SQLITE_OK ){
127190      if( SQLITE_ROW==sqlite3_step(pStmt) ){
127191        *piVal = sqlite3_column_int(pStmt, 0);
127192      }
127193      rc = sqlite3_finalize(pStmt);
127194    }
127195  }
127196  return rc;
127197}
127198
127199/*
127200** This function is called from within the xConnect() or xCreate() method to
127201** determine the node-size used by the rtree table being created or connected
127202** to. If successful, pRtree->iNodeSize is populated and SQLITE_OK returned.
127203** Otherwise, an SQLite error code is returned.
127204**
127205** If this function is being called as part of an xConnect(), then the rtree
127206** table already exists. In this case the node-size is determined by inspecting
127207** the root node of the tree.
127208**
127209** Otherwise, for an xCreate(), use 64 bytes less than the database page-size.
127210** This ensures that each node is stored on a single database page. If the
127211** database page-size is so large that more than RTREE_MAXCELLS entries
127212** would fit in a single node, use a smaller node-size.
127213*/
127214static int getNodeSize(
127215  sqlite3 *db,                    /* Database handle */
127216  Rtree *pRtree,                  /* Rtree handle */
127217  int isCreate                    /* True for xCreate, false for xConnect */
127218){
127219  int rc;
127220  char *zSql;
127221  if( isCreate ){
127222    int iPageSize;
127223    zSql = sqlite3_mprintf("PRAGMA %Q.page_size", pRtree->zDb);
127224    rc = getIntFromStmt(db, zSql, &iPageSize);
127225    if( rc==SQLITE_OK ){
127226      pRtree->iNodeSize = iPageSize-64;
127227      if( (4+pRtree->nBytesPerCell*RTREE_MAXCELLS)<pRtree->iNodeSize ){
127228        pRtree->iNodeSize = 4+pRtree->nBytesPerCell*RTREE_MAXCELLS;
127229      }
127230    }
127231  }else{
127232    zSql = sqlite3_mprintf(
127233        "SELECT length(data) FROM '%q'.'%q_node' WHERE nodeno = 1",
127234        pRtree->zDb, pRtree->zName
127235    );
127236    rc = getIntFromStmt(db, zSql, &pRtree->iNodeSize);
127237  }
127238
127239  sqlite3_free(zSql);
127240  return rc;
127241}
127242
127243/*
127244** This function is the implementation of both the xConnect and xCreate
127245** methods of the r-tree virtual table.
127246**
127247**   argv[0]   -> module name
127248**   argv[1]   -> database name
127249**   argv[2]   -> table name
127250**   argv[...] -> column names...
127251*/
127252static int rtreeInit(
127253  sqlite3 *db,                        /* Database connection */
127254  void *pAux,                         /* One of the RTREE_COORD_* constants */
127255  int argc, const char *const*argv,   /* Parameters to CREATE TABLE statement */
127256  sqlite3_vtab **ppVtab,              /* OUT: New virtual table */
127257  char **pzErr,                       /* OUT: Error message, if any */
127258  int isCreate                        /* True for xCreate, false for xConnect */
127259){
127260  int rc = SQLITE_OK;
127261  Rtree *pRtree;
127262  int nDb;              /* Length of string argv[1] */
127263  int nName;            /* Length of string argv[2] */
127264  int eCoordType = (pAux ? RTREE_COORD_INT32 : RTREE_COORD_REAL32);
127265
127266  const char *aErrMsg[] = {
127267    0,                                                    /* 0 */
127268    "Wrong number of columns for an rtree table",         /* 1 */
127269    "Too few columns for an rtree table",                 /* 2 */
127270    "Too many columns for an rtree table"                 /* 3 */
127271  };
127272
127273  int iErr = (argc<6) ? 2 : argc>(RTREE_MAX_DIMENSIONS*2+4) ? 3 : argc%2;
127274  if( aErrMsg[iErr] ){
127275    *pzErr = sqlite3_mprintf("%s", aErrMsg[iErr]);
127276    return SQLITE_ERROR;
127277  }
127278
127279  /* Allocate the sqlite3_vtab structure */
127280  nDb = strlen(argv[1]);
127281  nName = strlen(argv[2]);
127282  pRtree = (Rtree *)sqlite3_malloc(sizeof(Rtree)+nDb+nName+2);
127283  if( !pRtree ){
127284    return SQLITE_NOMEM;
127285  }
127286  memset(pRtree, 0, sizeof(Rtree)+nDb+nName+2);
127287  pRtree->nBusy = 1;
127288  pRtree->base.pModule = &rtreeModule;
127289  pRtree->zDb = (char *)&pRtree[1];
127290  pRtree->zName = &pRtree->zDb[nDb+1];
127291  pRtree->nDim = (argc-4)/2;
127292  pRtree->nBytesPerCell = 8 + pRtree->nDim*4*2;
127293  pRtree->eCoordType = eCoordType;
127294  memcpy(pRtree->zDb, argv[1], nDb);
127295  memcpy(pRtree->zName, argv[2], nName);
127296
127297  /* Figure out the node size to use. */
127298  rc = getNodeSize(db, pRtree, isCreate);
127299
127300  /* Create/Connect to the underlying relational database schema. If
127301  ** that is successful, call sqlite3_declare_vtab() to configure
127302  ** the r-tree table schema.
127303  */
127304  if( rc==SQLITE_OK ){
127305    if( (rc = rtreeSqlInit(pRtree, db, argv[1], argv[2], isCreate)) ){
127306      *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
127307    }else{
127308      char *zSql = sqlite3_mprintf("CREATE TABLE x(%s", argv[3]);
127309      char *zTmp;
127310      int ii;
127311      for(ii=4; zSql && ii<argc; ii++){
127312        zTmp = zSql;
127313        zSql = sqlite3_mprintf("%s, %s", zTmp, argv[ii]);
127314        sqlite3_free(zTmp);
127315      }
127316      if( zSql ){
127317        zTmp = zSql;
127318        zSql = sqlite3_mprintf("%s);", zTmp);
127319        sqlite3_free(zTmp);
127320      }
127321      if( !zSql ){
127322        rc = SQLITE_NOMEM;
127323      }else if( SQLITE_OK!=(rc = sqlite3_declare_vtab(db, zSql)) ){
127324        *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
127325      }
127326      sqlite3_free(zSql);
127327    }
127328  }
127329
127330  if( rc==SQLITE_OK ){
127331    *ppVtab = (sqlite3_vtab *)pRtree;
127332  }else{
127333    rtreeRelease(pRtree);
127334  }
127335  return rc;
127336}
127337
127338
127339/*
127340** Implementation of a scalar function that decodes r-tree nodes to
127341** human readable strings. This can be used for debugging and analysis.
127342**
127343** The scalar function takes two arguments, a blob of data containing
127344** an r-tree node, and the number of dimensions the r-tree indexes.
127345** For a two-dimensional r-tree structure called "rt", to deserialize
127346** all nodes, a statement like:
127347**
127348**   SELECT rtreenode(2, data) FROM rt_node;
127349**
127350** The human readable string takes the form of a Tcl list with one
127351** entry for each cell in the r-tree node. Each entry is itself a
127352** list, containing the 8-byte rowid/pageno followed by the
127353** <num-dimension>*2 coordinates.
127354*/
127355static void rtreenode(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){
127356  char *zText = 0;
127357  RtreeNode node;
127358  Rtree tree;
127359  int ii;
127360
127361  UNUSED_PARAMETER(nArg);
127362  memset(&node, 0, sizeof(RtreeNode));
127363  memset(&tree, 0, sizeof(Rtree));
127364  tree.nDim = sqlite3_value_int(apArg[0]);
127365  tree.nBytesPerCell = 8 + 8 * tree.nDim;
127366  node.zData = (u8 *)sqlite3_value_blob(apArg[1]);
127367
127368  for(ii=0; ii<NCELL(&node); ii++){
127369    char zCell[512];
127370    int nCell = 0;
127371    RtreeCell cell;
127372    int jj;
127373
127374    nodeGetCell(&tree, &node, ii, &cell);
127375    sqlite3_snprintf(512-nCell,&zCell[nCell],"%lld", cell.iRowid);
127376    nCell = strlen(zCell);
127377    for(jj=0; jj<tree.nDim*2; jj++){
127378      sqlite3_snprintf(512-nCell,&zCell[nCell]," %f",(double)cell.aCoord[jj].f);
127379      nCell = strlen(zCell);
127380    }
127381
127382    if( zText ){
127383      char *zTextNew = sqlite3_mprintf("%s {%s}", zText, zCell);
127384      sqlite3_free(zText);
127385      zText = zTextNew;
127386    }else{
127387      zText = sqlite3_mprintf("{%s}", zCell);
127388    }
127389  }
127390
127391  sqlite3_result_text(ctx, zText, -1, sqlite3_free);
127392}
127393
127394static void rtreedepth(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){
127395  UNUSED_PARAMETER(nArg);
127396  if( sqlite3_value_type(apArg[0])!=SQLITE_BLOB
127397   || sqlite3_value_bytes(apArg[0])<2
127398  ){
127399    sqlite3_result_error(ctx, "Invalid argument to rtreedepth()", -1);
127400  }else{
127401    u8 *zBlob = (u8 *)sqlite3_value_blob(apArg[0]);
127402    sqlite3_result_int(ctx, readInt16(zBlob));
127403  }
127404}
127405
127406/*
127407** Register the r-tree module with database handle db. This creates the
127408** virtual table module "rtree" and the debugging/analysis scalar
127409** function "rtreenode".
127410*/
127411SQLITE_PRIVATE int sqlite3RtreeInit(sqlite3 *db){
127412  const int utf8 = SQLITE_UTF8;
127413  int rc;
127414
127415  rc = sqlite3_create_function(db, "rtreenode", 2, utf8, 0, rtreenode, 0, 0);
127416  if( rc==SQLITE_OK ){
127417    rc = sqlite3_create_function(db, "rtreedepth", 1, utf8, 0,rtreedepth, 0, 0);
127418  }
127419  if( rc==SQLITE_OK ){
127420    void *c = (void *)RTREE_COORD_REAL32;
127421    rc = sqlite3_create_module_v2(db, "rtree", &rtreeModule, c, 0);
127422  }
127423  if( rc==SQLITE_OK ){
127424    void *c = (void *)RTREE_COORD_INT32;
127425    rc = sqlite3_create_module_v2(db, "rtree_i32", &rtreeModule, c, 0);
127426  }
127427
127428  return rc;
127429}
127430
127431/*
127432** A version of sqlite3_free() that can be used as a callback. This is used
127433** in two places - as the destructor for the blob value returned by the
127434** invocation of a geometry function, and as the destructor for the geometry
127435** functions themselves.
127436*/
127437static void doSqlite3Free(void *p){
127438  sqlite3_free(p);
127439}
127440
127441/*
127442** Each call to sqlite3_rtree_geometry_callback() creates an ordinary SQLite
127443** scalar user function. This C function is the callback used for all such
127444** registered SQL functions.
127445**
127446** The scalar user functions return a blob that is interpreted by r-tree
127447** table MATCH operators.
127448*/
127449static void geomCallback(sqlite3_context *ctx, int nArg, sqlite3_value **aArg){
127450  RtreeGeomCallback *pGeomCtx = (RtreeGeomCallback *)sqlite3_user_data(ctx);
127451  RtreeMatchArg *pBlob;
127452  int nBlob;
127453
127454  nBlob = sizeof(RtreeMatchArg) + (nArg-1)*sizeof(double);
127455  pBlob = (RtreeMatchArg *)sqlite3_malloc(nBlob);
127456  if( !pBlob ){
127457    sqlite3_result_error_nomem(ctx);
127458  }else{
127459    int i;
127460    pBlob->magic = RTREE_GEOMETRY_MAGIC;
127461    pBlob->xGeom = pGeomCtx->xGeom;
127462    pBlob->pContext = pGeomCtx->pContext;
127463    pBlob->nParam = nArg;
127464    for(i=0; i<nArg; i++){
127465      pBlob->aParam[i] = sqlite3_value_double(aArg[i]);
127466    }
127467    sqlite3_result_blob(ctx, pBlob, nBlob, doSqlite3Free);
127468  }
127469}
127470
127471/*
127472** Register a new geometry function for use with the r-tree MATCH operator.
127473*/
127474SQLITE_API int sqlite3_rtree_geometry_callback(
127475  sqlite3 *db,
127476  const char *zGeom,
127477  int (*xGeom)(sqlite3_rtree_geometry *, int, double *, int *),
127478  void *pContext
127479){
127480  RtreeGeomCallback *pGeomCtx;      /* Context object for new user-function */
127481
127482  /* Allocate and populate the context object. */
127483  pGeomCtx = (RtreeGeomCallback *)sqlite3_malloc(sizeof(RtreeGeomCallback));
127484  if( !pGeomCtx ) return SQLITE_NOMEM;
127485  pGeomCtx->xGeom = xGeom;
127486  pGeomCtx->pContext = pContext;
127487
127488  /* Create the new user-function. Register a destructor function to delete
127489  ** the context object when it is no longer required.  */
127490  return sqlite3_create_function_v2(db, zGeom, -1, SQLITE_ANY,
127491      (void *)pGeomCtx, geomCallback, 0, 0, doSqlite3Free
127492  );
127493}
127494
127495#if !SQLITE_CORE
127496SQLITE_API int sqlite3_extension_init(
127497  sqlite3 *db,
127498  char **pzErrMsg,
127499  const sqlite3_api_routines *pApi
127500){
127501  SQLITE_EXTENSION_INIT2(pApi)
127502  return sqlite3RtreeInit(db);
127503}
127504#endif
127505
127506#endif
127507
127508/************** End of rtree.c ***********************************************/
127509/************** Begin file icu.c *********************************************/
127510/*
127511** 2007 May 6
127512**
127513** The author disclaims copyright to this source code.  In place of
127514** a legal notice, here is a blessing:
127515**
127516**    May you do good and not evil.
127517**    May you find forgiveness for yourself and forgive others.
127518**    May you share freely, never taking more than you give.
127519**
127520*************************************************************************
127521** $Id: icu.c,v 1.7 2007/12/13 21:54:11 drh Exp $
127522**
127523** This file implements an integration between the ICU library
127524** ("International Components for Unicode", an open-source library
127525** for handling unicode data) and SQLite. The integration uses
127526** ICU to provide the following to SQLite:
127527**
127528**   * An implementation of the SQL regexp() function (and hence REGEXP
127529**     operator) using the ICU uregex_XX() APIs.
127530**
127531**   * Implementations of the SQL scalar upper() and lower() functions
127532**     for case mapping.
127533**
127534**   * Integration of ICU and SQLite collation seqences.
127535**
127536**   * An implementation of the LIKE operator that uses ICU to
127537**     provide case-independent matching.
127538*/
127539
127540#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_ICU)
127541
127542/* Include ICU headers */
127543#include <unicode/utypes.h>
127544#include <unicode/uregex.h>
127545#include <unicode/ustring.h>
127546#include <unicode/ucol.h>
127547
127548
127549#ifndef SQLITE_CORE
127550  SQLITE_EXTENSION_INIT1
127551#else
127552#endif
127553
127554/*
127555** Maximum length (in bytes) of the pattern in a LIKE or GLOB
127556** operator.
127557*/
127558#ifndef SQLITE_MAX_LIKE_PATTERN_LENGTH
127559# define SQLITE_MAX_LIKE_PATTERN_LENGTH 50000
127560#endif
127561
127562/*
127563** Version of sqlite3_free() that is always a function, never a macro.
127564*/
127565static void xFree(void *p){
127566  sqlite3_free(p);
127567}
127568
127569/*
127570** Compare two UTF-8 strings for equality where the first string is
127571** a "LIKE" expression. Return true (1) if they are the same and
127572** false (0) if they are different.
127573*/
127574static int icuLikeCompare(
127575  const uint8_t *zPattern,   /* LIKE pattern */
127576  const uint8_t *zString,    /* The UTF-8 string to compare against */
127577  const UChar32 uEsc         /* The escape character */
127578){
127579  static const int MATCH_ONE = (UChar32)'_';
127580  static const int MATCH_ALL = (UChar32)'%';
127581
127582  int iPattern = 0;       /* Current byte index in zPattern */
127583  int iString = 0;        /* Current byte index in zString */
127584
127585  int prevEscape = 0;     /* True if the previous character was uEsc */
127586
127587  while( zPattern[iPattern]!=0 ){
127588
127589    /* Read (and consume) the next character from the input pattern. */
127590    UChar32 uPattern;
127591    U8_NEXT_UNSAFE(zPattern, iPattern, uPattern);
127592    assert(uPattern!=0);
127593
127594    /* There are now 4 possibilities:
127595    **
127596    **     1. uPattern is an unescaped match-all character "%",
127597    **     2. uPattern is an unescaped match-one character "_",
127598    **     3. uPattern is an unescaped escape character, or
127599    **     4. uPattern is to be handled as an ordinary character
127600    */
127601    if( !prevEscape && uPattern==MATCH_ALL ){
127602      /* Case 1. */
127603      uint8_t c;
127604
127605      /* Skip any MATCH_ALL or MATCH_ONE characters that follow a
127606      ** MATCH_ALL. For each MATCH_ONE, skip one character in the
127607      ** test string.
127608      */
127609      while( (c=zPattern[iPattern]) == MATCH_ALL || c == MATCH_ONE ){
127610        if( c==MATCH_ONE ){
127611          if( zString[iString]==0 ) return 0;
127612          U8_FWD_1_UNSAFE(zString, iString);
127613        }
127614        iPattern++;
127615      }
127616
127617      if( zPattern[iPattern]==0 ) return 1;
127618
127619      while( zString[iString] ){
127620        if( icuLikeCompare(&zPattern[iPattern], &zString[iString], uEsc) ){
127621          return 1;
127622        }
127623        U8_FWD_1_UNSAFE(zString, iString);
127624      }
127625      return 0;
127626
127627    }else if( !prevEscape && uPattern==MATCH_ONE ){
127628      /* Case 2. */
127629      if( zString[iString]==0 ) return 0;
127630      U8_FWD_1_UNSAFE(zString, iString);
127631
127632    }else if( !prevEscape && uPattern==uEsc){
127633      /* Case 3. */
127634      prevEscape = 1;
127635
127636    }else{
127637      /* Case 4. */
127638      UChar32 uString;
127639      U8_NEXT_UNSAFE(zString, iString, uString);
127640      uString = u_foldCase(uString, U_FOLD_CASE_DEFAULT);
127641      uPattern = u_foldCase(uPattern, U_FOLD_CASE_DEFAULT);
127642      if( uString!=uPattern ){
127643        return 0;
127644      }
127645      prevEscape = 0;
127646    }
127647  }
127648
127649  return zString[iString]==0;
127650}
127651
127652/*
127653** Implementation of the like() SQL function.  This function implements
127654** the build-in LIKE operator.  The first argument to the function is the
127655** pattern and the second argument is the string.  So, the SQL statements:
127656**
127657**       A LIKE B
127658**
127659** is implemented as like(B, A). If there is an escape character E,
127660**
127661**       A LIKE B ESCAPE E
127662**
127663** is mapped to like(B, A, E).
127664*/
127665static void icuLikeFunc(
127666  sqlite3_context *context,
127667  int argc,
127668  sqlite3_value **argv
127669){
127670  const unsigned char *zA = sqlite3_value_text(argv[0]);
127671  const unsigned char *zB = sqlite3_value_text(argv[1]);
127672  UChar32 uEsc = 0;
127673
127674  /* Limit the length of the LIKE or GLOB pattern to avoid problems
127675  ** of deep recursion and N*N behavior in patternCompare().
127676  */
127677  if( sqlite3_value_bytes(argv[0])>SQLITE_MAX_LIKE_PATTERN_LENGTH ){
127678    sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1);
127679    return;
127680  }
127681
127682
127683  if( argc==3 ){
127684    /* The escape character string must consist of a single UTF-8 character.
127685    ** Otherwise, return an error.
127686    */
127687    int nE= sqlite3_value_bytes(argv[2]);
127688    const unsigned char *zE = sqlite3_value_text(argv[2]);
127689    int i = 0;
127690    if( zE==0 ) return;
127691    U8_NEXT(zE, i, nE, uEsc);
127692    if( i!=nE){
127693      sqlite3_result_error(context,
127694          "ESCAPE expression must be a single character", -1);
127695      return;
127696    }
127697  }
127698
127699  if( zA && zB ){
127700    sqlite3_result_int(context, icuLikeCompare(zA, zB, uEsc));
127701  }
127702}
127703
127704/*
127705** This function is called when an ICU function called from within
127706** the implementation of an SQL scalar function returns an error.
127707**
127708** The scalar function context passed as the first argument is
127709** loaded with an error message based on the following two args.
127710*/
127711static void icuFunctionError(
127712  sqlite3_context *pCtx,       /* SQLite scalar function context */
127713  const char *zName,           /* Name of ICU function that failed */
127714  UErrorCode e                 /* Error code returned by ICU function */
127715){
127716  char zBuf[128];
127717  sqlite3_snprintf(128, zBuf, "ICU error: %s(): %s", zName, u_errorName(e));
127718  zBuf[127] = '\0';
127719  sqlite3_result_error(pCtx, zBuf, -1);
127720}
127721
127722/*
127723** Function to delete compiled regexp objects. Registered as
127724** a destructor function with sqlite3_set_auxdata().
127725*/
127726static void icuRegexpDelete(void *p){
127727  URegularExpression *pExpr = (URegularExpression *)p;
127728  uregex_close(pExpr);
127729}
127730
127731/*
127732** Implementation of SQLite REGEXP operator. This scalar function takes
127733** two arguments. The first is a regular expression pattern to compile
127734** the second is a string to match against that pattern. If either
127735** argument is an SQL NULL, then NULL Is returned. Otherwise, the result
127736** is 1 if the string matches the pattern, or 0 otherwise.
127737**
127738** SQLite maps the regexp() function to the regexp() operator such
127739** that the following two are equivalent:
127740**
127741**     zString REGEXP zPattern
127742**     regexp(zPattern, zString)
127743**
127744** Uses the following ICU regexp APIs:
127745**
127746**     uregex_open()
127747**     uregex_matches()
127748**     uregex_close()
127749*/
127750static void icuRegexpFunc(sqlite3_context *p, int nArg, sqlite3_value **apArg){
127751  UErrorCode status = U_ZERO_ERROR;
127752  URegularExpression *pExpr;
127753  UBool res;
127754  const UChar *zString = sqlite3_value_text16(apArg[1]);
127755
127756  (void)nArg;  /* Unused parameter */
127757
127758  /* If the left hand side of the regexp operator is NULL,
127759  ** then the result is also NULL.
127760  */
127761  if( !zString ){
127762    return;
127763  }
127764
127765  pExpr = sqlite3_get_auxdata(p, 0);
127766  if( !pExpr ){
127767    const UChar *zPattern = sqlite3_value_text16(apArg[0]);
127768    if( !zPattern ){
127769      return;
127770    }
127771    pExpr = uregex_open(zPattern, -1, 0, 0, &status);
127772
127773    if( U_SUCCESS(status) ){
127774      sqlite3_set_auxdata(p, 0, pExpr, icuRegexpDelete);
127775    }else{
127776      assert(!pExpr);
127777      icuFunctionError(p, "uregex_open", status);
127778      return;
127779    }
127780  }
127781
127782  /* Configure the text that the regular expression operates on. */
127783  uregex_setText(pExpr, zString, -1, &status);
127784  if( !U_SUCCESS(status) ){
127785    icuFunctionError(p, "uregex_setText", status);
127786    return;
127787  }
127788
127789  /* Attempt the match */
127790  res = uregex_matches(pExpr, 0, &status);
127791  if( !U_SUCCESS(status) ){
127792    icuFunctionError(p, "uregex_matches", status);
127793    return;
127794  }
127795
127796  /* Set the text that the regular expression operates on to a NULL
127797  ** pointer. This is not really necessary, but it is tidier than
127798  ** leaving the regular expression object configured with an invalid
127799  ** pointer after this function returns.
127800  */
127801  uregex_setText(pExpr, 0, 0, &status);
127802
127803  /* Return 1 or 0. */
127804  sqlite3_result_int(p, res ? 1 : 0);
127805}
127806
127807/*
127808** Implementations of scalar functions for case mapping - upper() and
127809** lower(). Function upper() converts its input to upper-case (ABC).
127810** Function lower() converts to lower-case (abc).
127811**
127812** ICU provides two types of case mapping, "general" case mapping and
127813** "language specific". Refer to ICU documentation for the differences
127814** between the two.
127815**
127816** To utilise "general" case mapping, the upper() or lower() scalar
127817** functions are invoked with one argument:
127818**
127819**     upper('ABC') -> 'abc'
127820**     lower('abc') -> 'ABC'
127821**
127822** To access ICU "language specific" case mapping, upper() or lower()
127823** should be invoked with two arguments. The second argument is the name
127824** of the locale to use. Passing an empty string ("") or SQL NULL value
127825** as the second argument is the same as invoking the 1 argument version
127826** of upper() or lower().
127827**
127828**     lower('I', 'en_us') -> 'i'
127829**     lower('I', 'tr_tr') -> 'ı' (small dotless i)
127830**
127831** http://www.icu-project.org/userguide/posix.html#case_mappings
127832*/
127833static void icuCaseFunc16(sqlite3_context *p, int nArg, sqlite3_value **apArg){
127834  const UChar *zInput;
127835  UChar *zOutput;
127836  int nInput;
127837  int nOutput;
127838
127839  UErrorCode status = U_ZERO_ERROR;
127840  const char *zLocale = 0;
127841
127842  assert(nArg==1 || nArg==2);
127843  if( nArg==2 ){
127844    zLocale = (const char *)sqlite3_value_text(apArg[1]);
127845  }
127846
127847  zInput = sqlite3_value_text16(apArg[0]);
127848  if( !zInput ){
127849    return;
127850  }
127851  nInput = sqlite3_value_bytes16(apArg[0]);
127852
127853  nOutput = nInput * 2 + 2;
127854  zOutput = sqlite3_malloc(nOutput);
127855  if( !zOutput ){
127856    return;
127857  }
127858
127859  if( sqlite3_user_data(p) ){
127860    u_strToUpper(zOutput, nOutput/2, zInput, nInput/2, zLocale, &status);
127861  }else{
127862    u_strToLower(zOutput, nOutput/2, zInput, nInput/2, zLocale, &status);
127863  }
127864
127865  if( !U_SUCCESS(status) ){
127866    icuFunctionError(p, "u_strToLower()/u_strToUpper", status);
127867    return;
127868  }
127869
127870  sqlite3_result_text16(p, zOutput, -1, xFree);
127871}
127872
127873/*
127874** Collation sequence destructor function. The pCtx argument points to
127875** a UCollator structure previously allocated using ucol_open().
127876*/
127877static void icuCollationDel(void *pCtx){
127878  UCollator *p = (UCollator *)pCtx;
127879  ucol_close(p);
127880}
127881
127882/*
127883** Collation sequence comparison function. The pCtx argument points to
127884** a UCollator structure previously allocated using ucol_open().
127885*/
127886static int icuCollationColl(
127887  void *pCtx,
127888  int nLeft,
127889  const void *zLeft,
127890  int nRight,
127891  const void *zRight
127892){
127893  UCollationResult res;
127894  UCollator *p = (UCollator *)pCtx;
127895  res = ucol_strcoll(p, (UChar *)zLeft, nLeft/2, (UChar *)zRight, nRight/2);
127896  switch( res ){
127897    case UCOL_LESS:    return -1;
127898    case UCOL_GREATER: return +1;
127899    case UCOL_EQUAL:   return 0;
127900  }
127901  assert(!"Unexpected return value from ucol_strcoll()");
127902  return 0;
127903}
127904
127905/*
127906** Implementation of the scalar function icu_load_collation().
127907**
127908** This scalar function is used to add ICU collation based collation
127909** types to an SQLite database connection. It is intended to be called
127910** as follows:
127911**
127912**     SELECT icu_load_collation(<locale>, <collation-name>);
127913**
127914** Where <locale> is a string containing an ICU locale identifier (i.e.
127915** "en_AU", "tr_TR" etc.) and <collation-name> is the name of the
127916** collation sequence to create.
127917*/
127918static void icuLoadCollation(
127919  sqlite3_context *p,
127920  int nArg,
127921  sqlite3_value **apArg
127922){
127923  sqlite3 *db = (sqlite3 *)sqlite3_user_data(p);
127924  UErrorCode status = U_ZERO_ERROR;
127925  const char *zLocale;      /* Locale identifier - (eg. "jp_JP") */
127926  const char *zName;        /* SQL Collation sequence name (eg. "japanese") */
127927  UCollator *pUCollator;    /* ICU library collation object */
127928  int rc;                   /* Return code from sqlite3_create_collation_x() */
127929
127930  assert(nArg==2);
127931  zLocale = (const char *)sqlite3_value_text(apArg[0]);
127932  zName = (const char *)sqlite3_value_text(apArg[1]);
127933
127934  if( !zLocale || !zName ){
127935    return;
127936  }
127937
127938  pUCollator = ucol_open(zLocale, &status);
127939  if( !U_SUCCESS(status) ){
127940    icuFunctionError(p, "ucol_open", status);
127941    return;
127942  }
127943  assert(p);
127944
127945  rc = sqlite3_create_collation_v2(db, zName, SQLITE_UTF16, (void *)pUCollator,
127946      icuCollationColl, icuCollationDel
127947  );
127948  if( rc!=SQLITE_OK ){
127949    ucol_close(pUCollator);
127950    sqlite3_result_error(p, "Error registering collation function", -1);
127951  }
127952}
127953
127954/*
127955** Register the ICU extension functions with database db.
127956*/
127957SQLITE_PRIVATE int sqlite3IcuInit(sqlite3 *db){
127958  struct IcuScalar {
127959    const char *zName;                        /* Function name */
127960    int nArg;                                 /* Number of arguments */
127961    int enc;                                  /* Optimal text encoding */
127962    void *pContext;                           /* sqlite3_user_data() context */
127963    void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
127964  } scalars[] = {
127965    {"regexp", 2, SQLITE_ANY,          0, icuRegexpFunc},
127966
127967    {"lower",  1, SQLITE_UTF16,        0, icuCaseFunc16},
127968    {"lower",  2, SQLITE_UTF16,        0, icuCaseFunc16},
127969    {"upper",  1, SQLITE_UTF16, (void*)1, icuCaseFunc16},
127970    {"upper",  2, SQLITE_UTF16, (void*)1, icuCaseFunc16},
127971
127972    {"lower",  1, SQLITE_UTF8,         0, icuCaseFunc16},
127973    {"lower",  2, SQLITE_UTF8,         0, icuCaseFunc16},
127974    {"upper",  1, SQLITE_UTF8,  (void*)1, icuCaseFunc16},
127975    {"upper",  2, SQLITE_UTF8,  (void*)1, icuCaseFunc16},
127976
127977    {"like",   2, SQLITE_UTF8,         0, icuLikeFunc},
127978    {"like",   3, SQLITE_UTF8,         0, icuLikeFunc},
127979
127980    {"icu_load_collation",  2, SQLITE_UTF8, (void*)db, icuLoadCollation},
127981  };
127982
127983  int rc = SQLITE_OK;
127984  int i;
127985
127986  for(i=0; rc==SQLITE_OK && i<(int)(sizeof(scalars)/sizeof(scalars[0])); i++){
127987    struct IcuScalar *p = &scalars[i];
127988    rc = sqlite3_create_function(
127989        db, p->zName, p->nArg, p->enc, p->pContext, p->xFunc, 0, 0
127990    );
127991  }
127992
127993  return rc;
127994}
127995
127996#if !SQLITE_CORE
127997SQLITE_API int sqlite3_extension_init(
127998  sqlite3 *db,
127999  char **pzErrMsg,
128000  const sqlite3_api_routines *pApi
128001){
128002  SQLITE_EXTENSION_INIT2(pApi)
128003  return sqlite3IcuInit(db);
128004}
128005#endif
128006
128007#endif
128008
128009/************** End of icu.c *************************************************/
128010/************** Begin file fts3_icu.c ****************************************/
128011/*
128012** 2007 June 22
128013**
128014** The author disclaims copyright to this source code.  In place of
128015** a legal notice, here is a blessing:
128016**
128017**    May you do good and not evil.
128018**    May you find forgiveness for yourself and forgive others.
128019**    May you share freely, never taking more than you give.
128020**
128021*************************************************************************
128022** This file implements a tokenizer for fts3 based on the ICU library.
128023**
128024** $Id: fts3_icu.c,v 1.3 2008/09/01 18:34:20 danielk1977 Exp $
128025*/
128026
128027#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
128028#ifdef SQLITE_ENABLE_ICU
128029
128030
128031#include <unicode/ubrk.h>
128032#include <unicode/utf16.h>
128033
128034typedef struct IcuTokenizer IcuTokenizer;
128035typedef struct IcuCursor IcuCursor;
128036
128037struct IcuTokenizer {
128038  sqlite3_tokenizer base;
128039  char *zLocale;
128040};
128041
128042struct IcuCursor {
128043  sqlite3_tokenizer_cursor base;
128044
128045  UBreakIterator *pIter;      /* ICU break-iterator object */
128046  int nChar;                  /* Number of UChar elements in pInput */
128047  UChar *aChar;               /* Copy of input using utf-16 encoding */
128048  int *aOffset;               /* Offsets of each character in utf-8 input */
128049
128050  int nBuffer;
128051  char *zBuffer;
128052
128053  int iToken;
128054};
128055
128056/*
128057** Create a new tokenizer instance.
128058*/
128059static int icuCreate(
128060  int argc,                            /* Number of entries in argv[] */
128061  const char * const *argv,            /* Tokenizer creation arguments */
128062  sqlite3_tokenizer **ppTokenizer      /* OUT: Created tokenizer */
128063){
128064  IcuTokenizer *p;
128065  int n = 0;
128066
128067  if( argc>0 ){
128068    n = strlen(argv[0])+1;
128069  }
128070  p = (IcuTokenizer *)sqlite3_malloc(sizeof(IcuTokenizer)+n);
128071  if( !p ){
128072    return SQLITE_NOMEM;
128073  }
128074  memset(p, 0, sizeof(IcuTokenizer));
128075
128076  if( n ){
128077    p->zLocale = (char *)&p[1];
128078    memcpy(p->zLocale, argv[0], n);
128079  }
128080
128081  *ppTokenizer = (sqlite3_tokenizer *)p;
128082
128083  return SQLITE_OK;
128084}
128085
128086/*
128087** Destroy a tokenizer
128088*/
128089static int icuDestroy(sqlite3_tokenizer *pTokenizer){
128090  IcuTokenizer *p = (IcuTokenizer *)pTokenizer;
128091  sqlite3_free(p);
128092  return SQLITE_OK;
128093}
128094
128095/*
128096** Prepare to begin tokenizing a particular string.  The input
128097** string to be tokenized is pInput[0..nBytes-1].  A cursor
128098** used to incrementally tokenize this string is returned in
128099** *ppCursor.
128100*/
128101static int icuOpen(
128102  sqlite3_tokenizer *pTokenizer,         /* The tokenizer */
128103  const char *zInput,                    /* Input string */
128104  int nInput,                            /* Length of zInput in bytes */
128105  sqlite3_tokenizer_cursor **ppCursor    /* OUT: Tokenization cursor */
128106){
128107  IcuTokenizer *p = (IcuTokenizer *)pTokenizer;
128108  IcuCursor *pCsr;
128109
128110  const int32_t opt = U_FOLD_CASE_DEFAULT;
128111  UErrorCode status = U_ZERO_ERROR;
128112  int nChar;
128113
128114  UChar32 c;
128115  int iInput = 0;
128116  int iOut = 0;
128117
128118  *ppCursor = 0;
128119
128120  if( nInput<0 ){
128121    nInput = strlen(zInput);
128122  }
128123  nChar = nInput+1;
128124  pCsr = (IcuCursor *)sqlite3_malloc(
128125      sizeof(IcuCursor) +                /* IcuCursor */
128126      (nChar+1) * sizeof(int) +          /* IcuCursor.aOffset[] */
128127      nChar * sizeof(UChar)              /* IcuCursor.aChar[] */
128128  );
128129  if( !pCsr ){
128130    return SQLITE_NOMEM;
128131  }
128132  memset(pCsr, 0, sizeof(IcuCursor));
128133  pCsr->aOffset = (int *)&pCsr[1];
128134  pCsr->aChar = (UChar *)&pCsr->aOffset[nChar+1];
128135
128136  pCsr->aOffset[iOut] = iInput;
128137  U8_NEXT(zInput, iInput, nInput, c);
128138  while( c>0 ){
128139    int isError = 0;
128140    c = u_foldCase(c, opt);
128141    U16_APPEND(pCsr->aChar, iOut, nChar, c, isError);
128142    if( isError ){
128143      sqlite3_free(pCsr);
128144      return SQLITE_ERROR;
128145    }
128146    pCsr->aOffset[iOut] = iInput;
128147
128148    if( iInput<nInput ){
128149      U8_NEXT(zInput, iInput, nInput, c);
128150    }else{
128151      c = 0;
128152    }
128153  }
128154
128155  pCsr->pIter = ubrk_open(UBRK_WORD, p->zLocale, pCsr->aChar, iOut, &status);
128156  if( !U_SUCCESS(status) ){
128157    sqlite3_free(pCsr);
128158    return SQLITE_ERROR;
128159  }
128160  pCsr->nChar = iOut;
128161
128162  ubrk_first(pCsr->pIter);
128163  *ppCursor = (sqlite3_tokenizer_cursor *)pCsr;
128164  return SQLITE_OK;
128165}
128166
128167/*
128168** Close a tokenization cursor previously opened by a call to icuOpen().
128169*/
128170static int icuClose(sqlite3_tokenizer_cursor *pCursor){
128171  IcuCursor *pCsr = (IcuCursor *)pCursor;
128172  ubrk_close(pCsr->pIter);
128173  sqlite3_free(pCsr->zBuffer);
128174  sqlite3_free(pCsr);
128175  return SQLITE_OK;
128176}
128177
128178/*
128179** Extract the next token from a tokenization cursor.
128180*/
128181static int icuNext(
128182  sqlite3_tokenizer_cursor *pCursor,  /* Cursor returned by simpleOpen */
128183  const char **ppToken,               /* OUT: *ppToken is the token text */
128184  int *pnBytes,                       /* OUT: Number of bytes in token */
128185  int *piStartOffset,                 /* OUT: Starting offset of token */
128186  int *piEndOffset,                   /* OUT: Ending offset of token */
128187  int *piPosition                     /* OUT: Position integer of token */
128188){
128189  IcuCursor *pCsr = (IcuCursor *)pCursor;
128190
128191  int iStart = 0;
128192  int iEnd = 0;
128193  int nByte = 0;
128194
128195  while( iStart==iEnd ){
128196    UChar32 c;
128197
128198    iStart = ubrk_current(pCsr->pIter);
128199    iEnd = ubrk_next(pCsr->pIter);
128200    if( iEnd==UBRK_DONE ){
128201      return SQLITE_DONE;
128202    }
128203
128204    while( iStart<iEnd ){
128205      int iWhite = iStart;
128206      U16_NEXT(pCsr->aChar, iWhite, pCsr->nChar, c);
128207      if( u_isspace(c) ){
128208        iStart = iWhite;
128209      }else{
128210        break;
128211      }
128212    }
128213    assert(iStart<=iEnd);
128214  }
128215
128216  do {
128217    UErrorCode status = U_ZERO_ERROR;
128218    if( nByte ){
128219      char *zNew = sqlite3_realloc(pCsr->zBuffer, nByte);
128220      if( !zNew ){
128221        return SQLITE_NOMEM;
128222      }
128223      pCsr->zBuffer = zNew;
128224      pCsr->nBuffer = nByte;
128225    }
128226
128227    u_strToUTF8(
128228        pCsr->zBuffer, pCsr->nBuffer, &nByte,    /* Output vars */
128229        &pCsr->aChar[iStart], iEnd-iStart,       /* Input vars */
128230        &status                                  /* Output success/failure */
128231    );
128232  } while( nByte>pCsr->nBuffer );
128233
128234  *ppToken = pCsr->zBuffer;
128235  *pnBytes = nByte;
128236  *piStartOffset = pCsr->aOffset[iStart];
128237  *piEndOffset = pCsr->aOffset[iEnd];
128238  *piPosition = pCsr->iToken++;
128239
128240  return SQLITE_OK;
128241}
128242
128243/*
128244** The set of routines that implement the simple tokenizer
128245*/
128246static const sqlite3_tokenizer_module icuTokenizerModule = {
128247  0,                           /* iVersion */
128248  icuCreate,                   /* xCreate  */
128249  icuDestroy,                  /* xCreate  */
128250  icuOpen,                     /* xOpen    */
128251  icuClose,                    /* xClose   */
128252  icuNext,                     /* xNext    */
128253};
128254
128255/*
128256** Set *ppModule to point at the implementation of the ICU tokenizer.
128257*/
128258SQLITE_PRIVATE void sqlite3Fts3IcuTokenizerModule(
128259  sqlite3_tokenizer_module const**ppModule
128260){
128261  *ppModule = &icuTokenizerModule;
128262}
128263
128264#endif /* defined(SQLITE_ENABLE_ICU) */
128265#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
128266
128267/************** End of fts3_icu.c ********************************************/
128268